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;
 
  64   $main::lxdebug->enter_sub();
 
  66   # fetch chart-related data and set form fields
 
  67   # get_account is called by add_account in am.pl
 
  68   # always sets $form->{TAXKEY} and default_accounts
 
  69   # loads chart data when $form->{id} is passed
 
  71   my ($self, $myconfig, $form) = @_;
 
  73   # get default accounts
 
  74   map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
 
  77   my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
 
  79   foreach my $tk ( @{$taxes} ) {
 
  80     push @{ $form->{TAXKEY} },  { id          => $tk->id,
 
  81                                   chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
 
  82                                   taxkey      => $tk->taxkey,
 
  83                                   tax         => $tk->id . '--' . $tk->taxkey,
 
  90     my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
 
  92     my @chart_fields = qw(accno description charttype category link pos_bilanz
 
  93                           pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik);
 
  94     foreach my $cf ( @chart_fields ) {
 
  95       $form->{"$cf"} = $chart_obj->$cf;
 
  98     my $active_taxkey = $chart_obj->get_active_taxkey;
 
  99     $form->{$_}  = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
 
 100     $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
 
 102     # check if there are any transactions for this chart
 
 103     $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
 
 105     # check if new account is active
 
 106     # The old sql query was broken since at least 2006 and always returned 0
 
 107     $form->{new_chart_valid} = $chart_obj->new_chart_valid;
 
 109     # get the taxkeys of the account
 
 110     $form->{ACCOUNT_TAXKEYS} = [];
 
 111     foreach my $taxkey ( sort { $b->startdate <=> $a->startdate } @{ $chart_obj->taxkeys } ) {
 
 112       push @{ $form->{ACCOUNT_TAXKEYS} }, { id             => $taxkey->id,
 
 113                                             chart_id       => $taxkey->chart_id,
 
 114                                             tax_id         => $taxkey->tax_id,
 
 115                                             taxkey_id      => $taxkey->taxkey_id,
 
 116                                             pos_ustva      => $taxkey->pos_ustva,
 
 117                                             startdate      => $taxkey->startdate->to_kivitendo,
 
 118                                             taxdescription => $taxkey->tax->taxdescription,
 
 119                                             rate           => $taxkey->tax->rate,
 
 120                                             accno          => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
 
 124     # get new accounts (Folgekonto). Find all charts with the same link
 
 125     $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});
 
 127   } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
 
 128     $form->{orphaned} = 1;
 
 131   $main::lxdebug->leave_sub();
 
 135   my ($self, $myconfig, $form) = @_;
 
 136   $main::lxdebug->enter_sub();
 
 138   my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
 
 140   $::lxdebug->leave_sub;
 
 145   # TODO: it should be forbidden to change an account to a heading if there
 
 146   # have been bookings to this account in the past
 
 148   my ($self, $myconfig, $form) = @_;
 
 150   my $dbh = SL::DB->client->dbh;
 
 152   for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
 
 153     $form->{$form->{$_}} = $form->{$_} if $form->{$_};
 
 156   # sanity check, can't have AR with AR_...
 
 157   if ($form->{AR} || $form->{AP} || $form->{IC}) {
 
 158     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)) {
 
 159       $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
 
 163   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);
 
 164   $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
 
 166   # strip blanks from accno
 
 167   map { $form->{$_} =~ s/ //g; } qw(accno);
 
 169   # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
 
 170   map { $form->{$_} =~ s/\h+/ /g } qw(description);
 
 174   if ($form->{id} eq "NULL") {
 
 183   my @values = ($form->{accno});
 
 186     $query .= ' AND NOT id = ?';
 
 187     push(@values, $form->{id});
 
 190   my ($accno) = selectrow_query($form, $dbh, $query, @values);
 
 193     $form->error($::locale->text('Account number not unique!'));
 
 197   if (!$form->{id} || $form->{id} eq "") {
 
 198     $query = qq|SELECT nextval('id')|;
 
 199     ($form->{"id"}) = selectrow_query($form, $dbh, $query);
 
 200     $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
 
 201     do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
 
 209     # if charttype is heading make sure certain values are empty
 
 210     # specifically, if charttype is changed from an existing account, empty the
 
 211     # fields unnecessary for headings, so that e.g. heading doesn't appear in
 
 212     # drop-down menues due to still having a valid "link" entry
 
 214     if ( $form->{charttype} eq 'H' ) {
 
 216       $form->{pos_bwa} = '';
 
 217       $form->{pos_bilanz} = '';
 
 218       $form->{pos_eur} = '';
 
 219       $form->{new_chart_id} = '';
 
 220       $form->{valid_from} = '';
 
 223     $query = qq|UPDATE chart SET
 
 240                   $form->{description},
 
 244                   conv_i($form->{pos_bwa}),
 
 245                   conv_i($form->{pos_bilanz}),
 
 246                   conv_i($form->{pos_eur}),
 
 247                   conv_i($form->{pos_er}),
 
 248                   conv_i($form->{new_chart_id}),
 
 249                   conv_date($form->{valid_from}),
 
 250                   ($form->{datevautomatik} eq 'T') ? 'true':'false',
 
 257   do_query($form, $dbh, $query, @values);
 
 263   my $MAX_TRIES = 10; # Maximum count of taxkeys in form
 
 267   for $tk_count (0 .. $MAX_TRIES) {
 
 271     # Check if the account already exists, else cancel
 
 273     print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
 
 275     last READTAXKEYS if ( $form->{'id'} == 0);
 
 277     # check if there is a startdate
 
 278     if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
 
 283     # Add valid taxkeys into the array
 
 286         id        => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
 
 287         tax_id    => conv_i($form->{"taxkey_tax_$tk_count"}),
 
 288         startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
 
 289         chart_id  => conv_i($form->{"id"}),
 
 290         pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
 
 291         delete    => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
 
 298   for my $j (0 .. $#taxkeys){
 
 299     if ( defined $taxkeys[$j]{'id'} ){
 
 302       if ($taxkeys[$j]{'delete'}){
 
 304           DELETE FROM taxkeys WHERE id = ?
 
 307         @values = ($taxkeys[$j]{'id'});
 
 309         do_query($form, $dbh, $query, @values);
 
 318         SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
 
 326         $taxkeys[$j]{'tax_id'},
 
 327         $taxkeys[$j]{'chart_id'},
 
 328         $taxkeys[$j]{'tax_id'},
 
 329         $taxkeys[$j]{'pos_ustva'},
 
 330         $taxkeys[$j]{'startdate'},
 
 333       do_query($form, $dbh, $query, @values);
 
 339         INSERT INTO taxkeys (
 
 346         VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
 
 349         $taxkeys[$j]{'tax_id'},
 
 350         $taxkeys[$j]{'chart_id'},
 
 351         $taxkeys[$j]{'tax_id'},
 
 352         $taxkeys[$j]{'pos_ustva'},
 
 353         $taxkeys[$j]{'startdate'},
 
 356       do_query($form, $dbh, $query, @values);
 
 361   # Update chart.taxkey_id to the latest from taxkeys for this chart.
 
 367       WHERE taxkeys.chart_id = chart.id
 
 368       ORDER BY startdate DESC
 
 374   do_query($form, $dbh, $query, $form->{id});
 
 380   my ($self, $myconfig, $form) = @_;
 
 381   $main::lxdebug->enter_sub();
 
 383   my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
 
 385   $::lxdebug->leave_sub;
 
 389 sub _delete_account {
 
 390   my ($self, $myconfig, $form) = @_;
 
 392   my $dbh = SL::DB->client->dbh;
 
 394   my $query = qq|SELECT count(*) FROM acc_trans a
 
 395                  WHERE a.chart_id = ?|;
 
 396   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
 
 402   $query = qq|DELETE FROM tax
 
 404   do_query($form, $dbh, $query, $form->{id});
 
 406   # delete account taxkeys
 
 407   $query = qq|DELETE FROM taxkeys
 
 409   do_query($form, $dbh, $query, $form->{id});
 
 411   # delete chart of account record
 
 412   # last step delete chart, because we have a constraint
 
 414   $query = qq|DELETE FROM chart
 
 416   do_query($form, $dbh, $query, $form->{id});
 
 421 sub get_language_details {
 
 422   $main::lxdebug->enter_sub();
 
 424   my ($self, $myconfig, $form, $id) = @_;
 
 426   my $dbh = SL::DB->client->dbh;
 
 429     "SELECT template_code, " .
 
 430     "  output_numberformat, output_dateformat, output_longdates " .
 
 431     "FROM language WHERE id = ?";
 
 432   my @res = selectrow_query($form, $dbh, $query, $id);
 
 434   $main::lxdebug->leave_sub();
 
 439 sub prepare_template_filename {
 
 440   $main::lxdebug->enter_sub();
 
 442   my ($self, $myconfig, $form) = @_;
 
 444   my ($filename, $display_filename);
 
 446   $filename = $form->{formname};
 
 448   if ($form->{language}) {
 
 449     my ($id, $template_code) = split(/--/, $form->{language});
 
 450     $filename .= "_${template_code}";
 
 453   if ($form->{printer}) {
 
 454     my ($id, $template_code) = split(/--/, $form->{printer});
 
 455     $filename .= "_${template_code}";
 
 458   $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
 
 459   if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
 
 460     $filename =~ s|.*/||;
 
 462   $display_filename = $filename;
 
 463   $filename = SL::DB::Default->get->templates . "/$filename";
 
 465   $main::lxdebug->leave_sub();
 
 467   return ($filename, $display_filename);
 
 472   $main::lxdebug->enter_sub();
 
 474   my ($self, $filename) = @_;
 
 476   my ($content, $lines) = ("", 0);
 
 480   if (open(TEMPLATE, $filename)) {
 
 488   $content = Encode::decode('utf-8-strict', $content);
 
 490   $main::lxdebug->leave_sub();
 
 492   return ($content, $lines);
 
 496   $main::lxdebug->enter_sub();
 
 498   my ($self, $filename, $content) = @_;
 
 504   if (open(TEMPLATE, ">", $filename)) {
 
 505     $content = Encode::encode('utf-8-strict', $content);
 
 506     $content =~ s/\r\n/\n/g;
 
 507     print(TEMPLATE $content);
 
 513   $main::lxdebug->leave_sub();
 
 518 sub displayable_name_specs_by_module {
 
 520      'SL::DB::Customer' => {
 
 521        specs => SL::DB::Customer->displayable_name_specs,
 
 522        prefs => SL::DB::Customer->displayable_name_prefs,
 
 524      'SL::DB::Vendor' => {
 
 525        specs => SL::DB::Vendor->displayable_name_specs,
 
 526        prefs => SL::DB::Vendor->displayable_name_prefs,
 
 529        specs => SL::DB::Part->displayable_name_specs,
 
 530        prefs => SL::DB::Part->displayable_name_prefs,
 
 535 sub positions_scrollbar_height {
 
 536   SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
 
 539 sub purchase_search_makemodel {
 
 540   SL::Helper::UserPreferences::PartPickerSearch->new()->get_purchase_search_makemodel();
 
 543 sub sales_search_customer_partnumber {
 
 544   SL::Helper::UserPreferences::PartPickerSearch->new()->get_sales_search_customer_partnumber();
 
 547 sub positions_show_update_button {
 
 548   SL::Helper::UserPreferences::UpdatePositions->new()->get_show_update_button();
 
 551 sub time_recording_use_duration {
 
 552   SL::Helper::UserPreferences::TimeRecording->new()->get_use_duration();
 
 555 sub longdescription_dialog_size_percentage {
 
 556   SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();
 
 559 sub save_preferences {
 
 560   $main::lxdebug->enter_sub();
 
 562   my ($self, $form) = @_;
 
 564   my $employee = SL::DB::Manager::Employee->current;
 
 565   $employee->update_attributes(name => $form->{name});
 
 567   my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
 
 568   $user->update_attributes(
 
 570       %{ $user->config_values },
 
 571       map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
 
 574   # Displayable name preferences
 
 575   my $displayable_name_specs_by_module = displayable_name_specs_by_module();
 
 576   foreach my $specs (@{ $form->{displayable_name_specs} }) {
 
 577     if (!$specs->{value} || $specs->{value} eq $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->get_default()) {
 
 578       $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->delete($specs->{value});
 
 580       $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->store_value($specs->{value});
 
 584   if (exists $form->{positions_scrollbar_height}) {
 
 585     SL::Helper::UserPreferences::PositionsScrollbar->new()->store_height($form->{positions_scrollbar_height})
 
 587   if (exists $form->{purchase_search_makemodel}) {
 
 588     SL::Helper::UserPreferences::PartPickerSearch->new()->store_purchase_search_makemodel($form->{purchase_search_makemodel})
 
 590   if (exists $form->{sales_search_customer_partnumber}) {
 
 591     SL::Helper::UserPreferences::PartPickerSearch->new()->store_sales_search_customer_partnumber($form->{sales_search_customer_partnumber})
 
 593   if (exists $form->{positions_show_update_button}) {
 
 594     SL::Helper::UserPreferences::UpdatePositions->new()->store_show_update_button($form->{positions_show_update_button})
 
 596   if (exists $form->{time_recording_use_duration}) {
 
 597     SL::Helper::UserPreferences::TimeRecording->new()->store_use_duration($form->{time_recording_use_duration})
 
 599   if (exists $form->{longdescription_dialog_size_percentage}) {
 
 600     SL::Helper::UserPreferences::DisplayPreferences->new()->store_longdescription_dialog_size_percentage($form->{longdescription_dialog_size_percentage})
 
 603   $main::lxdebug->leave_sub();
 
 609   $main::lxdebug->enter_sub();
 
 614   my $myconfig = \%main::myconfig;
 
 615   my $form     = $main::form;
 
 617   my $dbh      = $params{dbh} || SL::DB->client->dbh;
 
 619   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
 
 621   $defaults->{weightunit} ||= 'kg';
 
 623   $main::lxdebug->leave_sub();
 
 629   $main::lxdebug->enter_sub();
 
 631   my ($self, $myconfig, $form) = @_;
 
 633   my $dbh = SL::DB->client->dbh;
 
 635   my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
 
 636   my $sth   = $dbh->prepare($query);
 
 637   $sth->execute || $form->dberror($query);
 
 639   ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
 
 643   $main::lxdebug->leave_sub();
 
 647   $main::lxdebug->enter_sub();
 
 649   my ($self, $myconfig, $form) = @_;
 
 651   SL::DB->client->with_transaction(sub {
 
 652     my $dbh = SL::DB->client->dbh;
 
 654     my ($query, @values);
 
 656     # is currently NEVER trueish (no more hidden revtrans in $form)
 
 657     # if ($form->{revtrans}) {
 
 658     #   $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
 
 659     # -> therefore you can only set this to false (which is already the default)
 
 660     # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
 
 662       $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
 
 663       @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
 
 665     # set close in defaults
 
 666     do_query($form, $dbh, $query, @values);
 
 668   }) or do { die SL::DB->client->error };
 
 670   $main::lxdebug->leave_sub();
 
 674   my ($self, $units, $unit_name, $factor) = @_;
 
 676   $factor = 1 unless ($factor);
 
 678   my $unit = $units->{$unit_name};
 
 680   if (!defined($unit) || !$unit->{"base_unit"} ||
 
 681       ($unit_name eq $unit->{"base_unit"})) {
 
 682     return ($unit_name, $factor);
 
 685   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
 
 689   $main::lxdebug->enter_sub();
 
 691   my ($self, $myconfig, $form, $prefix) = @_;
 
 694   my $dbh = SL::DB->client->dbh;
 
 696   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
 
 698   my $sth = prepare_execute_query($form, $dbh, $query);
 
 701   while (my $ref = $sth->fetchrow_hashref()) {
 
 702     $units->{$ref->{"name"}} = $ref;
 
 706   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
 
 707   $sth = $dbh->prepare($query_lang);
 
 708   $sth->execute() || $form->dberror($query_lang);
 
 710   while (my $ref = $sth->fetchrow_hashref()) {
 
 711     push(@languages, $ref);
 
 715   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
 
 716     "FROM units_language ul " .
 
 717     "LEFT JOIN language l ON ul.language_id = l.id " .
 
 719   $sth = $dbh->prepare($query_lang);
 
 721   foreach my $unit (values(%{$units})) {
 
 722     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
 
 724     $unit->{"LANGUAGES"} = {};
 
 725     foreach my $lang (@languages) {
 
 726       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
 
 729     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
 
 730     while (my $ref = $sth->fetchrow_hashref()) {
 
 731       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
 
 736   $main::lxdebug->leave_sub();
 
 741 sub retrieve_all_units {
 
 742   $main::lxdebug->enter_sub();
 
 746   if (!$::request->{cache}{all_units}) {
 
 747     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
 
 750   $main::lxdebug->leave_sub();
 
 752   return $::request->{cache}{all_units};
 
 756 sub translate_units {
 
 757   $main::lxdebug->enter_sub();
 
 759   my ($self, $form, $template_code, $unit, $amount) = @_;
 
 761   my $units = $self->retrieve_units(\%main::myconfig, $form);
 
 763   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
 
 764   my $new_unit = $unit;
 
 766     if (($amount != 1) && $h->{"localized_plural"}) {
 
 767       $new_unit = $h->{"localized_plural"};
 
 768     } elsif ($h->{"localized"}) {
 
 769       $new_unit = $h->{"localized"};
 
 773   $main::lxdebug->leave_sub();
 
 779   $main::lxdebug->enter_sub();
 
 781   my ($self, $myconfig, $form, $units) = @_;
 
 783   my $dbh = SL::DB->client->dbh;
 
 785   map({ $_->{"in_use"} = 0; } values(%{$units}));
 
 787   foreach my $unit (values(%{$units})) {
 
 788     my $base_unit = $unit->{"original_base_unit"};
 
 790       $units->{$base_unit}->{"in_use"} = 1;
 
 791       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
 
 792       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
 
 793       $base_unit = $units->{$base_unit}->{"original_base_unit"};
 
 797   foreach my $unit (values(%{$units})) {
 
 798     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
 
 800     foreach my $table (qw(parts invoice orderitems)) {
 
 801       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
 
 803       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
 
 804         $query .= "= " . $dbh->quote($unit->{"name"});
 
 806         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
 
 807           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
 
 810       my ($count) = $dbh->selectrow_array($query);
 
 811       $form->dberror($query) if ($dbh->err);
 
 814         $unit->{"in_use"} = 1;
 
 820   $main::lxdebug->leave_sub();
 
 823 sub convertible_units {
 
 824   $main::lxdebug->enter_sub();
 
 828   my $filter_unit = shift;
 
 829   my $not_smaller = shift;
 
 833   $filter_unit = $units->{$filter_unit};
 
 835   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
 
 836     my $unit = $units->{$name};
 
 838     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
 
 839         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
 
 840       push @{$conv_units}, $unit;
 
 844   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
 
 846   $main::lxdebug->leave_sub();
 
 851 # if $a is translatable to $b, return the factor between them.
 
 854   $main::lxdebug->enter_sub(2);
 
 855   my ($this, $a, $b, $all_units) = @_;
 
 858     $all_units = $this->retrieve_all_units;
 
 861   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
 
 862   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
 
 863   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
 
 864   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
 
 867 sub unit_select_data {
 
 868   $main::lxdebug->enter_sub();
 
 870   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
 
 875     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
 
 878   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
 
 879     if (!$convertible_into ||
 
 880         ($units->{$convertible_into} &&
 
 881          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
 
 882       push @{$select}, { "name"      => $unit,
 
 883                          "base_unit" => $units->{$unit}->{"base_unit"},
 
 884                          "factor"    => $units->{$unit}->{"factor"},
 
 885                          "selected"  => ($unit eq $selected) ? "selected" : "" };
 
 889   $main::lxdebug->leave_sub();
 
 894 sub unit_select_html {
 
 895   $main::lxdebug->enter_sub();
 
 897   my ($self, $units, $name, $selected, $convertible_into) = @_;
 
 899   my $select = "<select name=${name}>";
 
 901   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
 
 902     if (!$convertible_into ||
 
 903         ($units->{$convertible_into} &&
 
 904          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
 
 905       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
 
 908   $select .= "</select>";
 
 910   $main::lxdebug->leave_sub();
 
 916   $main::lxdebug->enter_sub();
 
 920   my $units = $self->retrieve_all_units();
 
 925   while (2 <= scalar(@_)) {
 
 927     my $unit = $units->{shift(@_)};
 
 929     croak "No unit defined with name $unit" if (!defined $unit);
 
 932       $base_unit = $unit->{base_unit};
 
 933     } elsif ($base_unit ne $unit->{base_unit}) {
 
 934       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
 
 937     $sum += $qty * $unit->{factor};
 
 940   $main::lxdebug->leave_sub();
 
 946   $main::lxdebug->enter_sub();
 
 948   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
 
 950   SL::DB->client->with_transaction(sub {
 
 951     my $dbh = SL::DB->client->dbh;
 
 953     my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
 
 954     my ($sortkey) = selectrow_query($form, $dbh, $query);
 
 956     $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
 
 957       "VALUES (?, ?, ?, ?)";
 
 958     do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
 
 961       $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
 
 962       my $sth = $dbh->prepare($query);
 
 963       foreach my $lang (@{$languages}) {
 
 964         my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
 
 965         $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
 
 970   }) or do { die SL::DB->client->error };
 
 972   $main::lxdebug->leave_sub();
 
 976   my ($self, $myconfig, $form, $units, $delete_units) = @_;
 
 977   $main::lxdebug->enter_sub();
 
 979   my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
 
 981   $::lxdebug->leave_sub;
 
 986   my ($self, $myconfig, $form, $units, $delete_units) = @_;
 
 988   my $dbh = SL::DB->client->dbh;
 
 990   my ($base_unit, $unit, $sth, $query);
 
 992   $query = "DELETE FROM units_language";
 
 993   $dbh->do($query) || $form->dberror($query);
 
 995   if ($delete_units && (0 != scalar(@{$delete_units}))) {
 
 996     $query = "DELETE FROM units WHERE name IN (";
 
 997     map({ $query .= "?," } @{$delete_units});
 
 998     substr($query, -1, 1) = ")";
 
 999     $dbh->do($query, undef, @{$delete_units}) ||
 
1000       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
 
1003   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
 
1004   $sth = $dbh->prepare($query);
 
1006   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
 
1007   my $sth_lang = $dbh->prepare($query_lang);
 
1009   foreach $unit (values(%{$units})) {
 
1010     $unit->{"depth"} = 0;
 
1011     my $base_unit = $unit;
 
1012     while ($base_unit->{"base_unit"}) {
 
1014       $base_unit = $units->{$base_unit->{"base_unit"}};
 
1018   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
 
1019     if ($unit->{"LANGUAGES"}) {
 
1020       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
 
1021         next unless ($lang->{"id"} && $lang->{"localized"});
 
1022         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
 
1023         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
 
1027     next if ($unit->{"unchanged_unit"});
 
1029     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
 
1030     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
 
1034   $sth_lang->finish();
 
1040   $main::lxdebug->enter_sub();
 
1042   my ($self, $myconfig, $form) = @_;
 
1044   my $dbh = SL::DB->client->dbh;
 
1046   my $query = qq|SELECT
 
1050                    round(t.rate * 100, 2) AS rate,
 
1051                    tc.accno               AS taxnumber,
 
1052                    tc.description         AS account_description,
 
1053                    ssc.accno              AS skonto_chart_accno,
 
1054                    ssc.description        AS skonto_chart_description,
 
1055                    spc.accno              AS skonto_chart_purchase_accno,
 
1056                    spc.description        AS skonto_chart_purchase_description
 
1058                  LEFT JOIN chart tc  ON (tc.id = t.chart_id)
 
1059                  LEFT JOIN chart ssc ON (ssc.id = t.skonto_sales_chart_id)
 
1060                  LEFT JOIN chart spc ON (spc.id = t.skonto_purchase_chart_id)
 
1061                  ORDER BY taxkey, rate|;
 
1063   my $sth = $dbh->prepare($query);
 
1064   $sth->execute || $form->dberror($query);
 
1067   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1068     push @{ $form->{TAX} }, $ref;
 
1073   $main::lxdebug->leave_sub();
 
1076 sub get_tax_accounts {
 
1077   $main::lxdebug->enter_sub();
 
1079   my ($self, $myconfig, $form) = @_;
 
1081   my $dbh = SL::DB->client->dbh;
 
1083   # get Accounts from chart
 
1084   my $query = qq{ SELECT
 
1086                  accno || ' - ' || description AS taxaccount
 
1088                WHERE link LIKE '%_tax%'
 
1092   my $sth = $dbh->prepare($query);
 
1093   $sth->execute || $form->dberror($query);
 
1095   $form->{ACCOUNTS} = [];
 
1096   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1097     push @{ $form->{ACCOUNTS} }, $ref;
 
1100   $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
 
1101   $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
 
1103   $form->{skontochart_value_title_sub} = sub {
 
1107       $item->{accno} .' '. $item->{description},
 
1113   $main::lxdebug->leave_sub();
 
1117   $main::lxdebug->enter_sub();
 
1119   my ($self, $myconfig, $form) = @_;
 
1121   my $dbh = SL::DB->client->dbh;
 
1123   my $query = qq|SELECT
 
1126                    round(rate * 100, 2) AS rate,
 
1129                    (id IN (SELECT tax_id
 
1130                            FROM acc_trans)) AS tax_already_used,
 
1131                    skonto_sales_chart_id,
 
1132                    skonto_purchase_chart_id
 
1136   my $sth = $dbh->prepare($query);
 
1137   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
 
1139   my $ref = $sth->fetchrow_hashref("NAME_lc");
 
1141   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1145   # see if it is used by a taxkey
 
1146   $query = qq|SELECT count(*) FROM taxkeys
 
1147               WHERE tax_id = ? AND chart_id >0|;
 
1149   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
 
1151   $form->{orphaned} = !$form->{orphaned};
 
1154   if (!$form->{orphaned} ) {
 
1155     $query = qq|SELECT DISTINCT c.id, c.accno
 
1157                 JOIN   tax t ON (t.id = tk.tax_id)
 
1158                 JOIN chart c ON (c.id = tk.chart_id)
 
1159                 WHERE tk.tax_id = ?|;
 
1161     $sth = $dbh->prepare($query);
 
1162     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
 
1164     $form->{TAXINUSE} = [];
 
1165     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1166       push @{ $form->{TAXINUSE} }, $ref;
 
1172   $main::lxdebug->leave_sub();
 
1176   my ($self, $myconfig, $form) = @_;
 
1177   $main::lxdebug->enter_sub();
 
1179   my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
 
1181   $::lxdebug->leave_sub;
 
1186   my ($self, $myconfig, $form) = @_;
 
1189   my $dbh = SL::DB->client->dbh;
 
1191   $form->{rate} = $form->{rate} / 100;
 
1193   my $chart_categories = '';
 
1194   $chart_categories .= 'A' if $form->{asset};
 
1195   $chart_categories .= 'L' if $form->{liability};
 
1196   $chart_categories .= 'Q' if $form->{equity};
 
1197   $chart_categories .= 'I' if $form->{revenue};
 
1198   $chart_categories .= 'E' if $form->{expense};
 
1199   $chart_categories .= 'C' if $form->{costs};
 
1201   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);
 
1202   if ($form->{id} ne "") {
 
1203     $query = qq|UPDATE tax SET
 
1208                   skonto_sales_chart_id    = ?,
 
1209                   skonto_purchase_chart_id = ?,
 
1210                   chart_categories         = ?
 
1215     ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
 
1216     $query = qq|INSERT INTO tax (
 
1221                   skonto_sales_chart_id,
 
1222                   skonto_purchase_chart_id,
 
1226                 VALUES (?, ?, ?, ?, ?, ?,  ?, ?)|;
 
1228   push(@values, $form->{id});
 
1229   do_query($form, $dbh, $query, @values);
 
1231   foreach my $language_id (keys %{ $form->{translations} }) {
 
1232     GenericTranslations->save('dbh'              => $dbh,
 
1233                               'translation_type' => 'SL::DB::Tax/taxdescription',
 
1234                               'translation_id'   => $form->{id},
 
1235                               'language_id'      => $language_id,
 
1236                               'translation'      => $form->{translations}->{$language_id});
 
1241   $main::lxdebug->enter_sub();
 
1243   my ($self, $myconfig, $form) = @_;
 
1246   SL::DB->client->with_transaction(sub {
 
1247     $query = qq|DELETE FROM tax WHERE id = ?|;
 
1248     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
1250   }) or do { die SL::DB->client->error };
 
1252   $main::lxdebug->leave_sub();
 
1255 sub save_warehouse {
 
1256   $main::lxdebug->enter_sub();
 
1258   my ($self, $myconfig, $form) = @_;
 
1260   croak('Need at least one new bin') unless $form->{number_of_new_bins} > 0;
 
1262   SL::DB->client->with_transaction(sub {
 
1263     my $dbh = SL::DB->client->dbh;
 
1265     my ($query, @values, $sth);
 
1268       $query        = qq|SELECT nextval('id')|;
 
1269       ($form->{id}) = selectrow_query($form, $dbh, $query);
 
1271       $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
 
1272       do_query($form, $dbh, $query, $form->{id});
 
1275     do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
 
1276              $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
 
1278     if (0 < $form->{number_of_new_bins}) {
 
1279       my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
 
1280       $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
 
1281       $sth   = prepare_query($form, $dbh, $query);
 
1283       foreach my $i (1..$form->{number_of_new_bins}) {
 
1284         do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
 
1290   }) or do { die SL::DB->client->error };
 
1292   $main::lxdebug->leave_sub();
 
1296   $main::lxdebug->enter_sub();
 
1298   my ($self, $myconfig, $form) = @_;
 
1300   SL::DB->client->with_transaction(sub {
 
1301     my $dbh = SL::DB->client->dbh;
 
1303     my ($query, @values, $sth);
 
1305     @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
 
1308       $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
 
1309       do_query($form, $dbh, $query, @values);
 
1312     $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
 
1313     $sth   = prepare_query($form, $dbh, $query);
 
1315     foreach my $row (1..$form->{rowcount}) {
 
1316       next if ($form->{"delete_${row}"});
 
1318       do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
 
1323   }) or do { die SL::DB->client->error };
 
1325   $main::lxdebug->leave_sub();
 
1328 sub delete_warehouse {
 
1329   $main::lxdebug->enter_sub();
 
1331   my ($self, $myconfig, $form) = @_;
 
1333   my $rc = SL::DB->client->with_transaction(sub {
 
1334     my $dbh = SL::DB->client->dbh;
 
1336     my $id      = conv_i($form->{id});
 
1337     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|;
 
1338     my ($count) = selectrow_query($form, $dbh, $query, $id);
 
1344     do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
 
1345     do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
 
1350   $main::lxdebug->leave_sub();
 
1355 sub get_all_warehouses {
 
1356   $main::lxdebug->enter_sub();
 
1358   my ($self, $myconfig, $form) = @_;
 
1360   my $dbh = SL::DB->client->dbh;
 
1362   my $query = qq|SELECT w.id, w.description, w.invalid,
 
1363                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
 
1365                  ORDER BY w.sortkey|;
 
1367   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
 
1369   $main::lxdebug->leave_sub();
 
1373   $main::lxdebug->enter_sub();
 
1375   my ($self, $myconfig, $form) = @_;
 
1377   my $dbh = SL::DB->client->dbh;
 
1379   my $id    = conv_i($form->{id});
 
1380   my $query = qq|SELECT w.description, w.invalid
 
1384   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
 
1386   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
1389    SELECT b.*, use.in_use
 
1392        SELECT DISTINCT bin_id, TRUE AS in_use FROM inventory
 
1394        SELECT DISTINCT bin_id, TRUE AS in_use FROM parts
 
1395      ) use ON use.bin_id = b.id
 
1396      WHERE b.warehouse_id = ?;
 
1399   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
1401   $main::lxdebug->leave_sub();
 
1404 sub get_eur_categories {
 
1405   my ($self, $myconfig, $form) = @_;
 
1407   my $dbh = SL::DB->client->dbh;
 
1408   my %eur_categories = selectall_as_map($form, $dbh, "select * from eur_categories order by id", 'id', 'description');
 
1410   return \%eur_categories;
 
1413 sub get_bwa_categories {
 
1414   my ($self, $myconfig, $form) = @_;
 
1416   my $dbh = SL::DB->client->dbh;
 
1417   my %bwa_categories = selectall_as_map($form, $dbh, "select * from bwa_categories order by id", 'id', 'description');
 
1419   return \%bwa_categories;