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., 51 Franklin Street, Fifth Floor, Boston,
30 #======================================================================
32 # Administration module
37 #======================================================================
44 use List::MoreUtils qw(any);
54 use SL::GenericTranslations;
55 use SL::Helper::UserPreferences::PositionsScrollbar;
56 use SL::Helper::UserPreferences::PartPickerSearch;
61 $main::lxdebug->enter_sub();
63 # fetch chart-related data and set form fields
64 # get_account is called by add_account in am.pl
65 # always sets $form->{TAXKEY} and default_accounts
66 # loads chart data when $form->{id} is passed
68 my ($self, $myconfig, $form) = @_;
70 # get default accounts
71 map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
74 my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
76 foreach my $tk ( @{$taxes} ) {
77 push @{ $form->{TAXKEY} }, { id => $tk->id,
78 chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
79 taxkey => $tk->taxkey,
80 tax => $tk->id . '--' . $tk->taxkey,
87 my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
89 my @chart_fields = qw(accno description charttype category link pos_bilanz
90 pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik);
91 foreach my $cf ( @chart_fields ) {
92 $form->{"$cf"} = $chart_obj->$cf;
95 my $active_taxkey = $chart_obj->get_active_taxkey;
96 $form->{$_} = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
97 $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
99 # check if there are any transactions for this chart
100 $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
102 # check if new account is active
103 # The old sql query was broken since at least 2006 and always returned 0
104 $form->{new_chart_valid} = $chart_obj->new_chart_valid;
106 # get the taxkeys of the account
107 $form->{ACCOUNT_TAXKEYS} = [];
108 foreach my $taxkey ( @{ $chart_obj->taxkeys } ) {
109 push @{ $form->{ACCOUNT_TAXKEYS} }, { id => $taxkey->id,
110 chart_id => $taxkey->chart_id,
111 tax_id => $taxkey->tax_id,
112 taxkey_id => $taxkey->taxkey_id,
113 pos_ustva => $taxkey->pos_ustva,
114 startdate => $taxkey->startdate->to_kivitendo,
115 taxdescription => $taxkey->tax->taxdescription,
116 rate => $taxkey->tax->rate,
117 accno => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
121 # get new accounts (Folgekonto). Find all charts with the same link
122 $form->{NEWACCOUNT} = $chart_obj->db->dbh->selectall_arrayref('select id, accno,description from chart where link = ? and id != ? order by accno', {Slice => {}}, $chart_obj->link, $form->{id});
124 } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
125 $form->{orphaned} = 1;
128 $main::lxdebug->leave_sub();
132 my ($self, $myconfig, $form) = @_;
133 $main::lxdebug->enter_sub();
135 my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
137 $::lxdebug->leave_sub;
142 # TODO: it should be forbidden to change an account to a heading if there
143 # have been bookings to this account in the past
145 my ($self, $myconfig, $form) = @_;
147 my $dbh = SL::DB->client->dbh;
149 for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
150 $form->{$form->{$_}} = $form->{$_} if $form->{$_};
153 # sanity check, can't have AR with AR_...
154 if ($form->{AR} || $form->{AP} || $form->{IC}) {
155 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)) {
156 $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
160 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);
161 $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
163 # strip blanks from accno
164 map { $form->{$_} =~ s/ //g; } qw(accno);
166 # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
167 map { $form->{$_} =~ s/\h+/ /g } qw(description);
171 if ($form->{id} eq "NULL") {
180 my @values = ($form->{accno});
183 $query .= ' AND NOT id = ?';
184 push(@values, $form->{id});
187 my ($accno) = selectrow_query($form, $dbh, $query, @values);
190 $form->error($::locale->text('Account number not unique!'));
194 if (!$form->{id} || $form->{id} eq "") {
195 $query = qq|SELECT nextval('id')|;
196 ($form->{"id"}) = selectrow_query($form, $dbh, $query);
197 $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
198 do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
206 # if charttype is heading make sure certain values are empty
207 # specifically, if charttype is changed from an existing account, empty the
208 # fields unnecessary for headings, so that e.g. heading doesn't appear in
209 # drop-down menues due to still having a valid "link" entry
211 if ( $form->{charttype} eq 'H' ) {
213 $form->{pos_bwa} = '';
214 $form->{pos_bilanz} = '';
215 $form->{pos_eur} = '';
216 $form->{new_chart_id} = '';
217 $form->{valid_from} = '';
220 $query = qq|UPDATE chart SET
237 $form->{description},
241 conv_i($form->{pos_bwa}),
242 conv_i($form->{pos_bilanz}),
243 conv_i($form->{pos_eur}),
244 conv_i($form->{pos_er}),
245 conv_i($form->{new_chart_id}),
246 conv_date($form->{valid_from}),
247 ($form->{datevautomatik} eq 'T') ? 'true':'false',
254 do_query($form, $dbh, $query, @values);
260 my $MAX_TRIES = 10; # Maximum count of taxkeys in form
264 for $tk_count (0 .. $MAX_TRIES) {
268 # Check if the account already exists, else cancel
270 print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
272 last READTAXKEYS if ( $form->{'id'} == 0);
274 # check if there is a startdate
275 if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
280 # Add valid taxkeys into the array
283 id => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
284 tax_id => conv_i($form->{"taxkey_tax_$tk_count"}),
285 startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
286 chart_id => conv_i($form->{"id"}),
287 pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
288 delete => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
295 for my $j (0 .. $#taxkeys){
296 if ( defined $taxkeys[$j]{'id'} ){
299 if ($taxkeys[$j]{'delete'}){
301 DELETE FROM taxkeys WHERE id = ?
304 @values = ($taxkeys[$j]{'id'});
306 do_query($form, $dbh, $query, @values);
315 SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
323 $taxkeys[$j]{'tax_id'},
324 $taxkeys[$j]{'chart_id'},
325 $taxkeys[$j]{'tax_id'},
326 $taxkeys[$j]{'pos_ustva'},
327 $taxkeys[$j]{'startdate'},
330 do_query($form, $dbh, $query, @values);
336 INSERT INTO taxkeys (
343 VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
346 $taxkeys[$j]{'tax_id'},
347 $taxkeys[$j]{'chart_id'},
348 $taxkeys[$j]{'tax_id'},
349 $taxkeys[$j]{'pos_ustva'},
350 $taxkeys[$j]{'startdate'},
353 do_query($form, $dbh, $query, @values);
358 # Update chart.taxkey_id to the latest from taxkeys for this chart.
364 WHERE taxkeys.chart_id = chart.id
365 ORDER BY startdate DESC
371 do_query($form, $dbh, $query, $form->{id});
377 my ($self, $myconfig, $form) = @_;
378 $main::lxdebug->enter_sub();
380 my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
382 $::lxdebug->leave_sub;
386 sub _delete_account {
387 my ($self, $myconfig, $form) = @_;
389 my $dbh = SL::DB->client->dbh;
391 my $query = qq|SELECT count(*) FROM acc_trans a
392 WHERE a.chart_id = ?|;
393 my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
399 $query = qq|DELETE FROM tax
401 do_query($form, $dbh, $query, $form->{id});
403 # delete account taxkeys
404 $query = qq|DELETE FROM taxkeys
406 do_query($form, $dbh, $query, $form->{id});
408 # delete chart of account record
409 # last step delete chart, because we have a constraint
411 $query = qq|DELETE FROM chart
413 do_query($form, $dbh, $query, $form->{id});
418 sub get_language_details {
419 $main::lxdebug->enter_sub();
421 my ($self, $myconfig, $form, $id) = @_;
423 my $dbh = SL::DB->client->dbh;
426 "SELECT template_code, " .
427 " output_numberformat, output_dateformat, output_longdates " .
428 "FROM language WHERE id = ?";
429 my @res = selectrow_query($form, $dbh, $query, $id);
431 $main::lxdebug->leave_sub();
436 sub prepare_template_filename {
437 $main::lxdebug->enter_sub();
439 my ($self, $myconfig, $form) = @_;
441 my ($filename, $display_filename);
443 $filename = $form->{formname};
445 if ($form->{language}) {
446 my ($id, $template_code) = split(/--/, $form->{language});
447 $filename .= "_${template_code}";
450 if ($form->{printer}) {
451 my ($id, $template_code) = split(/--/, $form->{printer});
452 $filename .= "_${template_code}";
455 $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
456 if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
457 $filename =~ s|.*/||;
459 $display_filename = $filename;
460 $filename = SL::DB::Default->get->templates . "/$filename";
462 $main::lxdebug->leave_sub();
464 return ($filename, $display_filename);
469 $main::lxdebug->enter_sub();
471 my ($self, $filename) = @_;
473 my ($content, $lines) = ("", 0);
477 if (open(TEMPLATE, $filename)) {
485 $content = Encode::decode('utf-8-strict', $content);
487 $main::lxdebug->leave_sub();
489 return ($content, $lines);
493 $main::lxdebug->enter_sub();
495 my ($self, $filename, $content) = @_;
501 if (open(TEMPLATE, ">", $filename)) {
502 $content = Encode::encode('utf-8-strict', $content);
503 $content =~ s/\r\n/\n/g;
504 print(TEMPLATE $content);
510 $main::lxdebug->leave_sub();
515 sub displayable_name_specs_by_module {
517 'SL::DB::Customer' => {
518 specs => SL::DB::Customer->displayable_name_specs,
519 prefs => SL::DB::Customer->displayable_name_prefs,
521 'SL::DB::Vendor' => {
522 specs => SL::DB::Vendor->displayable_name_specs,
523 prefs => SL::DB::Vendor->displayable_name_prefs,
526 specs => SL::DB::Part->displayable_name_specs,
527 prefs => SL::DB::Part->displayable_name_prefs,
532 sub positions_scrollbar_height {
533 SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
536 sub purchase_search_makemodel {
537 SL::Helper::UserPreferences::PartPickerSearch->new()->get_purchase_search_makemodel();
540 sub sales_search_customer_partnumber {
541 SL::Helper::UserPreferences::PartPickerSearch->new()->get_sales_search_customer_partnumber();
544 sub save_preferences {
545 $main::lxdebug->enter_sub();
547 my ($self, $form) = @_;
549 my $employee = SL::DB::Manager::Employee->find_by(login => $::myconfig{login});
550 $employee->update_attributes(name => $form->{name});
552 my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
553 $user->update_attributes(
555 %{ $user->config_values },
556 map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
559 # Displayable name preferences
560 my $displayable_name_specs_by_module = displayable_name_specs_by_module();
561 foreach my $specs (@{ $form->{displayable_name_specs} }) {
562 if (!$specs->{value} || $specs->{value} eq $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->get_default()) {
563 $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->delete($specs->{value});
565 $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->store_value($specs->{value});
569 if (exists $form->{positions_scrollbar_height}) {
570 SL::Helper::UserPreferences::PositionsScrollbar->new()->store_height($form->{positions_scrollbar_height})
572 if (exists $form->{purchase_search_makemodel}) {
573 SL::Helper::UserPreferences::PartPickerSearch->new()->store_purchase_search_makemodel($form->{purchase_search_makemodel})
575 if (exists $form->{sales_search_customer_partnumber}) {
576 SL::Helper::UserPreferences::PartPickerSearch->new()->store_sales_search_customer_partnumber($form->{sales_search_customer_partnumber})
579 $main::lxdebug->leave_sub();
585 $main::lxdebug->enter_sub();
590 my $myconfig = \%main::myconfig;
591 my $form = $main::form;
593 my $dbh = $params{dbh} || SL::DB->client->dbh;
595 my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
597 $defaults->{weightunit} ||= 'kg';
599 $main::lxdebug->leave_sub();
605 $main::lxdebug->enter_sub();
607 my ($self, $myconfig, $form) = @_;
609 my $dbh = SL::DB->client->dbh;
611 my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
612 my $sth = $dbh->prepare($query);
613 $sth->execute || $form->dberror($query);
615 ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
619 $main::lxdebug->leave_sub();
623 $main::lxdebug->enter_sub();
625 my ($self, $myconfig, $form) = @_;
627 SL::DB->client->with_transaction(sub {
628 my $dbh = SL::DB->client->dbh;
630 my ($query, @values);
632 # is currently NEVER trueish (no more hidden revtrans in $form)
633 # if ($form->{revtrans}) {
634 # $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
635 # -> therefore you can only set this to false (which is already the default)
636 # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
638 $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
639 @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
641 # set close in defaults
642 do_query($form, $dbh, $query, @values);
644 }) or do { die SL::DB->client->error };
646 $main::lxdebug->leave_sub();
650 my ($self, $units, $unit_name, $factor) = @_;
652 $factor = 1 unless ($factor);
654 my $unit = $units->{$unit_name};
656 if (!defined($unit) || !$unit->{"base_unit"} ||
657 ($unit_name eq $unit->{"base_unit"})) {
658 return ($unit_name, $factor);
661 return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
665 $main::lxdebug->enter_sub();
667 my ($self, $myconfig, $form, $prefix) = @_;
670 my $dbh = SL::DB->client->dbh;
672 my $query = "SELECT *, base_unit AS original_base_unit FROM units";
674 my $sth = prepare_execute_query($form, $dbh, $query);
677 while (my $ref = $sth->fetchrow_hashref()) {
678 $units->{$ref->{"name"}} = $ref;
682 my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
683 $sth = $dbh->prepare($query_lang);
684 $sth->execute() || $form->dberror($query_lang);
686 while (my $ref = $sth->fetchrow_hashref()) {
687 push(@languages, $ref);
691 $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
692 "FROM units_language ul " .
693 "LEFT JOIN language l ON ul.language_id = l.id " .
695 $sth = $dbh->prepare($query_lang);
697 foreach my $unit (values(%{$units})) {
698 ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
700 $unit->{"LANGUAGES"} = {};
701 foreach my $lang (@languages) {
702 $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
705 $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
706 while (my $ref = $sth->fetchrow_hashref()) {
707 map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
712 $main::lxdebug->leave_sub();
717 sub retrieve_all_units {
718 $main::lxdebug->enter_sub();
722 if (!$::request->{cache}{all_units}) {
723 $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
726 $main::lxdebug->leave_sub();
728 return $::request->{cache}{all_units};
732 sub translate_units {
733 $main::lxdebug->enter_sub();
735 my ($self, $form, $template_code, $unit, $amount) = @_;
737 my $units = $self->retrieve_units(\%main::myconfig, $form);
739 my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
740 my $new_unit = $unit;
742 if (($amount != 1) && $h->{"localized_plural"}) {
743 $new_unit = $h->{"localized_plural"};
744 } elsif ($h->{"localized"}) {
745 $new_unit = $h->{"localized"};
749 $main::lxdebug->leave_sub();
755 $main::lxdebug->enter_sub();
757 my ($self, $myconfig, $form, $units) = @_;
759 my $dbh = SL::DB->client->dbh;
761 map({ $_->{"in_use"} = 0; } values(%{$units}));
763 foreach my $unit (values(%{$units})) {
764 my $base_unit = $unit->{"original_base_unit"};
766 $units->{$base_unit}->{"in_use"} = 1;
767 $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
768 push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
769 $base_unit = $units->{$base_unit}->{"original_base_unit"};
773 foreach my $unit (values(%{$units})) {
774 map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
776 foreach my $table (qw(parts invoice orderitems)) {
777 my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
779 if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
780 $query .= "= " . $dbh->quote($unit->{"name"});
782 $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
783 join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
786 my ($count) = $dbh->selectrow_array($query);
787 $form->dberror($query) if ($dbh->err);
790 $unit->{"in_use"} = 1;
796 $main::lxdebug->leave_sub();
799 sub convertible_units {
800 $main::lxdebug->enter_sub();
804 my $filter_unit = shift;
805 my $not_smaller = shift;
809 $filter_unit = $units->{$filter_unit};
811 foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
812 my $unit = $units->{$name};
814 if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
815 (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
816 push @{$conv_units}, $unit;
820 my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
822 $main::lxdebug->leave_sub();
827 # if $a is translatable to $b, return the factor between them.
830 $main::lxdebug->enter_sub(2);
831 my ($this, $a, $b, $all_units) = @_;
834 $all_units = $this->retrieve_all_units;
837 $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
838 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
839 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
840 $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
843 sub unit_select_data {
844 $main::lxdebug->enter_sub();
846 my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
851 push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
854 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
855 if (!$convertible_into ||
856 ($units->{$convertible_into} &&
857 ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
858 push @{$select}, { "name" => $unit,
859 "base_unit" => $units->{$unit}->{"base_unit"},
860 "factor" => $units->{$unit}->{"factor"},
861 "selected" => ($unit eq $selected) ? "selected" : "" };
865 $main::lxdebug->leave_sub();
870 sub unit_select_html {
871 $main::lxdebug->enter_sub();
873 my ($self, $units, $name, $selected, $convertible_into) = @_;
875 my $select = "<select name=${name}>";
877 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
878 if (!$convertible_into ||
879 ($units->{$convertible_into} &&
880 ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
881 $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
884 $select .= "</select>";
886 $main::lxdebug->leave_sub();
892 $main::lxdebug->enter_sub();
896 my $units = $self->retrieve_all_units();
901 while (2 <= scalar(@_)) {
903 my $unit = $units->{shift(@_)};
905 croak "No unit defined with name $unit" if (!defined $unit);
908 $base_unit = $unit->{base_unit};
909 } elsif ($base_unit ne $unit->{base_unit}) {
910 croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
913 $sum += $qty * $unit->{factor};
916 $main::lxdebug->leave_sub();
922 $main::lxdebug->enter_sub();
924 my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
926 SL::DB->client->with_transaction(sub {
927 my $dbh = SL::DB->client->dbh;
929 my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
930 my ($sortkey) = selectrow_query($form, $dbh, $query);
932 $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
933 "VALUES (?, ?, ?, ?)";
934 do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
937 $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
938 my $sth = $dbh->prepare($query);
939 foreach my $lang (@{$languages}) {
940 my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
941 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
946 }) or do { die SL::DB->client->error };
948 $main::lxdebug->leave_sub();
952 my ($self, $myconfig, $form, $units, $delete_units) = @_;
953 $main::lxdebug->enter_sub();
955 my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
957 $::lxdebug->leave_sub;
962 my ($self, $myconfig, $form, $units, $delete_units) = @_;
964 my $dbh = SL::DB->client->dbh;
966 my ($base_unit, $unit, $sth, $query);
968 $query = "DELETE FROM units_language";
969 $dbh->do($query) || $form->dberror($query);
971 if ($delete_units && (0 != scalar(@{$delete_units}))) {
972 $query = "DELETE FROM units WHERE name IN (";
973 map({ $query .= "?," } @{$delete_units});
974 substr($query, -1, 1) = ")";
975 $dbh->do($query, undef, @{$delete_units}) ||
976 $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
979 $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
980 $sth = $dbh->prepare($query);
982 my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
983 my $sth_lang = $dbh->prepare($query_lang);
985 foreach $unit (values(%{$units})) {
986 $unit->{"depth"} = 0;
987 my $base_unit = $unit;
988 while ($base_unit->{"base_unit"}) {
990 $base_unit = $units->{$base_unit->{"base_unit"}};
994 foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
995 if ($unit->{"LANGUAGES"}) {
996 foreach my $lang (@{$unit->{"LANGUAGES"}}) {
997 next unless ($lang->{"id"} && $lang->{"localized"});
998 my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
999 $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1003 next if ($unit->{"unchanged_unit"});
1005 my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1006 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1010 $sth_lang->finish();
1016 $main::lxdebug->enter_sub();
1018 my ($self, $myconfig, $form) = @_;
1020 my $dbh = SL::DB->client->dbh;
1022 my $query = qq|SELECT
1026 round(t.rate * 100, 2) AS rate,
1027 tc.accno AS taxnumber,
1028 tc.description AS account_description,
1029 ssc.accno AS skonto_chart_accno,
1030 ssc.description AS skonto_chart_description,
1031 spc.accno AS skonto_chart_purchase_accno,
1032 spc.description AS skonto_chart_purchase_description
1034 LEFT JOIN chart tc ON (tc.id = t.chart_id)
1035 LEFT JOIN chart ssc ON (ssc.id = t.skonto_sales_chart_id)
1036 LEFT JOIN chart spc ON (spc.id = t.skonto_purchase_chart_id)
1037 ORDER BY taxkey, rate|;
1039 my $sth = $dbh->prepare($query);
1040 $sth->execute || $form->dberror($query);
1043 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1044 push @{ $form->{TAX} }, $ref;
1049 $main::lxdebug->leave_sub();
1052 sub get_tax_accounts {
1053 $main::lxdebug->enter_sub();
1055 my ($self, $myconfig, $form) = @_;
1057 my $dbh = SL::DB->client->dbh;
1059 # get Accounts from chart
1060 my $query = qq{ SELECT
1062 accno || ' - ' || description AS taxaccount
1064 WHERE link LIKE '%_tax%'
1068 my $sth = $dbh->prepare($query);
1069 $sth->execute || $form->dberror($query);
1071 $form->{ACCOUNTS} = [];
1072 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1073 push @{ $form->{ACCOUNTS} }, $ref;
1076 $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
1077 $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
1079 $form->{skontochart_value_title_sub} = sub {
1083 $item->{accno} .' '. $item->{description},
1089 $main::lxdebug->leave_sub();
1093 $main::lxdebug->enter_sub();
1095 my ($self, $myconfig, $form) = @_;
1097 my $dbh = SL::DB->client->dbh;
1099 my $query = qq|SELECT
1102 round(rate * 100, 2) AS rate,
1105 (id IN (SELECT tax_id
1106 FROM acc_trans)) AS tax_already_used,
1107 skonto_sales_chart_id,
1108 skonto_purchase_chart_id
1112 my $sth = $dbh->prepare($query);
1113 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1115 my $ref = $sth->fetchrow_hashref("NAME_lc");
1117 map { $form->{$_} = $ref->{$_} } keys %$ref;
1121 # see if it is used by a taxkey
1122 $query = qq|SELECT count(*) FROM taxkeys
1123 WHERE tax_id = ? AND chart_id >0|;
1125 ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1127 $form->{orphaned} = !$form->{orphaned};
1130 if (!$form->{orphaned} ) {
1131 $query = qq|SELECT DISTINCT c.id, c.accno
1133 JOIN tax t ON (t.id = tk.tax_id)
1134 JOIN chart c ON (c.id = tk.chart_id)
1135 WHERE tk.tax_id = ?|;
1137 $sth = $dbh->prepare($query);
1138 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1140 $form->{TAXINUSE} = [];
1141 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1142 push @{ $form->{TAXINUSE} }, $ref;
1148 $main::lxdebug->leave_sub();
1152 my ($self, $myconfig, $form) = @_;
1153 $main::lxdebug->enter_sub();
1155 my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
1157 $::lxdebug->leave_sub;
1162 my ($self, $myconfig, $form) = @_;
1165 my $dbh = SL::DB->client->dbh;
1167 $form->{rate} = $form->{rate} / 100;
1169 my $chart_categories = '';
1170 $chart_categories .= 'A' if $form->{asset};
1171 $chart_categories .= 'L' if $form->{liability};
1172 $chart_categories .= 'Q' if $form->{equity};
1173 $chart_categories .= 'I' if $form->{revenue};
1174 $chart_categories .= 'E' if $form->{expense};
1175 $chart_categories .= 'C' if $form->{costs};
1177 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);
1178 if ($form->{id} ne "") {
1179 $query = qq|UPDATE tax SET
1184 skonto_sales_chart_id = ?,
1185 skonto_purchase_chart_id = ?,
1186 chart_categories = ?
1191 ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
1192 $query = qq|INSERT INTO tax (
1197 skonto_sales_chart_id,
1198 skonto_purchase_chart_id,
1202 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?), ?, ?, ?, ?)|;
1204 push(@values, $form->{id});
1205 do_query($form, $dbh, $query, @values);
1207 foreach my $language_id (keys %{ $form->{translations} }) {
1208 GenericTranslations->save('dbh' => $dbh,
1209 'translation_type' => 'SL::DB::Tax/taxdescription',
1210 'translation_id' => $form->{id},
1211 'language_id' => $language_id,
1212 'translation' => $form->{translations}->{$language_id});
1217 $main::lxdebug->enter_sub();
1219 my ($self, $myconfig, $form) = @_;
1222 SL::DB->client->with_transaction(sub {
1223 $query = qq|DELETE FROM tax WHERE id = ?|;
1224 do_query($form, SL::DB->client->dbh, $query, $form->{id});
1226 }) or do { die SL::DB->client->error };
1228 $main::lxdebug->leave_sub();
1231 sub save_warehouse {
1232 $main::lxdebug->enter_sub();
1234 my ($self, $myconfig, $form) = @_;
1236 SL::DB->client->with_transaction(sub {
1237 my $dbh = SL::DB->client->dbh;
1239 my ($query, @values, $sth);
1242 $query = qq|SELECT nextval('id')|;
1243 ($form->{id}) = selectrow_query($form, $dbh, $query);
1245 $query = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1246 do_query($form, $dbh, $query, $form->{id});
1249 do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1250 $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1252 if (0 < $form->{number_of_new_bins}) {
1253 my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
1254 $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1255 $sth = prepare_query($form, $dbh, $query);
1257 foreach my $i (1..$form->{number_of_new_bins}) {
1258 do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
1264 }) or do { die SL::DB->client->error };
1266 $main::lxdebug->leave_sub();
1270 $main::lxdebug->enter_sub();
1272 my ($self, $myconfig, $form) = @_;
1274 SL::DB->client->with_transaction(sub {
1275 my $dbh = SL::DB->client->dbh;
1277 my ($query, @values, $sth);
1279 @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1282 $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1283 do_query($form, $dbh, $query, @values);
1286 $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1287 $sth = prepare_query($form, $dbh, $query);
1289 foreach my $row (1..$form->{rowcount}) {
1290 next if ($form->{"delete_${row}"});
1292 do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1297 }) or do { die SL::DB->client->error };
1299 $main::lxdebug->leave_sub();
1302 sub delete_warehouse {
1303 $main::lxdebug->enter_sub();
1305 my ($self, $myconfig, $form) = @_;
1307 my $rc = SL::DB->client->with_transaction(sub {
1308 my $dbh = SL::DB->client->dbh;
1310 my $id = conv_i($form->{id});
1311 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|;
1312 my ($count) = selectrow_query($form, $dbh, $query, $id);
1318 do_query($form, $dbh, qq|DELETE FROM bin WHERE warehouse_id = ?|, conv_i($form->{id}));
1319 do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id = ?|, conv_i($form->{id}));
1324 $main::lxdebug->leave_sub();
1329 sub get_all_warehouses {
1330 $main::lxdebug->enter_sub();
1332 my ($self, $myconfig, $form) = @_;
1334 my $dbh = SL::DB->client->dbh;
1336 my $query = qq|SELECT w.id, w.description, w.invalid,
1337 (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
1339 ORDER BY w.sortkey|;
1341 $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
1343 $main::lxdebug->leave_sub();
1347 $main::lxdebug->enter_sub();
1349 my ($self, $myconfig, $form) = @_;
1351 my $dbh = SL::DB->client->dbh;
1353 my $id = conv_i($form->{id});
1354 my $query = qq|SELECT w.description, w.invalid
1358 my $ref = selectfirst_hashref_query($form, $dbh, $query, $id);
1360 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1363 SELECT b.*, use.in_use
1366 SELECT DISTINCT bin_id, TRUE AS in_use FROM inventory
1368 SELECT DISTINCT bin_id, TRUE AS in_use FROM parts
1369 ) use ON use.bin_id = b.id
1370 WHERE b.warehouse_id = ?;
1373 $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1375 $main::lxdebug->leave_sub();
1378 sub get_eur_categories {
1379 my ($self, $myconfig, $form) = @_;
1381 my $dbh = SL::DB->client->dbh;
1382 my %eur_categories = selectall_as_map($form, $dbh, "select * from eur_categories order by id", 'id', 'description');
1384 return \%eur_categories;
1387 sub get_bwa_categories {
1388 my ($self, $myconfig, $form) = @_;
1390 my $dbh = SL::DB->client->dbh;
1391 my %bwa_categories = selectall_as_map($form, $dbh, "select * from bwa_categories order by id", 'id', 'description');
1393 return \%bwa_categories;