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;
57 use SL::Helper::UserPreferences::UpdatePositions;
62 $main::lxdebug->enter_sub();
64 # fetch chart-related data and set form fields
65 # get_account is called by add_account in am.pl
66 # always sets $form->{TAXKEY} and default_accounts
67 # loads chart data when $form->{id} is passed
69 my ($self, $myconfig, $form) = @_;
71 # get default accounts
72 map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
75 my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
77 foreach my $tk ( @{$taxes} ) {
78 push @{ $form->{TAXKEY} }, { id => $tk->id,
79 chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
80 taxkey => $tk->taxkey,
81 tax => $tk->id . '--' . $tk->taxkey,
88 my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
90 my @chart_fields = qw(accno description charttype category link pos_bilanz
91 pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik);
92 foreach my $cf ( @chart_fields ) {
93 $form->{"$cf"} = $chart_obj->$cf;
96 my $active_taxkey = $chart_obj->get_active_taxkey;
97 $form->{$_} = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
98 $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
100 # check if there are any transactions for this chart
101 $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
103 # check if new account is active
104 # The old sql query was broken since at least 2006 and always returned 0
105 $form->{new_chart_valid} = $chart_obj->new_chart_valid;
107 # get the taxkeys of the account
108 $form->{ACCOUNT_TAXKEYS} = [];
109 foreach my $taxkey ( sort { $b->startdate <=> $a->startdate } @{ $chart_obj->taxkeys } ) {
110 push @{ $form->{ACCOUNT_TAXKEYS} }, { id => $taxkey->id,
111 chart_id => $taxkey->chart_id,
112 tax_id => $taxkey->tax_id,
113 taxkey_id => $taxkey->taxkey_id,
114 pos_ustva => $taxkey->pos_ustva,
115 startdate => $taxkey->startdate->to_kivitendo,
116 taxdescription => $taxkey->tax->taxdescription,
117 rate => $taxkey->tax->rate,
118 accno => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
122 # get new accounts (Folgekonto). Find all charts with the same link
123 $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});
125 } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
126 $form->{orphaned} = 1;
129 $main::lxdebug->leave_sub();
133 my ($self, $myconfig, $form) = @_;
134 $main::lxdebug->enter_sub();
136 my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
138 $::lxdebug->leave_sub;
143 # TODO: it should be forbidden to change an account to a heading if there
144 # have been bookings to this account in the past
146 my ($self, $myconfig, $form) = @_;
148 my $dbh = SL::DB->client->dbh;
150 for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
151 $form->{$form->{$_}} = $form->{$_} if $form->{$_};
154 # sanity check, can't have AR with AR_...
155 if ($form->{AR} || $form->{AP} || $form->{IC}) {
156 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)) {
157 $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
161 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);
162 $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
164 # strip blanks from accno
165 map { $form->{$_} =~ s/ //g; } qw(accno);
167 # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
168 map { $form->{$_} =~ s/\h+/ /g } qw(description);
172 if ($form->{id} eq "NULL") {
181 my @values = ($form->{accno});
184 $query .= ' AND NOT id = ?';
185 push(@values, $form->{id});
188 my ($accno) = selectrow_query($form, $dbh, $query, @values);
191 $form->error($::locale->text('Account number not unique!'));
195 if (!$form->{id} || $form->{id} eq "") {
196 $query = qq|SELECT nextval('id')|;
197 ($form->{"id"}) = selectrow_query($form, $dbh, $query);
198 $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
199 do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
207 # if charttype is heading make sure certain values are empty
208 # specifically, if charttype is changed from an existing account, empty the
209 # fields unnecessary for headings, so that e.g. heading doesn't appear in
210 # drop-down menues due to still having a valid "link" entry
212 if ( $form->{charttype} eq 'H' ) {
214 $form->{pos_bwa} = '';
215 $form->{pos_bilanz} = '';
216 $form->{pos_eur} = '';
217 $form->{new_chart_id} = '';
218 $form->{valid_from} = '';
221 $query = qq|UPDATE chart SET
238 $form->{description},
242 conv_i($form->{pos_bwa}),
243 conv_i($form->{pos_bilanz}),
244 conv_i($form->{pos_eur}),
245 conv_i($form->{pos_er}),
246 conv_i($form->{new_chart_id}),
247 conv_date($form->{valid_from}),
248 ($form->{datevautomatik} eq 'T') ? 'true':'false',
255 do_query($form, $dbh, $query, @values);
261 my $MAX_TRIES = 10; # Maximum count of taxkeys in form
265 for $tk_count (0 .. $MAX_TRIES) {
269 # Check if the account already exists, else cancel
271 print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
273 last READTAXKEYS if ( $form->{'id'} == 0);
275 # check if there is a startdate
276 if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
281 # Add valid taxkeys into the array
284 id => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
285 tax_id => conv_i($form->{"taxkey_tax_$tk_count"}),
286 startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
287 chart_id => conv_i($form->{"id"}),
288 pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
289 delete => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
296 for my $j (0 .. $#taxkeys){
297 if ( defined $taxkeys[$j]{'id'} ){
300 if ($taxkeys[$j]{'delete'}){
302 DELETE FROM taxkeys WHERE id = ?
305 @values = ($taxkeys[$j]{'id'});
307 do_query($form, $dbh, $query, @values);
316 SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
324 $taxkeys[$j]{'tax_id'},
325 $taxkeys[$j]{'chart_id'},
326 $taxkeys[$j]{'tax_id'},
327 $taxkeys[$j]{'pos_ustva'},
328 $taxkeys[$j]{'startdate'},
331 do_query($form, $dbh, $query, @values);
337 INSERT INTO taxkeys (
344 VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
347 $taxkeys[$j]{'tax_id'},
348 $taxkeys[$j]{'chart_id'},
349 $taxkeys[$j]{'tax_id'},
350 $taxkeys[$j]{'pos_ustva'},
351 $taxkeys[$j]{'startdate'},
354 do_query($form, $dbh, $query, @values);
359 # Update chart.taxkey_id to the latest from taxkeys for this chart.
365 WHERE taxkeys.chart_id = chart.id
366 ORDER BY startdate DESC
372 do_query($form, $dbh, $query, $form->{id});
378 my ($self, $myconfig, $form) = @_;
379 $main::lxdebug->enter_sub();
381 my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
383 $::lxdebug->leave_sub;
387 sub _delete_account {
388 my ($self, $myconfig, $form) = @_;
390 my $dbh = SL::DB->client->dbh;
392 my $query = qq|SELECT count(*) FROM acc_trans a
393 WHERE a.chart_id = ?|;
394 my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
400 $query = qq|DELETE FROM tax
402 do_query($form, $dbh, $query, $form->{id});
404 # delete account taxkeys
405 $query = qq|DELETE FROM taxkeys
407 do_query($form, $dbh, $query, $form->{id});
409 # delete chart of account record
410 # last step delete chart, because we have a constraint
412 $query = qq|DELETE FROM chart
414 do_query($form, $dbh, $query, $form->{id});
419 sub get_language_details {
420 $main::lxdebug->enter_sub();
422 my ($self, $myconfig, $form, $id) = @_;
424 my $dbh = SL::DB->client->dbh;
427 "SELECT template_code, " .
428 " output_numberformat, output_dateformat, output_longdates " .
429 "FROM language WHERE id = ?";
430 my @res = selectrow_query($form, $dbh, $query, $id);
432 $main::lxdebug->leave_sub();
437 sub prepare_template_filename {
438 $main::lxdebug->enter_sub();
440 my ($self, $myconfig, $form) = @_;
442 my ($filename, $display_filename);
444 $filename = $form->{formname};
446 if ($form->{language}) {
447 my ($id, $template_code) = split(/--/, $form->{language});
448 $filename .= "_${template_code}";
451 if ($form->{printer}) {
452 my ($id, $template_code) = split(/--/, $form->{printer});
453 $filename .= "_${template_code}";
456 $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
457 if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
458 $filename =~ s|.*/||;
460 $display_filename = $filename;
461 $filename = SL::DB::Default->get->templates . "/$filename";
463 $main::lxdebug->leave_sub();
465 return ($filename, $display_filename);
470 $main::lxdebug->enter_sub();
472 my ($self, $filename) = @_;
474 my ($content, $lines) = ("", 0);
478 if (open(TEMPLATE, $filename)) {
486 $content = Encode::decode('utf-8-strict', $content);
488 $main::lxdebug->leave_sub();
490 return ($content, $lines);
494 $main::lxdebug->enter_sub();
496 my ($self, $filename, $content) = @_;
502 if (open(TEMPLATE, ">", $filename)) {
503 $content = Encode::encode('utf-8-strict', $content);
504 $content =~ s/\r\n/\n/g;
505 print(TEMPLATE $content);
511 $main::lxdebug->leave_sub();
516 sub displayable_name_specs_by_module {
518 'SL::DB::Customer' => {
519 specs => SL::DB::Customer->displayable_name_specs,
520 prefs => SL::DB::Customer->displayable_name_prefs,
522 'SL::DB::Vendor' => {
523 specs => SL::DB::Vendor->displayable_name_specs,
524 prefs => SL::DB::Vendor->displayable_name_prefs,
527 specs => SL::DB::Part->displayable_name_specs,
528 prefs => SL::DB::Part->displayable_name_prefs,
533 sub positions_scrollbar_height {
534 SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
537 sub purchase_search_makemodel {
538 SL::Helper::UserPreferences::PartPickerSearch->new()->get_purchase_search_makemodel();
541 sub sales_search_customer_partnumber {
542 SL::Helper::UserPreferences::PartPickerSearch->new()->get_sales_search_customer_partnumber();
545 sub positions_show_update_button {
546 SL::Helper::UserPreferences::UpdatePositions->new()->get_show_update_button();
549 sub save_preferences {
550 $main::lxdebug->enter_sub();
552 my ($self, $form) = @_;
554 my $employee = SL::DB::Manager::Employee->find_by(login => $::myconfig{login});
555 $employee->update_attributes(name => $form->{name});
557 my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
558 $user->update_attributes(
560 %{ $user->config_values },
561 map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
564 # Displayable name preferences
565 my $displayable_name_specs_by_module = displayable_name_specs_by_module();
566 foreach my $specs (@{ $form->{displayable_name_specs} }) {
567 if (!$specs->{value} || $specs->{value} eq $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->get_default()) {
568 $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->delete($specs->{value});
570 $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->store_value($specs->{value});
574 if (exists $form->{positions_scrollbar_height}) {
575 SL::Helper::UserPreferences::PositionsScrollbar->new()->store_height($form->{positions_scrollbar_height})
577 if (exists $form->{purchase_search_makemodel}) {
578 SL::Helper::UserPreferences::PartPickerSearch->new()->store_purchase_search_makemodel($form->{purchase_search_makemodel})
580 if (exists $form->{sales_search_customer_partnumber}) {
581 SL::Helper::UserPreferences::PartPickerSearch->new()->store_sales_search_customer_partnumber($form->{sales_search_customer_partnumber})
583 if (exists $form->{positions_show_update_button}) {
584 SL::Helper::UserPreferences::UpdatePositions->new()->store_show_update_button($form->{positions_show_update_button})
587 $main::lxdebug->leave_sub();
593 $main::lxdebug->enter_sub();
598 my $myconfig = \%main::myconfig;
599 my $form = $main::form;
601 my $dbh = $params{dbh} || SL::DB->client->dbh;
603 my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
605 $defaults->{weightunit} ||= 'kg';
607 $main::lxdebug->leave_sub();
613 $main::lxdebug->enter_sub();
615 my ($self, $myconfig, $form) = @_;
617 my $dbh = SL::DB->client->dbh;
619 my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
620 my $sth = $dbh->prepare($query);
621 $sth->execute || $form->dberror($query);
623 ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
627 $main::lxdebug->leave_sub();
631 $main::lxdebug->enter_sub();
633 my ($self, $myconfig, $form) = @_;
635 SL::DB->client->with_transaction(sub {
636 my $dbh = SL::DB->client->dbh;
638 my ($query, @values);
640 # is currently NEVER trueish (no more hidden revtrans in $form)
641 # if ($form->{revtrans}) {
642 # $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
643 # -> therefore you can only set this to false (which is already the default)
644 # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
646 $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
647 @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
649 # set close in defaults
650 do_query($form, $dbh, $query, @values);
652 }) or do { die SL::DB->client->error };
654 $main::lxdebug->leave_sub();
658 my ($self, $units, $unit_name, $factor) = @_;
660 $factor = 1 unless ($factor);
662 my $unit = $units->{$unit_name};
664 if (!defined($unit) || !$unit->{"base_unit"} ||
665 ($unit_name eq $unit->{"base_unit"})) {
666 return ($unit_name, $factor);
669 return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
673 $main::lxdebug->enter_sub();
675 my ($self, $myconfig, $form, $prefix) = @_;
678 my $dbh = SL::DB->client->dbh;
680 my $query = "SELECT *, base_unit AS original_base_unit FROM units";
682 my $sth = prepare_execute_query($form, $dbh, $query);
685 while (my $ref = $sth->fetchrow_hashref()) {
686 $units->{$ref->{"name"}} = $ref;
690 my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
691 $sth = $dbh->prepare($query_lang);
692 $sth->execute() || $form->dberror($query_lang);
694 while (my $ref = $sth->fetchrow_hashref()) {
695 push(@languages, $ref);
699 $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
700 "FROM units_language ul " .
701 "LEFT JOIN language l ON ul.language_id = l.id " .
703 $sth = $dbh->prepare($query_lang);
705 foreach my $unit (values(%{$units})) {
706 ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
708 $unit->{"LANGUAGES"} = {};
709 foreach my $lang (@languages) {
710 $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
713 $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
714 while (my $ref = $sth->fetchrow_hashref()) {
715 map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
720 $main::lxdebug->leave_sub();
725 sub retrieve_all_units {
726 $main::lxdebug->enter_sub();
730 if (!$::request->{cache}{all_units}) {
731 $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
734 $main::lxdebug->leave_sub();
736 return $::request->{cache}{all_units};
740 sub translate_units {
741 $main::lxdebug->enter_sub();
743 my ($self, $form, $template_code, $unit, $amount) = @_;
745 my $units = $self->retrieve_units(\%main::myconfig, $form);
747 my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
748 my $new_unit = $unit;
750 if (($amount != 1) && $h->{"localized_plural"}) {
751 $new_unit = $h->{"localized_plural"};
752 } elsif ($h->{"localized"}) {
753 $new_unit = $h->{"localized"};
757 $main::lxdebug->leave_sub();
763 $main::lxdebug->enter_sub();
765 my ($self, $myconfig, $form, $units) = @_;
767 my $dbh = SL::DB->client->dbh;
769 map({ $_->{"in_use"} = 0; } values(%{$units}));
771 foreach my $unit (values(%{$units})) {
772 my $base_unit = $unit->{"original_base_unit"};
774 $units->{$base_unit}->{"in_use"} = 1;
775 $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
776 push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
777 $base_unit = $units->{$base_unit}->{"original_base_unit"};
781 foreach my $unit (values(%{$units})) {
782 map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
784 foreach my $table (qw(parts invoice orderitems)) {
785 my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
787 if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
788 $query .= "= " . $dbh->quote($unit->{"name"});
790 $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
791 join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
794 my ($count) = $dbh->selectrow_array($query);
795 $form->dberror($query) if ($dbh->err);
798 $unit->{"in_use"} = 1;
804 $main::lxdebug->leave_sub();
807 sub convertible_units {
808 $main::lxdebug->enter_sub();
812 my $filter_unit = shift;
813 my $not_smaller = shift;
817 $filter_unit = $units->{$filter_unit};
819 foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
820 my $unit = $units->{$name};
822 if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
823 (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
824 push @{$conv_units}, $unit;
828 my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
830 $main::lxdebug->leave_sub();
835 # if $a is translatable to $b, return the factor between them.
838 $main::lxdebug->enter_sub(2);
839 my ($this, $a, $b, $all_units) = @_;
842 $all_units = $this->retrieve_all_units;
845 $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
846 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
847 $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
848 $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
851 sub unit_select_data {
852 $main::lxdebug->enter_sub();
854 my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
859 push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
862 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
863 if (!$convertible_into ||
864 ($units->{$convertible_into} &&
865 ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
866 push @{$select}, { "name" => $unit,
867 "base_unit" => $units->{$unit}->{"base_unit"},
868 "factor" => $units->{$unit}->{"factor"},
869 "selected" => ($unit eq $selected) ? "selected" : "" };
873 $main::lxdebug->leave_sub();
878 sub unit_select_html {
879 $main::lxdebug->enter_sub();
881 my ($self, $units, $name, $selected, $convertible_into) = @_;
883 my $select = "<select name=${name}>";
885 foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
886 if (!$convertible_into ||
887 ($units->{$convertible_into} &&
888 ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
889 $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
892 $select .= "</select>";
894 $main::lxdebug->leave_sub();
900 $main::lxdebug->enter_sub();
904 my $units = $self->retrieve_all_units();
909 while (2 <= scalar(@_)) {
911 my $unit = $units->{shift(@_)};
913 croak "No unit defined with name $unit" if (!defined $unit);
916 $base_unit = $unit->{base_unit};
917 } elsif ($base_unit ne $unit->{base_unit}) {
918 croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
921 $sum += $qty * $unit->{factor};
924 $main::lxdebug->leave_sub();
930 $main::lxdebug->enter_sub();
932 my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
934 SL::DB->client->with_transaction(sub {
935 my $dbh = SL::DB->client->dbh;
937 my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
938 my ($sortkey) = selectrow_query($form, $dbh, $query);
940 $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
941 "VALUES (?, ?, ?, ?)";
942 do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
945 $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
946 my $sth = $dbh->prepare($query);
947 foreach my $lang (@{$languages}) {
948 my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
949 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
954 }) or do { die SL::DB->client->error };
956 $main::lxdebug->leave_sub();
960 my ($self, $myconfig, $form, $units, $delete_units) = @_;
961 $main::lxdebug->enter_sub();
963 my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
965 $::lxdebug->leave_sub;
970 my ($self, $myconfig, $form, $units, $delete_units) = @_;
972 my $dbh = SL::DB->client->dbh;
974 my ($base_unit, $unit, $sth, $query);
976 $query = "DELETE FROM units_language";
977 $dbh->do($query) || $form->dberror($query);
979 if ($delete_units && (0 != scalar(@{$delete_units}))) {
980 $query = "DELETE FROM units WHERE name IN (";
981 map({ $query .= "?," } @{$delete_units});
982 substr($query, -1, 1) = ")";
983 $dbh->do($query, undef, @{$delete_units}) ||
984 $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
987 $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
988 $sth = $dbh->prepare($query);
990 my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
991 my $sth_lang = $dbh->prepare($query_lang);
993 foreach $unit (values(%{$units})) {
994 $unit->{"depth"} = 0;
995 my $base_unit = $unit;
996 while ($base_unit->{"base_unit"}) {
998 $base_unit = $units->{$base_unit->{"base_unit"}};
1002 foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1003 if ($unit->{"LANGUAGES"}) {
1004 foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1005 next unless ($lang->{"id"} && $lang->{"localized"});
1006 my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1007 $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1011 next if ($unit->{"unchanged_unit"});
1013 my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1014 $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1018 $sth_lang->finish();
1024 $main::lxdebug->enter_sub();
1026 my ($self, $myconfig, $form) = @_;
1028 my $dbh = SL::DB->client->dbh;
1030 my $query = qq|SELECT
1034 round(t.rate * 100, 2) AS rate,
1035 tc.accno AS taxnumber,
1036 tc.description AS account_description,
1037 ssc.accno AS skonto_chart_accno,
1038 ssc.description AS skonto_chart_description,
1039 spc.accno AS skonto_chart_purchase_accno,
1040 spc.description AS skonto_chart_purchase_description
1042 LEFT JOIN chart tc ON (tc.id = t.chart_id)
1043 LEFT JOIN chart ssc ON (ssc.id = t.skonto_sales_chart_id)
1044 LEFT JOIN chart spc ON (spc.id = t.skonto_purchase_chart_id)
1045 ORDER BY taxkey, rate|;
1047 my $sth = $dbh->prepare($query);
1048 $sth->execute || $form->dberror($query);
1051 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1052 push @{ $form->{TAX} }, $ref;
1057 $main::lxdebug->leave_sub();
1060 sub get_tax_accounts {
1061 $main::lxdebug->enter_sub();
1063 my ($self, $myconfig, $form) = @_;
1065 my $dbh = SL::DB->client->dbh;
1067 # get Accounts from chart
1068 my $query = qq{ SELECT
1070 accno || ' - ' || description AS taxaccount
1072 WHERE link LIKE '%_tax%'
1076 my $sth = $dbh->prepare($query);
1077 $sth->execute || $form->dberror($query);
1079 $form->{ACCOUNTS} = [];
1080 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1081 push @{ $form->{ACCOUNTS} }, $ref;
1084 $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
1085 $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
1087 $form->{skontochart_value_title_sub} = sub {
1091 $item->{accno} .' '. $item->{description},
1097 $main::lxdebug->leave_sub();
1101 $main::lxdebug->enter_sub();
1103 my ($self, $myconfig, $form) = @_;
1105 my $dbh = SL::DB->client->dbh;
1107 my $query = qq|SELECT
1110 round(rate * 100, 2) AS rate,
1113 (id IN (SELECT tax_id
1114 FROM acc_trans)) AS tax_already_used,
1115 skonto_sales_chart_id,
1116 skonto_purchase_chart_id
1120 my $sth = $dbh->prepare($query);
1121 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1123 my $ref = $sth->fetchrow_hashref("NAME_lc");
1125 map { $form->{$_} = $ref->{$_} } keys %$ref;
1129 # see if it is used by a taxkey
1130 $query = qq|SELECT count(*) FROM taxkeys
1131 WHERE tax_id = ? AND chart_id >0|;
1133 ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1135 $form->{orphaned} = !$form->{orphaned};
1138 if (!$form->{orphaned} ) {
1139 $query = qq|SELECT DISTINCT c.id, c.accno
1141 JOIN tax t ON (t.id = tk.tax_id)
1142 JOIN chart c ON (c.id = tk.chart_id)
1143 WHERE tk.tax_id = ?|;
1145 $sth = $dbh->prepare($query);
1146 $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1148 $form->{TAXINUSE} = [];
1149 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1150 push @{ $form->{TAXINUSE} }, $ref;
1156 $main::lxdebug->leave_sub();
1160 my ($self, $myconfig, $form) = @_;
1161 $main::lxdebug->enter_sub();
1163 my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
1165 $::lxdebug->leave_sub;
1170 my ($self, $myconfig, $form) = @_;
1173 my $dbh = SL::DB->client->dbh;
1175 $form->{rate} = $form->{rate} / 100;
1177 my $chart_categories = '';
1178 $chart_categories .= 'A' if $form->{asset};
1179 $chart_categories .= 'L' if $form->{liability};
1180 $chart_categories .= 'Q' if $form->{equity};
1181 $chart_categories .= 'I' if $form->{revenue};
1182 $chart_categories .= 'E' if $form->{expense};
1183 $chart_categories .= 'C' if $form->{costs};
1185 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);
1186 if ($form->{id} ne "") {
1187 $query = qq|UPDATE tax SET
1192 skonto_sales_chart_id = ?,
1193 skonto_purchase_chart_id = ?,
1194 chart_categories = ?
1199 ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
1200 $query = qq|INSERT INTO tax (
1205 skonto_sales_chart_id,
1206 skonto_purchase_chart_id,
1210 VALUES (?, ?, ?, ?, ?, ?, ?, ?)|;
1212 push(@values, $form->{id});
1213 do_query($form, $dbh, $query, @values);
1215 foreach my $language_id (keys %{ $form->{translations} }) {
1216 GenericTranslations->save('dbh' => $dbh,
1217 'translation_type' => 'SL::DB::Tax/taxdescription',
1218 'translation_id' => $form->{id},
1219 'language_id' => $language_id,
1220 'translation' => $form->{translations}->{$language_id});
1225 $main::lxdebug->enter_sub();
1227 my ($self, $myconfig, $form) = @_;
1230 SL::DB->client->with_transaction(sub {
1231 $query = qq|DELETE FROM tax WHERE id = ?|;
1232 do_query($form, SL::DB->client->dbh, $query, $form->{id});
1234 }) or do { die SL::DB->client->error };
1236 $main::lxdebug->leave_sub();
1239 sub save_warehouse {
1240 $main::lxdebug->enter_sub();
1242 my ($self, $myconfig, $form) = @_;
1244 SL::DB->client->with_transaction(sub {
1245 my $dbh = SL::DB->client->dbh;
1247 my ($query, @values, $sth);
1250 $query = qq|SELECT nextval('id')|;
1251 ($form->{id}) = selectrow_query($form, $dbh, $query);
1253 $query = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1254 do_query($form, $dbh, $query, $form->{id});
1257 do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1258 $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1260 if (0 < $form->{number_of_new_bins}) {
1261 my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
1262 $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1263 $sth = prepare_query($form, $dbh, $query);
1265 foreach my $i (1..$form->{number_of_new_bins}) {
1266 do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
1272 }) or do { die SL::DB->client->error };
1274 $main::lxdebug->leave_sub();
1278 $main::lxdebug->enter_sub();
1280 my ($self, $myconfig, $form) = @_;
1282 SL::DB->client->with_transaction(sub {
1283 my $dbh = SL::DB->client->dbh;
1285 my ($query, @values, $sth);
1287 @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1290 $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1291 do_query($form, $dbh, $query, @values);
1294 $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1295 $sth = prepare_query($form, $dbh, $query);
1297 foreach my $row (1..$form->{rowcount}) {
1298 next if ($form->{"delete_${row}"});
1300 do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1305 }) or do { die SL::DB->client->error };
1307 $main::lxdebug->leave_sub();
1310 sub delete_warehouse {
1311 $main::lxdebug->enter_sub();
1313 my ($self, $myconfig, $form) = @_;
1315 my $rc = SL::DB->client->with_transaction(sub {
1316 my $dbh = SL::DB->client->dbh;
1318 my $id = conv_i($form->{id});
1319 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|;
1320 my ($count) = selectrow_query($form, $dbh, $query, $id);
1326 do_query($form, $dbh, qq|DELETE FROM bin WHERE warehouse_id = ?|, conv_i($form->{id}));
1327 do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id = ?|, conv_i($form->{id}));
1332 $main::lxdebug->leave_sub();
1337 sub get_all_warehouses {
1338 $main::lxdebug->enter_sub();
1340 my ($self, $myconfig, $form) = @_;
1342 my $dbh = SL::DB->client->dbh;
1344 my $query = qq|SELECT w.id, w.description, w.invalid,
1345 (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
1347 ORDER BY w.sortkey|;
1349 $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
1351 $main::lxdebug->leave_sub();
1355 $main::lxdebug->enter_sub();
1357 my ($self, $myconfig, $form) = @_;
1359 my $dbh = SL::DB->client->dbh;
1361 my $id = conv_i($form->{id});
1362 my $query = qq|SELECT w.description, w.invalid
1366 my $ref = selectfirst_hashref_query($form, $dbh, $query, $id);
1368 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1371 SELECT b.*, use.in_use
1374 SELECT DISTINCT bin_id, TRUE AS in_use FROM inventory
1376 SELECT DISTINCT bin_id, TRUE AS in_use FROM parts
1377 ) use ON use.bin_id = b.id
1378 WHERE b.warehouse_id = ?;
1381 $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1383 $main::lxdebug->leave_sub();
1386 sub get_eur_categories {
1387 my ($self, $myconfig, $form) = @_;
1389 my $dbh = SL::DB->client->dbh;
1390 my %eur_categories = selectall_as_map($form, $dbh, "select * from eur_categories order by id", 'id', 'description');
1392 return \%eur_categories;
1395 sub get_bwa_categories {
1396 my ($self, $myconfig, $form) = @_;
1398 my $dbh = SL::DB->client->dbh;
1399 my %bwa_categories = selectall_as_map($form, $dbh, "select * from bwa_categories order by id", 'id', 'description');
1401 return \%bwa_categories;