1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Administration module
36 #======================================================================
43 use List::MoreUtils qw(any);
50 use SL::GenericTranslations;
55 $main::lxdebug->enter_sub();
57 # fetch chart-related data and set form fields
58 # get_account is called by add_account in am.pl
59 # always sets $form->{TAXKEY} and default_accounts
60 # loads chart data when $form->{id} is passed
62 my ($self, $myconfig, $form) = @_;
64 # get default accounts
65 map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
68 my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
70 foreach my $tk ( @{$taxes} ) {
71 push @{ $form->{TAXKEY} }, { id => $tk->id,
72 chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
73 taxkey => $tk->taxkey,
74 tax => $tk->id . '--' . $tk->taxkey,
81 my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
83 my @chart_fields = qw(accno description charttype category link pos_bilanz
84 pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik);
85 foreach my $cf ( @chart_fields ) {
86 $form->{"$cf"} = $chart_obj->$cf;
89 my $active_taxkey = $chart_obj->get_active_taxkey;
90 $form->{$_} = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
91 $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
93 # check if there are any transactions for this chart
94 $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
96 # check if new account is active
97 # The old sql query was broken since at least 2006 and always returned 0
98 $form->{new_chart_valid} = $chart_obj->new_chart_valid;
100 # get the taxkeys of the account
101 $form->{ACCOUNT_TAXKEYS} = [];
102 foreach my $taxkey ( @{ $chart_obj->taxkeys } ) {
103 push @{ $form->{ACCOUNT_TAXKEYS} }, { id => $taxkey->id,
104 chart_id => $taxkey->chart_id,
105 tax_id => $taxkey->tax_id,
106 taxkey_id => $taxkey->taxkey_id,
107 pos_ustva => $taxkey->pos_ustva,
108 startdate => $taxkey->startdate->to_kivitendo,
109 taxdescription => $taxkey->tax->taxdescription,
110 rate => $taxkey->tax->rate,
111 accno => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
115 # get new accounts (Folgekonto). Find all charts with the same link
116 $form->{NEWACCOUNT} = $chart_obj->db->dbh->selectall_arrayref('select id, accno,description from chart where link = ? order by accno', {Slice => {}}, $chart_obj->link);
118 } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
119 $form->{orphaned} = 1;
122 $main::lxdebug->leave_sub();
126 my ($self, $myconfig, $form) = @_;
127 $main::lxdebug->enter_sub();
129 my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
131 $::lxdebug->leave_sub;
136 # TODO: it should be forbidden to change an account to a heading if there
137 # have been bookings to this account in the past
139 my ($self, $myconfig, $form) = @_;
141 my $dbh = SL::DB->client->dbh;
143 for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
144 $form->{$form->{$_}} = $form->{$_} if $form->{$_};
147 # sanity check, can't have AR with AR_...
148 if ($form->{AR} || $form->{AP} || $form->{IC}) {
149 if (any { $form->{$_} } qw(AR_amount AR_tax AR_paid AP_amount AP_tax AP_paid IC_sale IC_cogs IC_taxpart IC_income IC_expense IC_taxservice)) {
150 $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
154 my @link_order = qw(AR AR_amount AR_tax AR_paid AP AP_amount AP_tax AP_paid IC IC_sale IC_cogs IC_taxpart IC_income IC_expense IC_taxservice);
155 $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
157 # strip blanks from accno
158 map { $form->{$_} =~ s/ //g; } qw(accno);
160 # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
161 map { $form->{$_} =~ s/\h+/ /g } qw(description);
165 if ($form->{id} eq "NULL") {
174 my @values = ($form->{accno});
177 $query .= ' AND NOT id = ?';
178 push(@values, $form->{id});
181 my ($accno) = selectrow_query($form, $dbh, $query, @values);
184 $form->error($::locale->text('Account number not unique!'));
188 if (!$form->{id} || $form->{id} eq "") {
189 $query = qq|SELECT nextval('id')|;
190 ($form->{"id"}) = selectrow_query($form, $dbh, $query);
191 $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
192 do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
200 # if charttype is heading make sure certain values are empty
201 # specifically, if charttype is changed from an existing account, empty the
202 # fields unnecessary for headings, so that e.g. heading doesn't appear in
203 # drop-down menues due to still having a valid "link" entry
205 if ( $form->{charttype} eq 'H' ) {
207 $form->{pos_bwa} = '';
208 $form->{pos_bilanz} = '';
209 $form->{pos_eur} = '';
210 $form->{new_chart_id} = '';
211 $form->{valid_from} = '';
214 $query = qq|UPDATE chart SET
231 $form->{description},
235 conv_i($form->{pos_bwa}),
236 conv_i($form->{pos_bilanz}),
237 conv_i($form->{pos_eur}),
238 conv_i($form->{pos_er}),
239 conv_i($form->{new_chart_id}),
240 conv_date($form->{valid_from}),
241 ($form->{datevautomatik} eq 'T') ? 'true':'false',
248 do_query($form, $dbh, $query, @values);
254 my $MAX_TRIES = 10; # Maximum count of taxkeys in form
258 for $tk_count (0 .. $MAX_TRIES) {
262 # Check if the account already exists, else cancel
264 print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
266 last READTAXKEYS if ( $form->{'id'} == 0);
268 # check if there is a startdate
269 if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
274 # Add valid taxkeys into the array
277 id => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
278 tax_id => conv_i($form->{"taxkey_tax_$tk_count"}),
279 startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
280 chart_id => conv_i($form->{"id"}),
281 pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
282 delete => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
289 for my $j (0 .. $#taxkeys){
290 if ( defined $taxkeys[$j]{'id'} ){
293 if ($taxkeys[$j]{'delete'}){
295 DELETE FROM taxkeys WHERE id = ?
298 @values = ($taxkeys[$j]{'id'});
300 do_query($form, $dbh, $query, @values);
309 SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
317 $taxkeys[$j]{'tax_id'},
318 $taxkeys[$j]{'chart_id'},
319 $taxkeys[$j]{'tax_id'},
320 $taxkeys[$j]{'pos_ustva'},
321 $taxkeys[$j]{'startdate'},
324 do_query($form, $dbh, $query, @values);
330 INSERT INTO taxkeys (
337 VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
340 $taxkeys[$j]{'tax_id'},
341 $taxkeys[$j]{'chart_id'},
342 $taxkeys[$j]{'tax_id'},
343 $taxkeys[$j]{'pos_ustva'},
344 $taxkeys[$j]{'startdate'},
347 do_query($form, $dbh, $query, @values);
352 # Update chart.taxkey_id to the latest from taxkeys for this chart.
358 WHERE taxkeys.chart_id = chart.id
359 ORDER BY startdate DESC
365 do_query($form, $dbh, $query, $form->{id});
371 my ($self, $myconfig, $form) = @_;
372 $main::lxdebug->enter_sub();
374 my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
376 $::lxdebug->leave_sub;
380 sub _delete_account {
381 my ($self, $myconfig, $form) = @_;
383 my $dbh = SL::DB->client->dbh;
385 my $query = qq|SELECT count(*) FROM acc_trans a
386 WHERE a.chart_id = ?|;
387 my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
393 # set inventory_accno_id, income_accno_id, expense_accno_id to defaults
394 foreach my $type (qw(inventory income expense)) {
397 qq|SET ${type}_accno_id = (SELECT ${type}_accno_id FROM defaults) | .
398 qq|WHERE ${type}_accno_id = ?|;
399 do_query($form, $dbh, $query, $form->{id});
402 $query = qq|DELETE FROM tax
404 do_query($form, $dbh, $query, $form->{id});
406 # delete account taxkeys
407 $query = qq|DELETE FROM taxkeys
409 do_query($form, $dbh, $query, $form->{id});
411 # delete chart of account record
412 # last step delete chart, because we have a constraint
414 $query = qq|DELETE FROM chart
416 do_query($form, $dbh, $query, $form->{id});
422 $main::lxdebug->enter_sub();
424 my ($self, $myconfig, $form) = @_;
426 my $dbh = SL::DB->client->dbh;
428 my $query = qq|SELECT id, lead
432 my $sth = $dbh->prepare($query);
433 $sth->execute || $form->dberror($query);
435 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
436 push @{ $form->{ALL} }, $ref;
441 $main::lxdebug->leave_sub();
445 $main::lxdebug->enter_sub();
447 my ($self, $myconfig, $form) = @_;
449 my $dbh = SL::DB->client->dbh;
452 qq|SELECT l.id, l.lead | .
455 my $sth = $dbh->prepare($query);
456 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
458 my $ref = $sth->fetchrow_hashref("NAME_lc");
460 map { $form->{$_} = $ref->{$_} } keys %$ref;
464 $main::lxdebug->leave_sub();
468 $main::lxdebug->enter_sub();
470 my ($self, $myconfig, $form) = @_;
473 my $dbh = SL::DB->client->dbh;
475 my @values = ($form->{description});
476 # id is the old record
478 $query = qq|UPDATE leads SET
481 push(@values, $form->{id});
483 $query = qq|INSERT INTO leads
487 do_query($form, $dbh, $query, @values);
489 $main::lxdebug->leave_sub();
493 $main::lxdebug->enter_sub();
495 my ($self, $myconfig, $form) = @_;
498 SL::DB->client->with_transaction(sub {
499 $query = qq|DELETE FROM leads WHERE id = ?|;
500 do_query($form, SL::DB->client->dbh, $query, $form->{id});
503 $main::lxdebug->leave_sub();
507 $main::lxdebug->enter_sub();
509 my ($self, $myconfig, $form, $return_list) = @_;
511 my $dbh = SL::DB->client->dbh;
514 "SELECT id, description, template_code, article_code, " .
515 " output_numberformat, output_dateformat, output_longdates " .
516 "FROM language ORDER BY description";
518 my $sth = $dbh->prepare($query);
519 $sth->execute || $form->dberror($query);
523 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
524 push(@{ $ary }, $ref);
529 $main::lxdebug->leave_sub();
539 $main::lxdebug->enter_sub();
541 my ($self, $myconfig, $form) = @_;
543 my $dbh = SL::DB->client->dbh;
546 "SELECT description, template_code, article_code, " .
547 " output_numberformat, output_dateformat, output_longdates " .
548 "FROM language WHERE id = ?";
549 my $sth = $dbh->prepare($query);
550 $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
552 my $ref = $sth->fetchrow_hashref("NAME_lc");
554 map { $form->{$_} = $ref->{$_} } keys %$ref;
558 $main::lxdebug->leave_sub();
561 sub get_language_details {
562 $main::lxdebug->enter_sub();
564 my ($self, $myconfig, $form, $id) = @_;
566 my $dbh = SL::DB->client->dbh;
569 "SELECT template_code, " .
570 " output_numberformat, output_dateformat, output_longdates " .
571 "FROM language WHERE id = ?";
572 my @res = selectrow_query($form, $dbh, $query, $id);
574 $main::lxdebug->leave_sub();
580 $main::lxdebug->enter_sub();
582 my ($self, $myconfig, $form) = @_;
584 SL::DB->client->with_transaction(sub {
585 my $dbh = SL::DB->client->dbh;
586 my (@values, $query);
588 map({ push(@values, $form->{$_}); }
589 qw(description template_code article_code
590 output_numberformat output_dateformat output_longdates));
592 # id is the old record
595 "UPDATE language SET " .
596 " description = ?, template_code = ?, article_code = ?, " .
597 " output_numberformat = ?, output_dateformat = ?, " .
598 " output_longdates = ? " .
600 push(@values, $form->{id});
603 "INSERT INTO language (" .
604 " description, template_code, article_code, " .
605 " output_numberformat, output_dateformat, output_longdates" .
606 ") VALUES (?, ?, ?, ?, ?, ?)";
608 do_query($form, $dbh, $query, @values);
611 $main::lxdebug->leave_sub();
614 sub delete_language {
615 $main::lxdebug->enter_sub();
617 my ($self, $myconfig, $form) = @_;
620 SL::DB->client->with_transaction(sub {
621 my $dbh = SL::DB->client->dbh;
623 foreach my $table (qw(generic_translations units_language)) {
624 $query = qq|DELETE FROM $table WHERE language_id = ?|;
625 do_query($form, $dbh, $query, $form->{"id"});
628 $query = "DELETE FROM language WHERE id = ?";
629 do_query($form, $dbh, $query, $form->{"id"});
632 $main::lxdebug->leave_sub();
635 sub prepare_template_filename {
636 $main::lxdebug->enter_sub();
638 my ($self, $myconfig, $form) = @_;
640 my ($filename, $display_filename);
642 if ($form->{type} eq "stylesheet") {
643 $filename = "css/$myconfig->{stylesheet}";
644 $display_filename = $myconfig->{stylesheet};
647 $filename = $form->{formname};
649 if ($form->{language}) {
650 my ($id, $template_code) = split(/--/, $form->{language});
651 $filename .= "_${template_code}";
654 if ($form->{printer}) {
655 my ($id, $template_code) = split(/--/, $form->{printer});
656 $filename .= "_${template_code}";
659 $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
660 if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
661 $filename =~ s|.*/||;
663 $display_filename = $filename;
664 $filename = SL::DB::Default->get->templates . "/$filename";
667 $main::lxdebug->leave_sub();
669 return ($filename, $display_filename);
674 $main::lxdebug->enter_sub();
676 my ($self, $filename) = @_;
678 my ($content, $lines) = ("", 0);
682 if (open(TEMPLATE, $filename)) {
690 $content = Encode::decode('utf-8-strict', $content);
692 $main::lxdebug->leave_sub();
694 return ($content, $lines);
698 $main::lxdebug->enter_sub();
700 my ($self, $filename, $content) = @_;
706 if (open(TEMPLATE, ">", $filename)) {
707 $content = Encode::encode('utf-8-strict', $content);
708 $content =~ s/\r\n/\n/g;
709 print(TEMPLATE $content);
715 $main::lxdebug->leave_sub();
720 sub save_preferences {
721 $main::lxdebug->enter_sub();
723 my ($self, $form) = @_;
725 my $employee = SL::DB::Manager::Employee->find_by(login => $::myconfig{login});
726 $employee->update_attributes(name => $form->{name});
728 my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
729 $user->update_attributes(
731 %{ $user->config_values },
732 map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
735 $main::lxdebug->leave_sub();
741 $main::lxdebug->enter_sub();
746 my $myconfig = \%main::myconfig;
747 my $form = $main::form;
749 my $dbh = $params{dbh} || SL::DB->client->dbh;
751 my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
753 $defaults->{weightunit} ||= 'kg';
755 $main::lxdebug->leave_sub();
761 $main::lxdebug->enter_sub();
763 my ($self, $myconfig, $form) = @_;
765 my $dbh = SL::DB->client->dbh;
767 my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
768 my $sth = $dbh->prepare($query);
769 $sth->execute || $form->dberror($query);
771 ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
775 $main::lxdebug->leave_sub();
779 $main::lxdebug->enter_sub();
781 my ($self, $myconfig, $form) = @_;
783 SL::DB->client->with_transaction(sub {
784 my $dbh = SL::DB->client->dbh;
786 my ($query, @values);
788 # is currently NEVER trueish (no more hidden revtrans in $form)
789 # if ($form->{revtrans}) {
790 # $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
791 # -> therefore you can only set this to false (which is already the default)
792 # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
794 $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
795 @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
797 # set close in defaults
798 do_query($form, $dbh, $query, @values);
801 $main::lxdebug->leave_sub();
805 my ($self, $units, $unit_name, $factor) = @_;
807 $factor = 1 unless ($factor);
809 my $unit = $units->{$unit_name};
811 if (!defined($unit) || !$unit->{"base_unit"} ||
812 ($unit_name eq $unit->{"base_unit"})) {
813 return ($unit_name, $factor);
816 return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
820 $main::lxdebug->enter_sub();
822 my ($self, $myconfig, $form, $prefix) = @_;
825 my $dbh = SL::DB->client->dbh;
827 my $query = "SELECT *, base_unit AS original_base_unit FROM units";
829 my $sth = prepare_execute_query($form, $dbh, $query);
832 while (my $ref = $sth->fetchrow_hashref()) {
833 $units->{$ref->{"name"}} = $ref;
837 my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
838 $sth = $dbh->prepare($query_lang);
839 $sth->execute() || $form->dberror($query_lang);
841 while (my $ref = $sth->fetchrow_hashref()) {
842 push(@languages, $ref);
846 $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
847 "FROM units_language ul " .
848 "LEFT JOIN language l ON ul.language_id = l.id " .
850 $sth = $dbh->prepare($query_lang);
852 foreach my $unit (values(%{$units})) {
853 ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
855 $unit->{"LANGUAGES"} = {};
856 foreach my $lang (@languages) {
857 $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
860 $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
861 while (my $ref = $sth->fetchrow_hashref()) {
862 map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
867 $main::lxdebug->leave_sub();
872 sub retrieve_all_units {
873 $main::lxdebug->enter_sub();
877 if (!$::request->{cache}{all_units}) {
878 $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
881 $main::lxdebug->leave_sub();
883 return $::request->{cache}{all_units};
887 sub translate_units {
888 $main::lxdebug->enter_sub();
890 my ($self, $form, $template_code, $unit, $amount) = @_;
892 my $units = $self->retrieve_units(\%main::myconfig, $form);
894 my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
895 my $new_unit = $unit;
897 if (($amount != 1) && $h->{"localized_plural"}) {
898 $new_unit = $h->{"localized_plural"};
899 } elsif ($h->{"localized"}) {
900 $new_unit = $h->{"localized"};
904 $main::lxdebug->leave_sub();
910 $main::lxdebug->enter_sub();
912 my ($self, $myconfig, $form, $units) = @_;
914 my $dbh = SL::DB->client->dbh;
916 map({ $_->{"in_use"} = 0; } values(%{$units}));
918 foreach my $unit (values(%{$units})) {
919 my $base_unit = $unit->{"original_base_unit"};
921 $units->{$base_unit}->{"in_use"} = 1;
922 $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
923 push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
924 $base_unit = $units->{$base_unit}->{"original_base_unit"};
928 foreach my $unit (values(%{$units})) {
929 map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
931 foreach my $table (qw(parts invoice orderitems)) {
932 my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
934 if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
935 $query .= "= " . $dbh->quote($unit->{"name"});
937 $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
938 join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
941 my ($count) = $dbh->selectrow_array($query);
942 $form->dberror($query) if ($dbh->err);
945 $unit->{"in_use"} = 1;
951 $main::lxdebug->leave_sub();
954 sub convertible_units {
955 $main::lxdebug->enter_sub();
959 my $filter_unit = shift;
960 my $not_smaller = shift;
964 $filter_unit = $units->{$filter_unit};
966 foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
967 my $unit = $units->{$name};
969 if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
970 (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
971 push @{$conv_units}, $unit;
975 my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
977 $main::lxdebug->leave_sub();
982 # if $a is translatable to $b, return the factor between them.
985 $main::lxdebug->enter_sub(2);
986 my ($this, $a, $b, $all_units) = @_;
989 $all_units = $this->retrieve_all_units;
992 $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
993 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
994 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
995 $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
998 sub unit_select_data {
999 $main::lxdebug->enter_sub();
1001 my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1006 push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1009 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1010 if (!$convertible_into ||
1011 ($units->{$convertible_into} &&
1012 ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1013 push @{$select}, { "name" => $unit,
1014 "base_unit" => $units->{$unit}->{"base_unit"},
1015 "factor" => $units->{$unit}->{"factor"},
1016 "selected" => ($unit eq $selected) ? "selected" : "" };
1020 $main::lxdebug->leave_sub();
1025 sub unit_select_html {
1026 $main::lxdebug->enter_sub();
1028 my ($self, $units, $name, $selected, $convertible_into) = @_;
1030 my $select = "<select name=${name}>";
1032 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1033 if (!$convertible_into ||
1034 ($units->{$convertible_into} &&
1035 ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1036 $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1039 $select .= "</select>";
1041 $main::lxdebug->leave_sub();
1047 $main::lxdebug->enter_sub();
1051 my $units = $self->retrieve_all_units();
1056 while (2 <= scalar(@_)) {
1057 my $qty = shift(@_);
1058 my $unit = $units->{shift(@_)};
1060 croak "No unit defined with name $unit" if (!defined $unit);
1063 $base_unit = $unit->{base_unit};
1064 } elsif ($base_unit ne $unit->{base_unit}) {
1065 croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1068 $sum += $qty * $unit->{factor};
1071 $main::lxdebug->leave_sub();
1077 $main::lxdebug->enter_sub();
1079 my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1081 SL::DB->client->with_transaction(sub {
1082 my $dbh = SL::DB->client->dbh;
1084 my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1085 my ($sortkey) = selectrow_query($form, $dbh, $query);
1087 $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1088 "VALUES (?, ?, ?, ?)";
1089 do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1092 $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1093 my $sth = $dbh->prepare($query);
1094 foreach my $lang (@{$languages}) {
1095 my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1096 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1102 $main::lxdebug->leave_sub();
1106 my ($self, $myconfig, $form, $units, $delete_units) = @_;
1107 $main::lxdebug->enter_sub();
1109 my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
1111 $::lxdebug->leave_sub;
1116 my ($self, $myconfig, $form, $units, $delete_units) = @_;
1118 my $dbh = SL::DB->client->dbh;
1120 my ($base_unit, $unit, $sth, $query);
1122 $query = "DELETE FROM units_language";
1123 $dbh->do($query) || $form->dberror($query);
1125 if ($delete_units && (0 != scalar(@{$delete_units}))) {
1126 $query = "DELETE FROM units WHERE name IN (";
1127 map({ $query .= "?," } @{$delete_units});
1128 substr($query, -1, 1) = ")";
1129 $dbh->do($query, undef, @{$delete_units}) ||
1130 $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1133 $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1134 $sth = $dbh->prepare($query);
1136 my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1137 my $sth_lang = $dbh->prepare($query_lang);
1139 foreach $unit (values(%{$units})) {
1140 $unit->{"depth"} = 0;
1141 my $base_unit = $unit;
1142 while ($base_unit->{"base_unit"}) {
1144 $base_unit = $units->{$base_unit->{"base_unit"}};
1148 foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1149 if ($unit->{"LANGUAGES"}) {
1150 foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1151 next unless ($lang->{"id"} && $lang->{"localized"});
1152 my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1153 $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1157 next if ($unit->{"unchanged_unit"});
1159 my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1160 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1164 $sth_lang->finish();
1170 $main::lxdebug->enter_sub();
1172 my ($self, $myconfig, $form) = @_;
1174 my $dbh = SL::DB->client->dbh;
1176 my $query = qq|SELECT
1180 round(t.rate * 100, 2) AS rate,
1181 (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1182 (SELECT description FROM chart WHERE id = chart_id) AS account_description,
1183 (SELECT accno FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_accno,
1184 (SELECT description FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_description,
1185 (SELECT accno FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_accno,
1186 (SELECT description FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_description
1188 ORDER BY taxkey, rate|;
1190 my $sth = $dbh->prepare($query);
1191 $sth->execute || $form->dberror($query);
1194 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1195 push @{ $form->{TAX} }, $ref;
1200 $main::lxdebug->leave_sub();
1203 sub get_tax_accounts {
1204 $main::lxdebug->enter_sub();
1206 my ($self, $myconfig, $form) = @_;
1208 my $dbh = SL::DB->client->dbh;
1210 # get Accounts from chart
1211 my $query = qq{ SELECT
1213 accno || ' - ' || description AS taxaccount
1215 WHERE link LIKE '%_tax%'
1219 my $sth = $dbh->prepare($query);
1220 $sth->execute || $form->dberror($query);
1222 $form->{ACCOUNTS} = [];
1223 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1224 push @{ $form->{ACCOUNTS} }, $ref;
1227 $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
1228 $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
1230 $form->{skontochart_value_title_sub} = sub {
1234 $item->{accno} .' '. $item->{description},
1240 $main::lxdebug->leave_sub();
1244 $main::lxdebug->enter_sub();
1246 my ($self, $myconfig, $form) = @_;
1248 my $dbh = SL::DB->client->dbh;
1250 my $query = qq|SELECT
1253 round(rate * 100, 2) AS rate,
1256 (id IN (SELECT tax_id
1257 FROM acc_trans)) AS tax_already_used,
1258 skonto_sales_chart_id,
1259 skonto_purchase_chart_id
1263 my $sth = $dbh->prepare($query);
1264 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1266 my $ref = $sth->fetchrow_hashref("NAME_lc");
1268 map { $form->{$_} = $ref->{$_} } keys %$ref;
1272 # see if it is used by a taxkey
1273 $query = qq|SELECT count(*) FROM taxkeys
1274 WHERE tax_id = ? AND chart_id >0|;
1276 ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1278 $form->{orphaned} = !$form->{orphaned};
1281 if (!$form->{orphaned} ) {
1282 $query = qq|SELECT DISTINCT c.id, c.accno
1284 JOIN tax t ON (t.id = tk.tax_id)
1285 JOIN chart c ON (c.id = tk.chart_id)
1286 WHERE tk.tax_id = ?|;
1288 $sth = $dbh->prepare($query);
1289 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1291 $form->{TAXINUSE} = [];
1292 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1293 push @{ $form->{TAXINUSE} }, $ref;
1299 $main::lxdebug->leave_sub();
1303 my ($self, $myconfig, $form) = @_;
1304 $main::lxdebug->enter_sub();
1306 my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
1308 $::lxdebug->leave_sub;
1313 my ($self, $myconfig, $form) = @_;
1316 my $dbh = SL::DB->client->dbh;
1318 $form->{rate} = $form->{rate} / 100;
1320 my $chart_categories = '';
1321 $chart_categories .= 'A' if $form->{asset};
1322 $chart_categories .= 'L' if $form->{liability};
1323 $chart_categories .= 'Q' if $form->{equity};
1324 $chart_categories .= 'I' if $form->{revenue};
1325 $chart_categories .= 'E' if $form->{expense};
1326 $chart_categories .= 'C' if $form->{costs};
1328 my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, conv_i($form->{chart_id}), conv_i($form->{chart_id}), conv_i($form->{skonto_sales_chart_id}), conv_i($form->{skonto_purchase_chart_id}), $chart_categories);
1329 if ($form->{id} ne "") {
1330 $query = qq|UPDATE tax SET
1335 taxnumber = (SELECT accno FROM chart WHERE id = ? ),
1336 skonto_sales_chart_id = ?,
1337 skonto_purchase_chart_id = ?,
1338 chart_categories = ?
1343 ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
1344 $query = qq|INSERT INTO tax (
1350 skonto_sales_chart_id,
1351 skonto_purchase_chart_id,
1355 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?), ?, ?, ?, ?)|;
1357 push(@values, $form->{id});
1358 do_query($form, $dbh, $query, @values);
1360 foreach my $language_id (keys %{ $form->{translations} }) {
1361 GenericTranslations->save('dbh' => $dbh,
1362 'translation_type' => 'SL::DB::Tax/taxdescription',
1363 'translation_id' => $form->{id},
1364 'language_id' => $language_id,
1365 'translation' => $form->{translations}->{$language_id});
1370 $main::lxdebug->enter_sub();
1372 my ($self, $myconfig, $form) = @_;
1375 SL::DB->client->with_transaction(sub {
1376 $query = qq|DELETE FROM tax WHERE id = ?|;
1377 do_query($form, SL::DB->client->dbh, $query, $form->{id});
1380 $main::lxdebug->leave_sub();
1383 sub save_price_factor {
1384 $main::lxdebug->enter_sub();
1386 my ($self, $myconfig, $form) = @_;
1388 SL::DB->client->with_transaction(sub {
1389 my $dbh = SL::DB->client->dbh;
1392 my @values = ($form->{description}, conv_i($form->{factor}));
1395 $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1396 push @values, conv_i($form->{id});
1399 $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1402 do_query($form, $dbh, $query, @values);
1405 $main::lxdebug->leave_sub();
1408 sub get_all_price_factors {
1409 $main::lxdebug->enter_sub();
1411 my ($self, $myconfig, $form) = @_;
1413 my $dbh = SL::DB->client->dbh;
1415 $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1417 $main::lxdebug->leave_sub();
1420 sub get_price_factor {
1421 $main::lxdebug->enter_sub();
1423 my ($self, $myconfig, $form) = @_;
1425 # connect to database
1426 my $dbh = SL::DB->client->dbh;
1428 my $query = qq|SELECT description, factor,
1429 ((SELECT COUNT(*) FROM parts WHERE price_factor_id = ?) +
1430 (SELECT COUNT(*) FROM invoice WHERE price_factor_id = ?) +
1431 (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1432 FROM price_factors WHERE id = ?|;
1434 ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1436 $main::lxdebug->leave_sub();
1439 sub delete_price_factor {
1440 $main::lxdebug->enter_sub();
1442 my ($self, $myconfig, $form) = @_;
1444 SL::DB->client->with_transaction(sub {
1445 do_query($form, SL::DB->client->dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1448 $main::lxdebug->leave_sub();
1451 sub save_warehouse {
1452 $main::lxdebug->enter_sub();
1454 my ($self, $myconfig, $form) = @_;
1456 SL::DB->client->with_transaction(sub {
1457 my $dbh = SL::DB->client->dbh;
1459 my ($query, @values, $sth);
1462 $query = qq|SELECT nextval('id')|;
1463 ($form->{id}) = selectrow_query($form, $dbh, $query);
1465 $query = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1466 do_query($form, $dbh, $query, $form->{id});
1469 do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1470 $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1472 if (0 < $form->{number_of_new_bins}) {
1473 my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
1474 $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1475 $sth = prepare_query($form, $dbh, $query);
1477 foreach my $i (1..$form->{number_of_new_bins}) {
1478 do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
1485 $main::lxdebug->leave_sub();
1489 $main::lxdebug->enter_sub();
1491 my ($self, $myconfig, $form) = @_;
1493 SL::DB->client->with_transaction(sub {
1494 my $dbh = SL::DB->client->dbh;
1496 my ($query, @values, $sth);
1498 @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1501 $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1502 do_query($form, $dbh, $query, @values);
1505 $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1506 $sth = prepare_query($form, $dbh, $query);
1508 foreach my $row (1..$form->{rowcount}) {
1509 next if ($form->{"delete_${row}"});
1511 do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1517 $main::lxdebug->leave_sub();
1520 sub delete_warehouse {
1521 $main::lxdebug->enter_sub();
1523 my ($self, $myconfig, $form) = @_;
1525 my $rc = SL::DB->client->with_transaction(sub {
1526 my $dbh = SL::DB->client->dbh;
1528 my $id = conv_i($form->{id});
1529 my $query = qq|SELECT i.bin_id FROM inventory i WHERE i.bin_id IN (SELECT b.id FROM bin b WHERE b.warehouse_id = ?) LIMIT 1|;
1530 my ($count) = selectrow_query($form, $dbh, $query, $id);
1536 do_query($form, $dbh, qq|DELETE FROM bin WHERE warehouse_id = ?|, conv_i($form->{id}));
1537 do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id = ?|, conv_i($form->{id}));
1542 $main::lxdebug->leave_sub();
1547 sub get_all_warehouses {
1548 $main::lxdebug->enter_sub();
1550 my ($self, $myconfig, $form) = @_;
1552 my $dbh = SL::DB->client->dbh;
1554 my $query = qq|SELECT w.id, w.description, w.invalid,
1555 (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
1557 ORDER BY w.sortkey|;
1559 $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
1561 $main::lxdebug->leave_sub();
1565 $main::lxdebug->enter_sub();
1567 my ($self, $myconfig, $form) = @_;
1569 my $dbh = SL::DB->client->dbh;
1571 my $id = conv_i($form->{id});
1572 my $query = qq|SELECT w.description, w.invalid
1576 my $ref = selectfirst_hashref_query($form, $dbh, $query, $id);
1578 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1582 ( EXISTS(SELECT i.bin_id FROM inventory i WHERE i.bin_id = b.id LIMIT 1)
1583 OR EXISTS(SELECT p.bin_id FROM parts p WHERE p.bin_id = b.id LIMIT 1))
1586 WHERE b.warehouse_id = ?
1589 $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1591 $main::lxdebug->leave_sub();