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;
 
  60   $main::lxdebug->enter_sub();
 
  62   # fetch chart-related data and set form fields
 
  63   # get_account is called by add_account in am.pl
 
  64   # always sets $form->{TAXKEY} and default_accounts
 
  65   # loads chart data when $form->{id} is passed
 
  67   my ($self, $myconfig, $form) = @_;
 
  69   # get default accounts
 
  70   map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
 
  73   my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
 
  75   foreach my $tk ( @{$taxes} ) {
 
  76     push @{ $form->{TAXKEY} },  { id          => $tk->id,
 
  77                                   chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
 
  78                                   taxkey      => $tk->taxkey,
 
  79                                   tax         => $tk->id . '--' . $tk->taxkey,
 
  86     my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
 
  88     my @chart_fields = qw(accno description charttype category link pos_bilanz
 
  89                           pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik);
 
  90     foreach my $cf ( @chart_fields ) {
 
  91       $form->{"$cf"} = $chart_obj->$cf;
 
  94     my $active_taxkey = $chart_obj->get_active_taxkey;
 
  95     $form->{$_}  = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
 
  96     $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
 
  98     # check if there are any transactions for this chart
 
  99     $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
 
 101     # check if new account is active
 
 102     # The old sql query was broken since at least 2006 and always returned 0
 
 103     $form->{new_chart_valid} = $chart_obj->new_chart_valid;
 
 105     # get the taxkeys of the account
 
 106     $form->{ACCOUNT_TAXKEYS} = [];
 
 107     foreach my $taxkey ( @{ $chart_obj->taxkeys } ) {
 
 108       push @{ $form->{ACCOUNT_TAXKEYS} }, { id             => $taxkey->id,
 
 109                                             chart_id       => $taxkey->chart_id,
 
 110                                             tax_id         => $taxkey->tax_id,
 
 111                                             taxkey_id      => $taxkey->taxkey_id,
 
 112                                             pos_ustva      => $taxkey->pos_ustva,
 
 113                                             startdate      => $taxkey->startdate->to_kivitendo,
 
 114                                             taxdescription => $taxkey->tax->taxdescription,
 
 115                                             rate           => $taxkey->tax->rate,
 
 116                                             accno          => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
 
 120     # get new accounts (Folgekonto). Find all charts with the same link
 
 121     $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});
 
 123   } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
 
 124     $form->{orphaned} = 1;
 
 127   $main::lxdebug->leave_sub();
 
 131   my ($self, $myconfig, $form) = @_;
 
 132   $main::lxdebug->enter_sub();
 
 134   my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
 
 136   $::lxdebug->leave_sub;
 
 141   # TODO: it should be forbidden to change an account to a heading if there
 
 142   # have been bookings to this account in the past
 
 144   my ($self, $myconfig, $form) = @_;
 
 146   my $dbh = SL::DB->client->dbh;
 
 148   for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
 
 149     $form->{$form->{$_}} = $form->{$_} if $form->{$_};
 
 152   # sanity check, can't have AR with AR_...
 
 153   if ($form->{AR} || $form->{AP} || $form->{IC}) {
 
 154     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)) {
 
 155       $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
 
 159   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);
 
 160   $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
 
 162   # strip blanks from accno
 
 163   map { $form->{$_} =~ s/ //g; } qw(accno);
 
 165   # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
 
 166   map { $form->{$_} =~ s/\h+/ /g } qw(description);
 
 170   if ($form->{id} eq "NULL") {
 
 179   my @values = ($form->{accno});
 
 182     $query .= ' AND NOT id = ?';
 
 183     push(@values, $form->{id});
 
 186   my ($accno) = selectrow_query($form, $dbh, $query, @values);
 
 189     $form->error($::locale->text('Account number not unique!'));
 
 193   if (!$form->{id} || $form->{id} eq "") {
 
 194     $query = qq|SELECT nextval('id')|;
 
 195     ($form->{"id"}) = selectrow_query($form, $dbh, $query);
 
 196     $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
 
 197     do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
 
 205     # if charttype is heading make sure certain values are empty
 
 206     # specifically, if charttype is changed from an existing account, empty the
 
 207     # fields unnecessary for headings, so that e.g. heading doesn't appear in
 
 208     # drop-down menues due to still having a valid "link" entry
 
 210     if ( $form->{charttype} eq 'H' ) {
 
 212       $form->{pos_bwa} = '';
 
 213       $form->{pos_bilanz} = '';
 
 214       $form->{pos_eur} = '';
 
 215       $form->{new_chart_id} = '';
 
 216       $form->{valid_from} = '';
 
 219     $query = qq|UPDATE chart SET
 
 236                   $form->{description},
 
 240                   conv_i($form->{pos_bwa}),
 
 241                   conv_i($form->{pos_bilanz}),
 
 242                   conv_i($form->{pos_eur}),
 
 243                   conv_i($form->{pos_er}),
 
 244                   conv_i($form->{new_chart_id}),
 
 245                   conv_date($form->{valid_from}),
 
 246                   ($form->{datevautomatik} eq 'T') ? 'true':'false',
 
 253   do_query($form, $dbh, $query, @values);
 
 259   my $MAX_TRIES = 10; # Maximum count of taxkeys in form
 
 263   for $tk_count (0 .. $MAX_TRIES) {
 
 267     # Check if the account already exists, else cancel
 
 269     print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
 
 271     last READTAXKEYS if ( $form->{'id'} == 0);
 
 273     # check if there is a startdate
 
 274     if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
 
 279     # Add valid taxkeys into the array
 
 282         id        => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
 
 283         tax_id    => conv_i($form->{"taxkey_tax_$tk_count"}),
 
 284         startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
 
 285         chart_id  => conv_i($form->{"id"}),
 
 286         pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
 
 287         delete    => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
 
 294   for my $j (0 .. $#taxkeys){
 
 295     if ( defined $taxkeys[$j]{'id'} ){
 
 298       if ($taxkeys[$j]{'delete'}){
 
 300           DELETE FROM taxkeys WHERE id = ?
 
 303         @values = ($taxkeys[$j]{'id'});
 
 305         do_query($form, $dbh, $query, @values);
 
 314         SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
 
 322         $taxkeys[$j]{'tax_id'},
 
 323         $taxkeys[$j]{'chart_id'},
 
 324         $taxkeys[$j]{'tax_id'},
 
 325         $taxkeys[$j]{'pos_ustva'},
 
 326         $taxkeys[$j]{'startdate'},
 
 329       do_query($form, $dbh, $query, @values);
 
 335         INSERT INTO taxkeys (
 
 342         VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
 
 345         $taxkeys[$j]{'tax_id'},
 
 346         $taxkeys[$j]{'chart_id'},
 
 347         $taxkeys[$j]{'tax_id'},
 
 348         $taxkeys[$j]{'pos_ustva'},
 
 349         $taxkeys[$j]{'startdate'},
 
 352       do_query($form, $dbh, $query, @values);
 
 357   # Update chart.taxkey_id to the latest from taxkeys for this chart.
 
 363       WHERE taxkeys.chart_id = chart.id
 
 364       ORDER BY startdate DESC
 
 370   do_query($form, $dbh, $query, $form->{id});
 
 376   my ($self, $myconfig, $form) = @_;
 
 377   $main::lxdebug->enter_sub();
 
 379   my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
 
 381   $::lxdebug->leave_sub;
 
 385 sub _delete_account {
 
 386   my ($self, $myconfig, $form) = @_;
 
 388   my $dbh = SL::DB->client->dbh;
 
 390   my $query = qq|SELECT count(*) FROM acc_trans a
 
 391                  WHERE a.chart_id = ?|;
 
 392   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
 
 398   $query = qq|DELETE FROM tax
 
 400   do_query($form, $dbh, $query, $form->{id});
 
 402   # delete account taxkeys
 
 403   $query = qq|DELETE FROM taxkeys
 
 405   do_query($form, $dbh, $query, $form->{id});
 
 407   # delete chart of account record
 
 408   # last step delete chart, because we have a constraint
 
 410   $query = qq|DELETE FROM chart
 
 412   do_query($form, $dbh, $query, $form->{id});
 
 417 sub get_language_details {
 
 418   $main::lxdebug->enter_sub();
 
 420   my ($self, $myconfig, $form, $id) = @_;
 
 422   my $dbh = SL::DB->client->dbh;
 
 425     "SELECT template_code, " .
 
 426     "  output_numberformat, output_dateformat, output_longdates " .
 
 427     "FROM language WHERE id = ?";
 
 428   my @res = selectrow_query($form, $dbh, $query, $id);
 
 430   $main::lxdebug->leave_sub();
 
 435 sub prepare_template_filename {
 
 436   $main::lxdebug->enter_sub();
 
 438   my ($self, $myconfig, $form) = @_;
 
 440   my ($filename, $display_filename);
 
 442   $filename = $form->{formname};
 
 444   if ($form->{language}) {
 
 445     my ($id, $template_code) = split(/--/, $form->{language});
 
 446     $filename .= "_${template_code}";
 
 449   if ($form->{printer}) {
 
 450     my ($id, $template_code) = split(/--/, $form->{printer});
 
 451     $filename .= "_${template_code}";
 
 454   $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
 
 455   if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
 
 456     $filename =~ s|.*/||;
 
 458   $display_filename = $filename;
 
 459   $filename = SL::DB::Default->get->templates . "/$filename";
 
 461   $main::lxdebug->leave_sub();
 
 463   return ($filename, $display_filename);
 
 468   $main::lxdebug->enter_sub();
 
 470   my ($self, $filename) = @_;
 
 472   my ($content, $lines) = ("", 0);
 
 476   if (open(TEMPLATE, $filename)) {
 
 484   $content = Encode::decode('utf-8-strict', $content);
 
 486   $main::lxdebug->leave_sub();
 
 488   return ($content, $lines);
 
 492   $main::lxdebug->enter_sub();
 
 494   my ($self, $filename, $content) = @_;
 
 500   if (open(TEMPLATE, ">", $filename)) {
 
 501     $content = Encode::encode('utf-8-strict', $content);
 
 502     $content =~ s/\r\n/\n/g;
 
 503     print(TEMPLATE $content);
 
 509   $main::lxdebug->leave_sub();
 
 514 sub displayable_name_specs_by_module {
 
 516      'SL::DB::Customer' => {
 
 517        specs => SL::DB::Customer->displayable_name_specs,
 
 518        prefs => SL::DB::Customer->displayable_name_prefs,
 
 520      'SL::DB::Vendor' => {
 
 521        specs => SL::DB::Vendor->displayable_name_specs,
 
 522        prefs => SL::DB::Vendor->displayable_name_prefs,
 
 525        specs => SL::DB::Part->displayable_name_specs,
 
 526        prefs => SL::DB::Part->displayable_name_prefs,
 
 531 sub positions_scrollbar_height {
 
 532   SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
 
 535 sub save_preferences {
 
 536   $main::lxdebug->enter_sub();
 
 538   my ($self, $form) = @_;
 
 540   my $employee = SL::DB::Manager::Employee->find_by(login => $::myconfig{login});
 
 541   $employee->update_attributes(name => $form->{name});
 
 543   my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
 
 544   $user->update_attributes(
 
 546       %{ $user->config_values },
 
 547       map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
 
 550   # Displayable name preferences
 
 551   my $displayable_name_specs_by_module = displayable_name_specs_by_module();
 
 552   foreach my $specs (@{ $form->{displayable_name_specs} }) {
 
 553     if (!$specs->{value} || $specs->{value} eq $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->get_default()) {
 
 554       $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->delete($specs->{value});
 
 556       $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->store_value($specs->{value});
 
 560   if (exists $form->{positions_scrollbar_height}) {
 
 561     SL::Helper::UserPreferences::PositionsScrollbar->new()->store_height($form->{positions_scrollbar_height})
 
 564   $main::lxdebug->leave_sub();
 
 570   $main::lxdebug->enter_sub();
 
 575   my $myconfig = \%main::myconfig;
 
 576   my $form     = $main::form;
 
 578   my $dbh      = $params{dbh} || SL::DB->client->dbh;
 
 580   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
 
 582   $defaults->{weightunit} ||= 'kg';
 
 584   $main::lxdebug->leave_sub();
 
 590   $main::lxdebug->enter_sub();
 
 592   my ($self, $myconfig, $form) = @_;
 
 594   my $dbh = SL::DB->client->dbh;
 
 596   my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
 
 597   my $sth   = $dbh->prepare($query);
 
 598   $sth->execute || $form->dberror($query);
 
 600   ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
 
 604   $main::lxdebug->leave_sub();
 
 608   $main::lxdebug->enter_sub();
 
 610   my ($self, $myconfig, $form) = @_;
 
 612   SL::DB->client->with_transaction(sub {
 
 613     my $dbh = SL::DB->client->dbh;
 
 615     my ($query, @values);
 
 617     # is currently NEVER trueish (no more hidden revtrans in $form)
 
 618     # if ($form->{revtrans}) {
 
 619     #   $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
 
 620     # -> therefore you can only set this to false (which is already the default)
 
 621     # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
 
 623       $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
 
 624       @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
 
 626     # set close in defaults
 
 627     do_query($form, $dbh, $query, @values);
 
 629   }) or do { die SL::DB->client->error };
 
 631   $main::lxdebug->leave_sub();
 
 635   my ($self, $units, $unit_name, $factor) = @_;
 
 637   $factor = 1 unless ($factor);
 
 639   my $unit = $units->{$unit_name};
 
 641   if (!defined($unit) || !$unit->{"base_unit"} ||
 
 642       ($unit_name eq $unit->{"base_unit"})) {
 
 643     return ($unit_name, $factor);
 
 646   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
 
 650   $main::lxdebug->enter_sub();
 
 652   my ($self, $myconfig, $form, $prefix) = @_;
 
 655   my $dbh = SL::DB->client->dbh;
 
 657   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
 
 659   my $sth = prepare_execute_query($form, $dbh, $query);
 
 662   while (my $ref = $sth->fetchrow_hashref()) {
 
 663     $units->{$ref->{"name"}} = $ref;
 
 667   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
 
 668   $sth = $dbh->prepare($query_lang);
 
 669   $sth->execute() || $form->dberror($query_lang);
 
 671   while (my $ref = $sth->fetchrow_hashref()) {
 
 672     push(@languages, $ref);
 
 676   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
 
 677     "FROM units_language ul " .
 
 678     "LEFT JOIN language l ON ul.language_id = l.id " .
 
 680   $sth = $dbh->prepare($query_lang);
 
 682   foreach my $unit (values(%{$units})) {
 
 683     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
 
 685     $unit->{"LANGUAGES"} = {};
 
 686     foreach my $lang (@languages) {
 
 687       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
 
 690     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
 
 691     while (my $ref = $sth->fetchrow_hashref()) {
 
 692       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
 
 697   $main::lxdebug->leave_sub();
 
 702 sub retrieve_all_units {
 
 703   $main::lxdebug->enter_sub();
 
 707   if (!$::request->{cache}{all_units}) {
 
 708     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
 
 711   $main::lxdebug->leave_sub();
 
 713   return $::request->{cache}{all_units};
 
 717 sub translate_units {
 
 718   $main::lxdebug->enter_sub();
 
 720   my ($self, $form, $template_code, $unit, $amount) = @_;
 
 722   my $units = $self->retrieve_units(\%main::myconfig, $form);
 
 724   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
 
 725   my $new_unit = $unit;
 
 727     if (($amount != 1) && $h->{"localized_plural"}) {
 
 728       $new_unit = $h->{"localized_plural"};
 
 729     } elsif ($h->{"localized"}) {
 
 730       $new_unit = $h->{"localized"};
 
 734   $main::lxdebug->leave_sub();
 
 740   $main::lxdebug->enter_sub();
 
 742   my ($self, $myconfig, $form, $units) = @_;
 
 744   my $dbh = SL::DB->client->dbh;
 
 746   map({ $_->{"in_use"} = 0; } values(%{$units}));
 
 748   foreach my $unit (values(%{$units})) {
 
 749     my $base_unit = $unit->{"original_base_unit"};
 
 751       $units->{$base_unit}->{"in_use"} = 1;
 
 752       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
 
 753       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
 
 754       $base_unit = $units->{$base_unit}->{"original_base_unit"};
 
 758   foreach my $unit (values(%{$units})) {
 
 759     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
 
 761     foreach my $table (qw(parts invoice orderitems)) {
 
 762       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
 
 764       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
 
 765         $query .= "= " . $dbh->quote($unit->{"name"});
 
 767         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
 
 768           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
 
 771       my ($count) = $dbh->selectrow_array($query);
 
 772       $form->dberror($query) if ($dbh->err);
 
 775         $unit->{"in_use"} = 1;
 
 781   $main::lxdebug->leave_sub();
 
 784 sub convertible_units {
 
 785   $main::lxdebug->enter_sub();
 
 789   my $filter_unit = shift;
 
 790   my $not_smaller = shift;
 
 794   $filter_unit = $units->{$filter_unit};
 
 796   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
 
 797     my $unit = $units->{$name};
 
 799     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
 
 800         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
 
 801       push @{$conv_units}, $unit;
 
 805   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
 
 807   $main::lxdebug->leave_sub();
 
 812 # if $a is translatable to $b, return the factor between them.
 
 815   $main::lxdebug->enter_sub(2);
 
 816   my ($this, $a, $b, $all_units) = @_;
 
 819     $all_units = $this->retrieve_all_units;
 
 822   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
 
 823   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
 
 824   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
 
 825   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
 
 828 sub unit_select_data {
 
 829   $main::lxdebug->enter_sub();
 
 831   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
 
 836     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
 
 839   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
 
 840     if (!$convertible_into ||
 
 841         ($units->{$convertible_into} &&
 
 842          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
 
 843       push @{$select}, { "name"      => $unit,
 
 844                          "base_unit" => $units->{$unit}->{"base_unit"},
 
 845                          "factor"    => $units->{$unit}->{"factor"},
 
 846                          "selected"  => ($unit eq $selected) ? "selected" : "" };
 
 850   $main::lxdebug->leave_sub();
 
 855 sub unit_select_html {
 
 856   $main::lxdebug->enter_sub();
 
 858   my ($self, $units, $name, $selected, $convertible_into) = @_;
 
 860   my $select = "<select name=${name}>";
 
 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       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
 
 869   $select .= "</select>";
 
 871   $main::lxdebug->leave_sub();
 
 877   $main::lxdebug->enter_sub();
 
 881   my $units = $self->retrieve_all_units();
 
 886   while (2 <= scalar(@_)) {
 
 888     my $unit = $units->{shift(@_)};
 
 890     croak "No unit defined with name $unit" if (!defined $unit);
 
 893       $base_unit = $unit->{base_unit};
 
 894     } elsif ($base_unit ne $unit->{base_unit}) {
 
 895       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
 
 898     $sum += $qty * $unit->{factor};
 
 901   $main::lxdebug->leave_sub();
 
 907   $main::lxdebug->enter_sub();
 
 909   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
 
 911   SL::DB->client->with_transaction(sub {
 
 912     my $dbh = SL::DB->client->dbh;
 
 914     my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
 
 915     my ($sortkey) = selectrow_query($form, $dbh, $query);
 
 917     $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
 
 918       "VALUES (?, ?, ?, ?)";
 
 919     do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
 
 922       $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
 
 923       my $sth = $dbh->prepare($query);
 
 924       foreach my $lang (@{$languages}) {
 
 925         my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
 
 926         $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
 
 931   }) or do { die SL::DB->client->error };
 
 933   $main::lxdebug->leave_sub();
 
 937   my ($self, $myconfig, $form, $units, $delete_units) = @_;
 
 938   $main::lxdebug->enter_sub();
 
 940   my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
 
 942   $::lxdebug->leave_sub;
 
 947   my ($self, $myconfig, $form, $units, $delete_units) = @_;
 
 949   my $dbh = SL::DB->client->dbh;
 
 951   my ($base_unit, $unit, $sth, $query);
 
 953   $query = "DELETE FROM units_language";
 
 954   $dbh->do($query) || $form->dberror($query);
 
 956   if ($delete_units && (0 != scalar(@{$delete_units}))) {
 
 957     $query = "DELETE FROM units WHERE name IN (";
 
 958     map({ $query .= "?," } @{$delete_units});
 
 959     substr($query, -1, 1) = ")";
 
 960     $dbh->do($query, undef, @{$delete_units}) ||
 
 961       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
 
 964   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
 
 965   $sth = $dbh->prepare($query);
 
 967   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
 
 968   my $sth_lang = $dbh->prepare($query_lang);
 
 970   foreach $unit (values(%{$units})) {
 
 971     $unit->{"depth"} = 0;
 
 972     my $base_unit = $unit;
 
 973     while ($base_unit->{"base_unit"}) {
 
 975       $base_unit = $units->{$base_unit->{"base_unit"}};
 
 979   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
 
 980     if ($unit->{"LANGUAGES"}) {
 
 981       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
 
 982         next unless ($lang->{"id"} && $lang->{"localized"});
 
 983         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
 
 984         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
 
 988     next if ($unit->{"unchanged_unit"});
 
 990     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
 
 991     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
 
1001   $main::lxdebug->enter_sub();
 
1003   my ($self, $myconfig, $form) = @_;
 
1005   my $dbh = SL::DB->client->dbh;
 
1007   my $query = qq|SELECT
 
1011                    round(t.rate * 100, 2) AS rate,
 
1012                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
 
1013                    (SELECT description FROM chart WHERE id = chart_id) AS account_description,
 
1014                    (SELECT accno FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_accno,
 
1015                    (SELECT description FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_description,
 
1016                    (SELECT accno FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_accno,
 
1017                    (SELECT description FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_description
 
1019                  ORDER BY taxkey, rate|;
 
1021   my $sth = $dbh->prepare($query);
 
1022   $sth->execute || $form->dberror($query);
 
1025   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1026     push @{ $form->{TAX} }, $ref;
 
1031   $main::lxdebug->leave_sub();
 
1034 sub get_tax_accounts {
 
1035   $main::lxdebug->enter_sub();
 
1037   my ($self, $myconfig, $form) = @_;
 
1039   my $dbh = SL::DB->client->dbh;
 
1041   # get Accounts from chart
 
1042   my $query = qq{ SELECT
 
1044                  accno || ' - ' || description AS taxaccount
 
1046                WHERE link LIKE '%_tax%'
 
1050   my $sth = $dbh->prepare($query);
 
1051   $sth->execute || $form->dberror($query);
 
1053   $form->{ACCOUNTS} = [];
 
1054   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1055     push @{ $form->{ACCOUNTS} }, $ref;
 
1058   $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
 
1059   $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
 
1061   $form->{skontochart_value_title_sub} = sub {
 
1065       $item->{accno} .' '. $item->{description},
 
1071   $main::lxdebug->leave_sub();
 
1075   $main::lxdebug->enter_sub();
 
1077   my ($self, $myconfig, $form) = @_;
 
1079   my $dbh = SL::DB->client->dbh;
 
1081   my $query = qq|SELECT
 
1084                    round(rate * 100, 2) AS rate,
 
1087                    (id IN (SELECT tax_id
 
1088                            FROM acc_trans)) AS tax_already_used,
 
1089                    skonto_sales_chart_id,
 
1090                    skonto_purchase_chart_id
 
1094   my $sth = $dbh->prepare($query);
 
1095   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
 
1097   my $ref = $sth->fetchrow_hashref("NAME_lc");
 
1099   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1103   # see if it is used by a taxkey
 
1104   $query = qq|SELECT count(*) FROM taxkeys
 
1105               WHERE tax_id = ? AND chart_id >0|;
 
1107   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
 
1109   $form->{orphaned} = !$form->{orphaned};
 
1112   if (!$form->{orphaned} ) {
 
1113     $query = qq|SELECT DISTINCT c.id, c.accno
 
1115                 JOIN   tax t ON (t.id = tk.tax_id)
 
1116                 JOIN chart c ON (c.id = tk.chart_id)
 
1117                 WHERE tk.tax_id = ?|;
 
1119     $sth = $dbh->prepare($query);
 
1120     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
 
1122     $form->{TAXINUSE} = [];
 
1123     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1124       push @{ $form->{TAXINUSE} }, $ref;
 
1130   $main::lxdebug->leave_sub();
 
1134   my ($self, $myconfig, $form) = @_;
 
1135   $main::lxdebug->enter_sub();
 
1137   my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
 
1139   $::lxdebug->leave_sub;
 
1144   my ($self, $myconfig, $form) = @_;
 
1147   my $dbh = SL::DB->client->dbh;
 
1149   $form->{rate} = $form->{rate} / 100;
 
1151   my $chart_categories = '';
 
1152   $chart_categories .= 'A' if $form->{asset};
 
1153   $chart_categories .= 'L' if $form->{liability};
 
1154   $chart_categories .= 'Q' if $form->{equity};
 
1155   $chart_categories .= 'I' if $form->{revenue};
 
1156   $chart_categories .= 'E' if $form->{expense};
 
1157   $chart_categories .= 'C' if $form->{costs};
 
1159   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, conv_i($form->{chart_id}), conv_i($form->{chart_id}), conv_i($form->{skonto_sales_chart_id}), conv_i($form->{skonto_purchase_chart_id}), $chart_categories);
 
1160   if ($form->{id} ne "") {
 
1161     $query = qq|UPDATE tax SET
 
1166                   taxnumber                = (SELECT accno FROM chart WHERE id = ? ),
 
1167                   skonto_sales_chart_id    = ?,
 
1168                   skonto_purchase_chart_id = ?,
 
1169                   chart_categories         = ?
 
1174     ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
 
1175     $query = qq|INSERT INTO tax (
 
1181                   skonto_sales_chart_id,
 
1182                   skonto_purchase_chart_id,
 
1186                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?), ?, ?,  ?, ?)|;
 
1188   push(@values, $form->{id});
 
1189   do_query($form, $dbh, $query, @values);
 
1191   foreach my $language_id (keys %{ $form->{translations} }) {
 
1192     GenericTranslations->save('dbh'              => $dbh,
 
1193                               'translation_type' => 'SL::DB::Tax/taxdescription',
 
1194                               'translation_id'   => $form->{id},
 
1195                               'language_id'      => $language_id,
 
1196                               'translation'      => $form->{translations}->{$language_id});
 
1201   $main::lxdebug->enter_sub();
 
1203   my ($self, $myconfig, $form) = @_;
 
1206   SL::DB->client->with_transaction(sub {
 
1207     $query = qq|DELETE FROM tax WHERE id = ?|;
 
1208     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
1210   }) or do { die SL::DB->client->error };
 
1212   $main::lxdebug->leave_sub();
 
1215 sub save_warehouse {
 
1216   $main::lxdebug->enter_sub();
 
1218   my ($self, $myconfig, $form) = @_;
 
1220   SL::DB->client->with_transaction(sub {
 
1221     my $dbh = SL::DB->client->dbh;
 
1223     my ($query, @values, $sth);
 
1226       $query        = qq|SELECT nextval('id')|;
 
1227       ($form->{id}) = selectrow_query($form, $dbh, $query);
 
1229       $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
 
1230       do_query($form, $dbh, $query, $form->{id});
 
1233     do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
 
1234              $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
 
1236     if (0 < $form->{number_of_new_bins}) {
 
1237       my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
 
1238       $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
 
1239       $sth   = prepare_query($form, $dbh, $query);
 
1241       foreach my $i (1..$form->{number_of_new_bins}) {
 
1242         do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
 
1248   }) or do { die SL::DB->client->error };
 
1250   $main::lxdebug->leave_sub();
 
1254   $main::lxdebug->enter_sub();
 
1256   my ($self, $myconfig, $form) = @_;
 
1258   SL::DB->client->with_transaction(sub {
 
1259     my $dbh = SL::DB->client->dbh;
 
1261     my ($query, @values, $sth);
 
1263     @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
 
1266       $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
 
1267       do_query($form, $dbh, $query, @values);
 
1270     $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
 
1271     $sth   = prepare_query($form, $dbh, $query);
 
1273     foreach my $row (1..$form->{rowcount}) {
 
1274       next if ($form->{"delete_${row}"});
 
1276       do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
 
1281   }) or do { die SL::DB->client->error };
 
1283   $main::lxdebug->leave_sub();
 
1286 sub delete_warehouse {
 
1287   $main::lxdebug->enter_sub();
 
1289   my ($self, $myconfig, $form) = @_;
 
1291   my $rc = SL::DB->client->with_transaction(sub {
 
1292     my $dbh = SL::DB->client->dbh;
 
1294     my $id      = conv_i($form->{id});
 
1295     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|;
 
1296     my ($count) = selectrow_query($form, $dbh, $query, $id);
 
1302     do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
 
1303     do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
 
1308   $main::lxdebug->leave_sub();
 
1313 sub get_all_warehouses {
 
1314   $main::lxdebug->enter_sub();
 
1316   my ($self, $myconfig, $form) = @_;
 
1318   my $dbh = SL::DB->client->dbh;
 
1320   my $query = qq|SELECT w.id, w.description, w.invalid,
 
1321                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
 
1323                  ORDER BY w.sortkey|;
 
1325   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
 
1327   $main::lxdebug->leave_sub();
 
1331   $main::lxdebug->enter_sub();
 
1333   my ($self, $myconfig, $form) = @_;
 
1335   my $dbh = SL::DB->client->dbh;
 
1337   my $id    = conv_i($form->{id});
 
1338   my $query = qq|SELECT w.description, w.invalid
 
1342   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
 
1344   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
1347    SELECT b.*, use.in_use
 
1350        SELECT DISTINCT bin_id, TRUE AS in_use FROM inventory
 
1352        SELECT DISTINCT bin_id, TRUE AS in_use FROM parts
 
1353      ) use ON use.bin_id = b.id
 
1354      WHERE b.warehouse_id = ?;
 
1357   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
1359   $main::lxdebug->leave_sub();
 
1362 sub get_eur_categories {
 
1363   my ($self, $myconfig, $form) = @_;
 
1365   my $dbh = SL::DB->client->dbh;
 
1366   my %eur_categories = selectall_as_map($form, $dbh, "select * from eur_categories order by id", 'id', 'description');
 
1368   return \%eur_categories;
 
1371 sub get_bwa_categories {
 
1372   my ($self, $myconfig, $form) = @_;
 
1374   my $dbh = SL::DB->client->dbh;
 
1375   my %bwa_categories = selectall_as_map($form, $dbh, "select * from bwa_categories order by id", 'id', 'description');
 
1377   return \%bwa_categories;