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::DisplayPreferences;
56 use SL::Helper::UserPreferences::PositionsScrollbar;
57 use SL::Helper::UserPreferences::PartPickerSearch;
58 use SL::Helper::UserPreferences::TimeRecording;
59 use SL::Helper::UserPreferences::UpdatePositions;
60 use SL::Helper::UserPreferences::ItemInputPosition;
65 $main::lxdebug->enter_sub();
67 # fetch chart-related data and set form fields
68 # get_account is called by add_account in am.pl
69 # always sets $form->{TAXKEY} and default_accounts
70 # loads chart data when $form->{id} is passed
72 my ($self, $myconfig, $form) = @_;
74 # get default accounts
75 map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
78 my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
80 foreach my $tk ( @{$taxes} ) {
81 push @{ $form->{TAXKEY} }, { id => $tk->id,
82 chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
83 taxkey => $tk->taxkey,
84 tax => $tk->id . '--' . $tk->taxkey,
91 my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
93 my @chart_fields = qw(accno description charttype category link pos_bilanz
94 pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik
96 foreach my $cf ( @chart_fields ) {
97 $form->{"$cf"} = $chart_obj->$cf;
100 my $active_taxkey = $chart_obj->get_active_taxkey;
101 if ($active_taxkey) {
102 $form->{$_} = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
103 $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
106 # check if there are any transactions for this chart
107 $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
109 # check if new account is active
110 # The old sql query was broken since at least 2006 and always returned 0
111 $form->{new_chart_valid} = $chart_obj->new_chart_valid;
113 # get the taxkeys of the account
114 $form->{ACCOUNT_TAXKEYS} = [];
115 foreach my $taxkey ( sort { $b->startdate <=> $a->startdate } @{ $chart_obj->taxkeys } ) {
116 push @{ $form->{ACCOUNT_TAXKEYS} }, { id => $taxkey->id,
117 chart_id => $taxkey->chart_id,
118 tax_id => $taxkey->tax_id,
119 taxkey_id => $taxkey->taxkey_id,
120 pos_ustva => $taxkey->pos_ustva,
121 startdate => $taxkey->startdate->to_kivitendo,
122 taxdescription => $taxkey->tax->taxdescription,
123 rate => $taxkey->tax->rate,
124 accno => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
128 # get new accounts (Folgekonto). Find all charts with the same link
129 $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});
131 } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
132 $form->{orphaned} = 1;
135 $main::lxdebug->leave_sub();
139 my ($self, $myconfig, $form) = @_;
140 $main::lxdebug->enter_sub();
142 my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
144 $::lxdebug->leave_sub;
149 # TODO: it should be forbidden to change an account to a heading if there
150 # have been bookings to this account in the past
152 my ($self, $myconfig, $form) = @_;
154 my $dbh = SL::DB->client->dbh;
156 for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
157 $form->{$form->{$_}} = $form->{$_} if $form->{$_};
160 # sanity check, can't have AR with AR_...
161 if ($form->{AR} || $form->{AP} || $form->{IC}) {
162 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)) {
163 $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
167 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);
168 $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
170 # strip blanks from accno
171 map { $form->{$_} =~ s/ //g; } qw(accno);
173 # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
174 map { $form->{$_} =~ s/\h+/ /g } qw(description);
178 if ($form->{id} eq "NULL") {
187 my @values = ($form->{accno});
190 $query .= ' AND NOT id = ?';
191 push(@values, $form->{id});
194 my ($accno) = selectrow_query($form, $dbh, $query, @values);
197 $form->error($::locale->text('Account number not unique!'));
201 if (!$form->{id} || $form->{id} eq "") {
202 $query = qq|SELECT nextval('id')|;
203 ($form->{"id"}) = selectrow_query($form, $dbh, $query);
204 $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
205 do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
213 # if charttype is heading make sure certain values are empty
214 # specifically, if charttype is changed from an existing account, empty the
215 # fields unnecessary for headings, so that e.g. heading doesn't appear in
216 # drop-down menues due to still having a valid "link" entry
218 if ( $form->{charttype} eq 'H' ) {
220 $form->{pos_bwa} = '';
221 $form->{pos_bilanz} = '';
222 $form->{pos_eur} = '';
223 $form->{new_chart_id} = '';
224 $form->{valid_from} = '';
227 $query = qq|UPDATE chart SET
245 $form->{description},
249 conv_i($form->{pos_bwa}),
250 conv_i($form->{pos_bilanz}),
251 conv_i($form->{pos_eur}),
252 conv_i($form->{pos_er}),
253 conv_i($form->{new_chart_id}),
254 conv_date($form->{valid_from}),
255 ($form->{datevautomatik} eq 'T') ? 'true':'false',
256 $form->{invalid} ? 'true' : 'false',
263 do_query($form, $dbh, $query, @values);
269 my $MAX_TRIES = 10; # Maximum count of taxkeys in form
273 for $tk_count (0 .. $MAX_TRIES) {
277 # Check if the account already exists, else cancel
279 print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
281 last READTAXKEYS if ( $form->{'id'} == 0);
283 # check if there is a startdate
284 if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
289 # Add valid taxkeys into the array
292 id => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
293 tax_id => conv_i($form->{"taxkey_tax_$tk_count"}),
294 startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
295 chart_id => conv_i($form->{"id"}),
296 pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
297 delete => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
304 for my $j (0 .. $#taxkeys){
305 if ( defined $taxkeys[$j]{'id'} ){
308 if ($taxkeys[$j]{'delete'}){
310 DELETE FROM taxkeys WHERE id = ?
313 @values = ($taxkeys[$j]{'id'});
315 do_query($form, $dbh, $query, @values);
324 SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
332 $taxkeys[$j]{'tax_id'},
333 $taxkeys[$j]{'chart_id'},
334 $taxkeys[$j]{'tax_id'},
335 $taxkeys[$j]{'pos_ustva'},
336 $taxkeys[$j]{'startdate'},
339 do_query($form, $dbh, $query, @values);
345 INSERT INTO taxkeys (
352 VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
355 $taxkeys[$j]{'tax_id'},
356 $taxkeys[$j]{'chart_id'},
357 $taxkeys[$j]{'tax_id'},
358 $taxkeys[$j]{'pos_ustva'},
359 $taxkeys[$j]{'startdate'},
362 do_query($form, $dbh, $query, @values);
367 # Update chart.taxkey_id to the latest from taxkeys for this chart.
373 WHERE taxkeys.chart_id = chart.id
374 ORDER BY startdate DESC
380 do_query($form, $dbh, $query, $form->{id});
386 my ($self, $myconfig, $form) = @_;
387 $main::lxdebug->enter_sub();
389 my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
391 $::lxdebug->leave_sub;
395 sub _delete_account {
396 my ($self, $myconfig, $form) = @_;
398 my $dbh = SL::DB->client->dbh;
400 my $query = qq|SELECT count(*) FROM acc_trans a
401 WHERE a.chart_id = ?|;
402 my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
408 $query = qq|DELETE FROM tax
410 do_query($form, $dbh, $query, $form->{id});
412 # delete account taxkeys
413 $query = qq|DELETE FROM taxkeys
415 do_query($form, $dbh, $query, $form->{id});
417 # delete chart of account record
418 # last step delete chart, because we have a constraint
420 $query = qq|DELETE FROM chart
422 do_query($form, $dbh, $query, $form->{id});
427 sub get_language_details {
428 $main::lxdebug->enter_sub();
430 my ($self, $myconfig, $form, $id) = @_;
432 my $dbh = SL::DB->client->dbh;
435 "SELECT template_code, " .
436 " output_numberformat, output_dateformat, output_longdates " .
437 "FROM language WHERE id = ?";
438 my @res = selectrow_query($form, $dbh, $query, $id);
440 $main::lxdebug->leave_sub();
445 sub prepare_template_filename {
446 $main::lxdebug->enter_sub();
448 my ($self, $myconfig, $form) = @_;
450 my ($filename, $display_filename);
452 $filename = $form->{formname};
454 if ($form->{language}) {
455 my ($id, $template_code) = split(/--/, $form->{language});
456 $filename .= "_${template_code}";
459 if ($form->{printer}) {
460 my ($id, $template_code) = split(/--/, $form->{printer});
461 $filename .= "_${template_code}";
464 $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
465 if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
466 $filename =~ s|.*/||;
468 $display_filename = $filename;
469 $filename = SL::DB::Default->get->templates . "/$filename";
471 $main::lxdebug->leave_sub();
473 return ($filename, $display_filename);
478 $main::lxdebug->enter_sub();
480 my ($self, $filename) = @_;
482 my ($content, $lines) = ("", 0);
486 if (open(TEMPLATE, $filename)) {
494 $content = Encode::decode('utf-8-strict', $content);
496 $main::lxdebug->leave_sub();
498 return ($content, $lines);
502 $main::lxdebug->enter_sub();
504 my ($self, $filename, $content) = @_;
510 if (open(TEMPLATE, ">", $filename)) {
511 $content = Encode::encode('utf-8-strict', $content);
512 $content =~ s/\r\n/\n/g;
513 print(TEMPLATE $content);
519 $main::lxdebug->leave_sub();
524 sub displayable_name_specs_by_module {
526 'SL::DB::Customer' => {
527 specs => SL::DB::Customer->displayable_name_specs,
528 prefs => SL::DB::Customer->displayable_name_prefs,
530 'SL::DB::Vendor' => {
531 specs => SL::DB::Vendor->displayable_name_specs,
532 prefs => SL::DB::Vendor->displayable_name_prefs,
535 specs => SL::DB::Part->displayable_name_specs,
536 prefs => SL::DB::Part->displayable_name_prefs,
541 sub positions_scrollbar_height {
542 SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
545 sub purchase_search_makemodel {
546 SL::Helper::UserPreferences::PartPickerSearch->new()->get_purchase_search_makemodel();
549 sub sales_search_customer_partnumber {
550 SL::Helper::UserPreferences::PartPickerSearch->new()->get_sales_search_customer_partnumber();
553 sub positions_show_update_button {
554 SL::Helper::UserPreferences::UpdatePositions->new()->get_show_update_button();
557 sub time_recording_use_duration {
558 SL::Helper::UserPreferences::TimeRecording->new()->get_use_duration();
561 sub longdescription_dialog_size_percentage {
562 SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();
566 SL::Helper::UserPreferences::DisplayPreferences->new()->get_layout_style();
569 sub part_picker_search_all_as_list_default {
570 SL::Helper::UserPreferences::PartPickerSearch->new()->get_all_as_list_default();
573 sub order_item_input_position {
574 SL::Helper::UserPreferences::ItemInputPosition->new()->get_order_item_input_position();
577 sub save_preferences {
578 $main::lxdebug->enter_sub();
580 my ($self, $form) = @_;
582 my $employee = SL::DB::Manager::Employee->current;
583 $employee->update_attributes(name => $form->{name});
585 my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
586 $user->update_attributes(
588 %{ $user->config_values },
589 map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
592 # Displayable name preferences
593 my $displayable_name_specs_by_module = displayable_name_specs_by_module();
594 foreach my $specs (@{ $form->{displayable_name_specs} }) {
595 if (!$specs->{value} || $specs->{value} eq $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->get_default()) {
596 $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->delete($specs->{value});
598 $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->store_value($specs->{value});
602 if (exists $form->{positions_scrollbar_height}) {
603 SL::Helper::UserPreferences::PositionsScrollbar->new()->store_height($form->{positions_scrollbar_height})
605 if (exists $form->{purchase_search_makemodel}) {
606 SL::Helper::UserPreferences::PartPickerSearch->new()->store_purchase_search_makemodel($form->{purchase_search_makemodel})
608 if (exists $form->{sales_search_customer_partnumber}) {
609 SL::Helper::UserPreferences::PartPickerSearch->new()->store_sales_search_customer_partnumber($form->{sales_search_customer_partnumber})
611 if (exists $form->{positions_show_update_button}) {
612 SL::Helper::UserPreferences::UpdatePositions->new()->store_show_update_button($form->{positions_show_update_button})
614 if (exists $form->{time_recording_use_duration}) {
615 SL::Helper::UserPreferences::TimeRecording->new()->store_use_duration($form->{time_recording_use_duration})
617 if (exists $form->{longdescription_dialog_size_percentage}) {
618 SL::Helper::UserPreferences::DisplayPreferences->new()->store_longdescription_dialog_size_percentage($form->{longdescription_dialog_size_percentage})
620 if (exists $form->{layout_style}) {
621 SL::Helper::UserPreferences::DisplayPreferences->new()->store_layout_style($form->{layout_style})
623 if (exists $form->{part_picker_search_all_as_list_default}) {
624 SL::Helper::UserPreferences::PartPickerSearch->new()->store_all_as_list_default($form->{part_picker_search_all_as_list_default})
626 if (exists $form->{order_item_input_position}) {
627 SL::Helper::UserPreferences::ItemInputPosition->new()->store_order_item_input_position($form->{order_item_input_position})
630 $main::lxdebug->leave_sub();
636 $main::lxdebug->enter_sub();
641 my $myconfig = \%main::myconfig;
642 my $form = $main::form;
644 my $dbh = $params{dbh} || SL::DB->client->dbh;
646 my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
648 $defaults->{weightunit} ||= 'kg';
650 $main::lxdebug->leave_sub();
656 $main::lxdebug->enter_sub();
658 my ($self, $myconfig, $form) = @_;
660 my $dbh = SL::DB->client->dbh;
662 my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
663 my $sth = $dbh->prepare($query);
664 $sth->execute || $form->dberror($query);
666 ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
670 $main::lxdebug->leave_sub();
674 $main::lxdebug->enter_sub();
676 my ($self, $myconfig, $form) = @_;
678 SL::DB->client->with_transaction(sub {
679 my $dbh = SL::DB->client->dbh;
681 my ($query, @values);
683 # is currently NEVER trueish (no more hidden revtrans in $form)
684 # if ($form->{revtrans}) {
685 # $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
686 # -> therefore you can only set this to false (which is already the default)
687 # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
689 $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
690 @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
692 # set close in defaults
693 do_query($form, $dbh, $query, @values);
695 }) or do { die SL::DB->client->error };
697 $main::lxdebug->leave_sub();
701 my ($self, $units, $unit_name, $factor) = @_;
703 $factor = 1 unless ($factor);
705 my $unit = $units->{$unit_name};
707 if (!defined($unit) || !$unit->{"base_unit"} ||
708 ($unit_name eq $unit->{"base_unit"})) {
709 return ($unit_name, $factor);
712 return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
716 $main::lxdebug->enter_sub();
718 my ($self, $myconfig, $form, $prefix) = @_;
721 my $dbh = SL::DB->client->dbh;
723 my $query = "SELECT *, base_unit AS original_base_unit FROM units";
725 my $sth = prepare_execute_query($form, $dbh, $query);
728 while (my $ref = $sth->fetchrow_hashref()) {
729 $units->{$ref->{"name"}} = $ref;
733 my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
734 $sth = $dbh->prepare($query_lang);
735 $sth->execute() || $form->dberror($query_lang);
737 while (my $ref = $sth->fetchrow_hashref()) {
738 push(@languages, $ref);
742 $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
743 "FROM units_language ul " .
744 "LEFT JOIN language l ON ul.language_id = l.id " .
746 $sth = $dbh->prepare($query_lang);
748 foreach my $unit (values(%{$units})) {
749 ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
751 $unit->{"LANGUAGES"} = {};
752 foreach my $lang (@languages) {
753 $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
756 $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
757 while (my $ref = $sth->fetchrow_hashref()) {
758 map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
763 $main::lxdebug->leave_sub();
768 sub retrieve_all_units {
769 $main::lxdebug->enter_sub();
773 if (!$::request->{cache}{all_units}) {
774 $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
777 $main::lxdebug->leave_sub();
779 return $::request->{cache}{all_units};
783 sub translate_units {
784 $main::lxdebug->enter_sub();
786 my ($self, $form, $template_code, $unit, $amount) = @_;
788 my $units = $self->retrieve_units(\%main::myconfig, $form);
790 my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
791 my $new_unit = $unit;
793 if (($amount != 1) && $h->{"localized_plural"}) {
794 $new_unit = $h->{"localized_plural"};
795 } elsif ($h->{"localized"}) {
796 $new_unit = $h->{"localized"};
800 $main::lxdebug->leave_sub();
806 $main::lxdebug->enter_sub();
808 my ($self, $myconfig, $form, $units) = @_;
810 my $dbh = SL::DB->client->dbh;
812 map({ $_->{"in_use"} = 0; } values(%{$units}));
814 foreach my $unit (values(%{$units})) {
815 my $base_unit = $unit->{"original_base_unit"};
817 $units->{$base_unit}->{"in_use"} = 1;
818 $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
819 push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
820 $base_unit = $units->{$base_unit}->{"original_base_unit"};
824 foreach my $unit (values(%{$units})) {
825 map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
827 foreach my $table (qw(parts invoice orderitems)) {
828 my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
830 if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
831 $query .= "= " . $dbh->quote($unit->{"name"});
833 $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
834 join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
837 my ($count) = $dbh->selectrow_array($query);
838 $form->dberror($query) if ($dbh->err);
841 $unit->{"in_use"} = 1;
847 $main::lxdebug->leave_sub();
850 sub convertible_units {
851 $main::lxdebug->enter_sub();
855 my $filter_unit = shift;
856 my $not_smaller = shift;
860 $filter_unit = $units->{$filter_unit};
862 foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
863 my $unit = $units->{$name};
865 if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
866 (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
867 push @{$conv_units}, $unit;
871 my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
873 $main::lxdebug->leave_sub();
878 # if $a is translatable to $b, return the factor between them.
881 $main::lxdebug->enter_sub(2);
882 my ($this, $a, $b, $all_units) = @_;
885 $all_units = $this->retrieve_all_units;
888 $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
889 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
890 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
891 $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
894 sub unit_select_data {
895 $main::lxdebug->enter_sub();
897 my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
902 push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
905 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
906 if (!$convertible_into ||
907 ($units->{$convertible_into} &&
908 ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
909 push @{$select}, { "name" => $unit,
910 "base_unit" => $units->{$unit}->{"base_unit"},
911 "factor" => $units->{$unit}->{"factor"},
912 "selected" => ($unit eq $selected) ? "selected" : "" };
916 $main::lxdebug->leave_sub();
921 sub unit_select_html {
922 $main::lxdebug->enter_sub();
924 my ($self, $units, $name, $selected, $convertible_into) = @_;
926 my $select = "<select name=${name}>";
928 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
929 if (!$convertible_into ||
930 ($units->{$convertible_into} &&
931 ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
932 $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
935 $select .= "</select>";
937 $main::lxdebug->leave_sub();
943 $main::lxdebug->enter_sub();
947 my $units = $self->retrieve_all_units();
952 while (2 <= scalar(@_)) {
954 my $unit = $units->{shift(@_)};
956 croak "No unit defined with name $unit" if (!defined $unit);
959 $base_unit = $unit->{base_unit};
960 } elsif ($base_unit ne $unit->{base_unit}) {
961 croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
964 $sum += $qty * $unit->{factor};
967 $main::lxdebug->leave_sub();
973 $main::lxdebug->enter_sub();
975 my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
977 SL::DB->client->with_transaction(sub {
978 my $dbh = SL::DB->client->dbh;
980 my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
981 my ($sortkey) = selectrow_query($form, $dbh, $query);
983 $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
984 "VALUES (?, ?, ?, ?)";
985 do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
988 $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
989 my $sth = $dbh->prepare($query);
990 foreach my $lang (@{$languages}) {
991 my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
992 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
997 }) or do { die SL::DB->client->error };
999 $main::lxdebug->leave_sub();
1003 my ($self, $myconfig, $form, $units, $delete_units) = @_;
1004 $main::lxdebug->enter_sub();
1006 my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
1008 $::lxdebug->leave_sub;
1013 my ($self, $myconfig, $form, $units, $delete_units) = @_;
1015 my $dbh = SL::DB->client->dbh;
1017 my ($base_unit, $unit, $sth, $query);
1019 $query = "DELETE FROM units_language";
1020 $dbh->do($query) || $form->dberror($query);
1022 if ($delete_units && (0 != scalar(@{$delete_units}))) {
1023 $query = "DELETE FROM units WHERE name IN (";
1024 map({ $query .= "?," } @{$delete_units});
1025 substr($query, -1, 1) = ")";
1026 $dbh->do($query, undef, @{$delete_units}) ||
1027 $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1030 $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1031 $sth = $dbh->prepare($query);
1033 my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1034 my $sth_lang = $dbh->prepare($query_lang);
1036 foreach $unit (values(%{$units})) {
1037 $unit->{"depth"} = 0;
1038 my $base_unit = $unit;
1039 while ($base_unit->{"base_unit"}) {
1041 $base_unit = $units->{$base_unit->{"base_unit"}};
1045 foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1046 if ($unit->{"LANGUAGES"}) {
1047 foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1048 next unless ($lang->{"id"} && $lang->{"localized"});
1049 my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1050 $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1054 next if ($unit->{"unchanged_unit"});
1056 my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1057 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1061 $sth_lang->finish();
1067 $main::lxdebug->enter_sub();
1069 my ($self, $myconfig, $form) = @_;
1071 my $dbh = SL::DB->client->dbh;
1073 my $query = qq|SELECT
1077 round(t.rate * 100, 2) AS rate,
1078 tc.accno AS taxnumber,
1079 tc.description AS account_description,
1080 ssc.accno AS skonto_chart_accno,
1081 ssc.description AS skonto_chart_description,
1082 spc.accno AS skonto_chart_purchase_accno,
1083 spc.description AS skonto_chart_purchase_description
1085 LEFT JOIN chart tc ON (tc.id = t.chart_id)
1086 LEFT JOIN chart ssc ON (ssc.id = t.skonto_sales_chart_id)
1087 LEFT JOIN chart spc ON (spc.id = t.skonto_purchase_chart_id)
1088 ORDER BY taxkey, rate|;
1090 my $sth = $dbh->prepare($query);
1091 $sth->execute || $form->dberror($query);
1094 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1095 push @{ $form->{TAX} }, $ref;
1100 $main::lxdebug->leave_sub();
1103 sub get_tax_accounts {
1104 $main::lxdebug->enter_sub();
1106 my ($self, $myconfig, $form) = @_;
1108 my $dbh = SL::DB->client->dbh;
1110 # get Accounts from chart
1111 my $query = qq{ SELECT
1113 accno || ' - ' || description AS taxaccount
1115 WHERE link LIKE '%_tax%'
1119 my $sth = $dbh->prepare($query);
1120 $sth->execute || $form->dberror($query);
1122 $form->{ACCOUNTS} = [];
1123 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1124 push @{ $form->{ACCOUNTS} }, $ref;
1127 $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
1128 $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
1130 $form->{skontochart_value_title_sub} = sub {
1134 $item->{accno} .' '. $item->{description},
1140 $main::lxdebug->leave_sub();
1144 $main::lxdebug->enter_sub();
1146 my ($self, $myconfig, $form) = @_;
1148 my $dbh = SL::DB->client->dbh;
1150 my $query = qq|SELECT
1153 round(rate * 100, 2) AS rate,
1156 (id IN (SELECT tax_id
1157 FROM acc_trans)) AS tax_already_used,
1158 skonto_sales_chart_id,
1159 skonto_purchase_chart_id
1163 my $sth = $dbh->prepare($query);
1164 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1166 my $ref = $sth->fetchrow_hashref("NAME_lc");
1168 map { $form->{$_} = $ref->{$_} } keys %$ref;
1172 # see if it is used by a taxkey
1173 $query = qq|SELECT count(*) FROM taxkeys
1174 WHERE tax_id = ? AND chart_id >0|;
1176 ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1178 $form->{orphaned} = !$form->{orphaned};
1181 if (!$form->{orphaned} ) {
1182 $query = qq|SELECT DISTINCT c.id, c.accno
1184 JOIN tax t ON (t.id = tk.tax_id)
1185 JOIN chart c ON (c.id = tk.chart_id)
1186 WHERE tk.tax_id = ?|;
1188 $sth = $dbh->prepare($query);
1189 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1191 $form->{TAXINUSE} = [];
1192 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1193 push @{ $form->{TAXINUSE} }, $ref;
1199 $main::lxdebug->leave_sub();
1203 my ($self, $myconfig, $form) = @_;
1204 $main::lxdebug->enter_sub();
1206 my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
1208 $::lxdebug->leave_sub;
1213 my ($self, $myconfig, $form) = @_;
1216 my $dbh = SL::DB->client->dbh;
1218 $form->{rate} = $form->{rate} / 100;
1220 my $chart_categories = '';
1221 $chart_categories .= 'A' if $form->{asset};
1222 $chart_categories .= 'L' if $form->{liability};
1223 $chart_categories .= 'Q' if $form->{equity};
1224 $chart_categories .= 'I' if $form->{revenue};
1225 $chart_categories .= 'E' if $form->{expense};
1226 $chart_categories .= 'C' if $form->{costs};
1228 my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, conv_i($form->{chart_id}), conv_i($form->{skonto_sales_chart_id}), conv_i($form->{skonto_purchase_chart_id}), $chart_categories);
1229 if ($form->{id} ne "") {
1230 $query = qq|UPDATE tax SET
1235 skonto_sales_chart_id = ?,
1236 skonto_purchase_chart_id = ?,
1237 chart_categories = ?
1242 ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
1243 $query = qq|INSERT INTO tax (
1248 skonto_sales_chart_id,
1249 skonto_purchase_chart_id,
1253 VALUES (?, ?, ?, ?, ?, ?, ?, ?)|;
1255 push(@values, $form->{id});
1256 do_query($form, $dbh, $query, @values);
1258 foreach my $language_id (keys %{ $form->{translations} }) {
1259 GenericTranslations->save('dbh' => $dbh,
1260 'translation_type' => 'SL::DB::Tax/taxdescription',
1261 'translation_id' => $form->{id},
1262 'language_id' => $language_id,
1263 'translation' => $form->{translations}->{$language_id});
1268 $main::lxdebug->enter_sub();
1270 my ($self, $myconfig, $form) = @_;
1273 SL::DB->client->with_transaction(sub {
1274 $query = qq|DELETE FROM tax WHERE id = ?|;
1275 do_query($form, SL::DB->client->dbh, $query, $form->{id});
1277 }) or do { die SL::DB->client->error };
1279 $main::lxdebug->leave_sub();
1282 sub save_warehouse {
1283 $main::lxdebug->enter_sub();
1285 my ($self, $myconfig, $form) = @_;
1287 croak('Need at least one new bin') unless $form->{number_of_new_bins} > 0;
1289 SL::DB->client->with_transaction(sub {
1290 my $dbh = SL::DB->client->dbh;
1292 my ($query, @values, $sth);
1295 $query = qq|SELECT nextval('id')|;
1296 ($form->{id}) = selectrow_query($form, $dbh, $query);
1298 $query = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1299 do_query($form, $dbh, $query, $form->{id});
1302 do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1303 $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1305 if (0 < $form->{number_of_new_bins}) {
1306 my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
1307 $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1308 $sth = prepare_query($form, $dbh, $query);
1310 foreach my $i (1..$form->{number_of_new_bins}) {
1311 do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
1317 }) or do { die SL::DB->client->error };
1319 $main::lxdebug->leave_sub();
1323 $main::lxdebug->enter_sub();
1325 my ($self, $myconfig, $form) = @_;
1327 SL::DB->client->with_transaction(sub {
1328 my $dbh = SL::DB->client->dbh;
1330 my ($query, @values, $sth);
1332 @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1335 $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1336 do_query($form, $dbh, $query, @values);
1339 $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1340 $sth = prepare_query($form, $dbh, $query);
1342 foreach my $row (1..$form->{rowcount}) {
1343 next if ($form->{"delete_${row}"});
1345 do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1350 }) or do { die SL::DB->client->error };
1352 $main::lxdebug->leave_sub();
1355 sub delete_warehouse {
1356 $main::lxdebug->enter_sub();
1358 my ($self, $myconfig, $form) = @_;
1360 my $rc = SL::DB->client->with_transaction(sub {
1361 my $dbh = SL::DB->client->dbh;
1363 my $id = conv_i($form->{id});
1364 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|;
1365 my ($count) = selectrow_query($form, $dbh, $query, $id);
1371 do_query($form, $dbh, qq|DELETE FROM bin WHERE warehouse_id = ?|, conv_i($form->{id}));
1372 do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id = ?|, conv_i($form->{id}));
1377 $main::lxdebug->leave_sub();
1382 sub get_all_warehouses {
1383 $main::lxdebug->enter_sub();
1385 my ($self, $myconfig, $form) = @_;
1387 my $dbh = SL::DB->client->dbh;
1389 my $query = qq|SELECT w.id, w.description, w.invalid,
1390 (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
1392 ORDER BY w.sortkey|;
1394 $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
1396 $main::lxdebug->leave_sub();
1400 $main::lxdebug->enter_sub();
1402 my ($self, $myconfig, $form) = @_;
1404 my $dbh = SL::DB->client->dbh;
1406 my $id = conv_i($form->{id});
1407 my $query = qq|SELECT w.description, w.invalid
1411 my $ref = selectfirst_hashref_query($form, $dbh, $query, $id);
1413 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1416 SELECT b.*, use.in_use
1419 SELECT DISTINCT bin_id, TRUE AS in_use FROM inventory
1421 SELECT DISTINCT bin_id, TRUE AS in_use FROM parts
1422 ) use ON use.bin_id = b.id
1423 WHERE b.warehouse_id = ?
1424 ORDER by description;
1427 $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1429 $main::lxdebug->leave_sub();
1432 sub get_eur_categories {
1433 my ($self, $myconfig, $form) = @_;
1435 my $dbh = SL::DB->client->dbh;
1436 my %eur_categories = selectall_as_map($form, $dbh, "select * from eur_categories order by id", 'id', 'description');
1438 return \%eur_categories;
1441 sub get_bwa_categories {
1442 my ($self, $myconfig, $form) = @_;
1444 my $dbh = SL::DB->client->dbh;
1445 my %bwa_categories = selectall_as_map($form, $dbh, "select * from bwa_categories order by id", 'id', 'description');
1447 return \%bwa_categories;