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::TimeRecording;
 
  58 use SL::Helper::UserPreferences::UpdatePositions;
 
  63   $main::lxdebug->enter_sub();
 
  65   # fetch chart-related data and set form fields
 
  66   # get_account is called by add_account in am.pl
 
  67   # always sets $form->{TAXKEY} and default_accounts
 
  68   # loads chart data when $form->{id} is passed
 
  70   my ($self, $myconfig, $form) = @_;
 
  72   # get default accounts
 
  73   map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
 
  76   my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
 
  78   foreach my $tk ( @{$taxes} ) {
 
  79     push @{ $form->{TAXKEY} },  { id          => $tk->id,
 
  80                                   chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
 
  81                                   taxkey      => $tk->taxkey,
 
  82                                   tax         => $tk->id . '--' . $tk->taxkey,
 
  89     my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
 
  91     my @chart_fields = qw(accno description charttype category link pos_bilanz
 
  92                           pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik);
 
  93     foreach my $cf ( @chart_fields ) {
 
  94       $form->{"$cf"} = $chart_obj->$cf;
 
  97     my $active_taxkey = $chart_obj->get_active_taxkey;
 
  98     $form->{$_}  = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
 
  99     $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
 
 101     # check if there are any transactions for this chart
 
 102     $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
 
 104     # check if new account is active
 
 105     # The old sql query was broken since at least 2006 and always returned 0
 
 106     $form->{new_chart_valid} = $chart_obj->new_chart_valid;
 
 108     # get the taxkeys of the account
 
 109     $form->{ACCOUNT_TAXKEYS} = [];
 
 110     foreach my $taxkey ( sort { $b->startdate <=> $a->startdate } @{ $chart_obj->taxkeys } ) {
 
 111       push @{ $form->{ACCOUNT_TAXKEYS} }, { id             => $taxkey->id,
 
 112                                             chart_id       => $taxkey->chart_id,
 
 113                                             tax_id         => $taxkey->tax_id,
 
 114                                             taxkey_id      => $taxkey->taxkey_id,
 
 115                                             pos_ustva      => $taxkey->pos_ustva,
 
 116                                             startdate      => $taxkey->startdate->to_kivitendo,
 
 117                                             taxdescription => $taxkey->tax->taxdescription,
 
 118                                             rate           => $taxkey->tax->rate,
 
 119                                             accno          => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
 
 123     # get new accounts (Folgekonto). Find all charts with the same link
 
 124     $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});
 
 126   } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
 
 127     $form->{orphaned} = 1;
 
 130   $main::lxdebug->leave_sub();
 
 134   my ($self, $myconfig, $form) = @_;
 
 135   $main::lxdebug->enter_sub();
 
 137   my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
 
 139   $::lxdebug->leave_sub;
 
 144   # TODO: it should be forbidden to change an account to a heading if there
 
 145   # have been bookings to this account in the past
 
 147   my ($self, $myconfig, $form) = @_;
 
 149   my $dbh = SL::DB->client->dbh;
 
 151   for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
 
 152     $form->{$form->{$_}} = $form->{$_} if $form->{$_};
 
 155   # sanity check, can't have AR with AR_...
 
 156   if ($form->{AR} || $form->{AP} || $form->{IC}) {
 
 157     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)) {
 
 158       $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
 
 162   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);
 
 163   $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
 
 165   # strip blanks from accno
 
 166   map { $form->{$_} =~ s/ //g; } qw(accno);
 
 168   # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
 
 169   map { $form->{$_} =~ s/\h+/ /g } qw(description);
 
 173   if ($form->{id} eq "NULL") {
 
 182   my @values = ($form->{accno});
 
 185     $query .= ' AND NOT id = ?';
 
 186     push(@values, $form->{id});
 
 189   my ($accno) = selectrow_query($form, $dbh, $query, @values);
 
 192     $form->error($::locale->text('Account number not unique!'));
 
 196   if (!$form->{id} || $form->{id} eq "") {
 
 197     $query = qq|SELECT nextval('id')|;
 
 198     ($form->{"id"}) = selectrow_query($form, $dbh, $query);
 
 199     $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
 
 200     do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
 
 208     # if charttype is heading make sure certain values are empty
 
 209     # specifically, if charttype is changed from an existing account, empty the
 
 210     # fields unnecessary for headings, so that e.g. heading doesn't appear in
 
 211     # drop-down menues due to still having a valid "link" entry
 
 213     if ( $form->{charttype} eq 'H' ) {
 
 215       $form->{pos_bwa} = '';
 
 216       $form->{pos_bilanz} = '';
 
 217       $form->{pos_eur} = '';
 
 218       $form->{new_chart_id} = '';
 
 219       $form->{valid_from} = '';
 
 222     $query = qq|UPDATE chart SET
 
 239                   $form->{description},
 
 243                   conv_i($form->{pos_bwa}),
 
 244                   conv_i($form->{pos_bilanz}),
 
 245                   conv_i($form->{pos_eur}),
 
 246                   conv_i($form->{pos_er}),
 
 247                   conv_i($form->{new_chart_id}),
 
 248                   conv_date($form->{valid_from}),
 
 249                   ($form->{datevautomatik} eq 'T') ? 'true':'false',
 
 256   do_query($form, $dbh, $query, @values);
 
 262   my $MAX_TRIES = 10; # Maximum count of taxkeys in form
 
 266   for $tk_count (0 .. $MAX_TRIES) {
 
 270     # Check if the account already exists, else cancel
 
 272     print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
 
 274     last READTAXKEYS if ( $form->{'id'} == 0);
 
 276     # check if there is a startdate
 
 277     if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
 
 282     # Add valid taxkeys into the array
 
 285         id        => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
 
 286         tax_id    => conv_i($form->{"taxkey_tax_$tk_count"}),
 
 287         startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
 
 288         chart_id  => conv_i($form->{"id"}),
 
 289         pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
 
 290         delete    => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
 
 297   for my $j (0 .. $#taxkeys){
 
 298     if ( defined $taxkeys[$j]{'id'} ){
 
 301       if ($taxkeys[$j]{'delete'}){
 
 303           DELETE FROM taxkeys WHERE id = ?
 
 306         @values = ($taxkeys[$j]{'id'});
 
 308         do_query($form, $dbh, $query, @values);
 
 317         SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
 
 325         $taxkeys[$j]{'tax_id'},
 
 326         $taxkeys[$j]{'chart_id'},
 
 327         $taxkeys[$j]{'tax_id'},
 
 328         $taxkeys[$j]{'pos_ustva'},
 
 329         $taxkeys[$j]{'startdate'},
 
 332       do_query($form, $dbh, $query, @values);
 
 338         INSERT INTO taxkeys (
 
 345         VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
 
 348         $taxkeys[$j]{'tax_id'},
 
 349         $taxkeys[$j]{'chart_id'},
 
 350         $taxkeys[$j]{'tax_id'},
 
 351         $taxkeys[$j]{'pos_ustva'},
 
 352         $taxkeys[$j]{'startdate'},
 
 355       do_query($form, $dbh, $query, @values);
 
 360   # Update chart.taxkey_id to the latest from taxkeys for this chart.
 
 366       WHERE taxkeys.chart_id = chart.id
 
 367       ORDER BY startdate DESC
 
 373   do_query($form, $dbh, $query, $form->{id});
 
 379   my ($self, $myconfig, $form) = @_;
 
 380   $main::lxdebug->enter_sub();
 
 382   my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
 
 384   $::lxdebug->leave_sub;
 
 388 sub _delete_account {
 
 389   my ($self, $myconfig, $form) = @_;
 
 391   my $dbh = SL::DB->client->dbh;
 
 393   my $query = qq|SELECT count(*) FROM acc_trans a
 
 394                  WHERE a.chart_id = ?|;
 
 395   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
 
 401   $query = qq|DELETE FROM tax
 
 403   do_query($form, $dbh, $query, $form->{id});
 
 405   # delete account taxkeys
 
 406   $query = qq|DELETE FROM taxkeys
 
 408   do_query($form, $dbh, $query, $form->{id});
 
 410   # delete chart of account record
 
 411   # last step delete chart, because we have a constraint
 
 413   $query = qq|DELETE FROM chart
 
 415   do_query($form, $dbh, $query, $form->{id});
 
 420 sub get_language_details {
 
 421   $main::lxdebug->enter_sub();
 
 423   my ($self, $myconfig, $form, $id) = @_;
 
 425   my $dbh = SL::DB->client->dbh;
 
 428     "SELECT template_code, " .
 
 429     "  output_numberformat, output_dateformat, output_longdates " .
 
 430     "FROM language WHERE id = ?";
 
 431   my @res = selectrow_query($form, $dbh, $query, $id);
 
 433   $main::lxdebug->leave_sub();
 
 438 sub prepare_template_filename {
 
 439   $main::lxdebug->enter_sub();
 
 441   my ($self, $myconfig, $form) = @_;
 
 443   my ($filename, $display_filename);
 
 445   $filename = $form->{formname};
 
 447   if ($form->{language}) {
 
 448     my ($id, $template_code) = split(/--/, $form->{language});
 
 449     $filename .= "_${template_code}";
 
 452   if ($form->{printer}) {
 
 453     my ($id, $template_code) = split(/--/, $form->{printer});
 
 454     $filename .= "_${template_code}";
 
 457   $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
 
 458   if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
 
 459     $filename =~ s|.*/||;
 
 461   $display_filename = $filename;
 
 462   $filename = SL::DB::Default->get->templates . "/$filename";
 
 464   $main::lxdebug->leave_sub();
 
 466   return ($filename, $display_filename);
 
 471   $main::lxdebug->enter_sub();
 
 473   my ($self, $filename) = @_;
 
 475   my ($content, $lines) = ("", 0);
 
 479   if (open(TEMPLATE, $filename)) {
 
 487   $content = Encode::decode('utf-8-strict', $content);
 
 489   $main::lxdebug->leave_sub();
 
 491   return ($content, $lines);
 
 495   $main::lxdebug->enter_sub();
 
 497   my ($self, $filename, $content) = @_;
 
 503   if (open(TEMPLATE, ">", $filename)) {
 
 504     $content = Encode::encode('utf-8-strict', $content);
 
 505     $content =~ s/\r\n/\n/g;
 
 506     print(TEMPLATE $content);
 
 512   $main::lxdebug->leave_sub();
 
 517 sub displayable_name_specs_by_module {
 
 519      'SL::DB::Customer' => {
 
 520        specs => SL::DB::Customer->displayable_name_specs,
 
 521        prefs => SL::DB::Customer->displayable_name_prefs,
 
 523      'SL::DB::Vendor' => {
 
 524        specs => SL::DB::Vendor->displayable_name_specs,
 
 525        prefs => SL::DB::Vendor->displayable_name_prefs,
 
 528        specs => SL::DB::Part->displayable_name_specs,
 
 529        prefs => SL::DB::Part->displayable_name_prefs,
 
 534 sub positions_scrollbar_height {
 
 535   SL::Helper::UserPreferences::PositionsScrollbar->new()->get_height();
 
 538 sub purchase_search_makemodel {
 
 539   SL::Helper::UserPreferences::PartPickerSearch->new()->get_purchase_search_makemodel();
 
 542 sub sales_search_customer_partnumber {
 
 543   SL::Helper::UserPreferences::PartPickerSearch->new()->get_sales_search_customer_partnumber();
 
 546 sub positions_show_update_button {
 
 547   SL::Helper::UserPreferences::UpdatePositions->new()->get_show_update_button();
 
 550 sub time_recording_use_duration {
 
 551   SL::Helper::UserPreferences::TimeRecording->new()->get_use_duration();
 
 554 sub save_preferences {
 
 555   $main::lxdebug->enter_sub();
 
 557   my ($self, $form) = @_;
 
 559   my $employee = SL::DB::Manager::Employee->find_by(login => $::myconfig{login});
 
 560   $employee->update_attributes(name => $form->{name});
 
 562   my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
 
 563   $user->update_attributes(
 
 565       %{ $user->config_values },
 
 566       map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
 
 569   # Displayable name preferences
 
 570   my $displayable_name_specs_by_module = displayable_name_specs_by_module();
 
 571   foreach my $specs (@{ $form->{displayable_name_specs} }) {
 
 572     if (!$specs->{value} || $specs->{value} eq $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->get_default()) {
 
 573       $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->delete($specs->{value});
 
 575       $displayable_name_specs_by_module->{$specs->{module}}->{prefs}->store_value($specs->{value});
 
 579   if (exists $form->{positions_scrollbar_height}) {
 
 580     SL::Helper::UserPreferences::PositionsScrollbar->new()->store_height($form->{positions_scrollbar_height})
 
 582   if (exists $form->{purchase_search_makemodel}) {
 
 583     SL::Helper::UserPreferences::PartPickerSearch->new()->store_purchase_search_makemodel($form->{purchase_search_makemodel})
 
 585   if (exists $form->{sales_search_customer_partnumber}) {
 
 586     SL::Helper::UserPreferences::PartPickerSearch->new()->store_sales_search_customer_partnumber($form->{sales_search_customer_partnumber})
 
 588   if (exists $form->{positions_show_update_button}) {
 
 589     SL::Helper::UserPreferences::UpdatePositions->new()->store_show_update_button($form->{positions_show_update_button})
 
 591   if (exists $form->{time_recording_use_duration}) {
 
 592     SL::Helper::UserPreferences::TimeRecording->new()->store_use_duration($form->{time_recording_use_duration})
 
 595   $main::lxdebug->leave_sub();
 
 601   $main::lxdebug->enter_sub();
 
 606   my $myconfig = \%main::myconfig;
 
 607   my $form     = $main::form;
 
 609   my $dbh      = $params{dbh} || SL::DB->client->dbh;
 
 611   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
 
 613   $defaults->{weightunit} ||= 'kg';
 
 615   $main::lxdebug->leave_sub();
 
 621   $main::lxdebug->enter_sub();
 
 623   my ($self, $myconfig, $form) = @_;
 
 625   my $dbh = SL::DB->client->dbh;
 
 627   my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
 
 628   my $sth   = $dbh->prepare($query);
 
 629   $sth->execute || $form->dberror($query);
 
 631   ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
 
 635   $main::lxdebug->leave_sub();
 
 639   $main::lxdebug->enter_sub();
 
 641   my ($self, $myconfig, $form) = @_;
 
 643   SL::DB->client->with_transaction(sub {
 
 644     my $dbh = SL::DB->client->dbh;
 
 646     my ($query, @values);
 
 648     # is currently NEVER trueish (no more hidden revtrans in $form)
 
 649     # if ($form->{revtrans}) {
 
 650     #   $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
 
 651     # -> therefore you can only set this to false (which is already the default)
 
 652     # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
 
 654       $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
 
 655       @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
 
 657     # set close in defaults
 
 658     do_query($form, $dbh, $query, @values);
 
 660   }) or do { die SL::DB->client->error };
 
 662   $main::lxdebug->leave_sub();
 
 666   my ($self, $units, $unit_name, $factor) = @_;
 
 668   $factor = 1 unless ($factor);
 
 670   my $unit = $units->{$unit_name};
 
 672   if (!defined($unit) || !$unit->{"base_unit"} ||
 
 673       ($unit_name eq $unit->{"base_unit"})) {
 
 674     return ($unit_name, $factor);
 
 677   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
 
 681   $main::lxdebug->enter_sub();
 
 683   my ($self, $myconfig, $form, $prefix) = @_;
 
 686   my $dbh = SL::DB->client->dbh;
 
 688   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
 
 690   my $sth = prepare_execute_query($form, $dbh, $query);
 
 693   while (my $ref = $sth->fetchrow_hashref()) {
 
 694     $units->{$ref->{"name"}} = $ref;
 
 698   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
 
 699   $sth = $dbh->prepare($query_lang);
 
 700   $sth->execute() || $form->dberror($query_lang);
 
 702   while (my $ref = $sth->fetchrow_hashref()) {
 
 703     push(@languages, $ref);
 
 707   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
 
 708     "FROM units_language ul " .
 
 709     "LEFT JOIN language l ON ul.language_id = l.id " .
 
 711   $sth = $dbh->prepare($query_lang);
 
 713   foreach my $unit (values(%{$units})) {
 
 714     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
 
 716     $unit->{"LANGUAGES"} = {};
 
 717     foreach my $lang (@languages) {
 
 718       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
 
 721     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
 
 722     while (my $ref = $sth->fetchrow_hashref()) {
 
 723       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
 
 728   $main::lxdebug->leave_sub();
 
 733 sub retrieve_all_units {
 
 734   $main::lxdebug->enter_sub();
 
 738   if (!$::request->{cache}{all_units}) {
 
 739     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
 
 742   $main::lxdebug->leave_sub();
 
 744   return $::request->{cache}{all_units};
 
 748 sub translate_units {
 
 749   $main::lxdebug->enter_sub();
 
 751   my ($self, $form, $template_code, $unit, $amount) = @_;
 
 753   my $units = $self->retrieve_units(\%main::myconfig, $form);
 
 755   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
 
 756   my $new_unit = $unit;
 
 758     if (($amount != 1) && $h->{"localized_plural"}) {
 
 759       $new_unit = $h->{"localized_plural"};
 
 760     } elsif ($h->{"localized"}) {
 
 761       $new_unit = $h->{"localized"};
 
 765   $main::lxdebug->leave_sub();
 
 771   $main::lxdebug->enter_sub();
 
 773   my ($self, $myconfig, $form, $units) = @_;
 
 775   my $dbh = SL::DB->client->dbh;
 
 777   map({ $_->{"in_use"} = 0; } values(%{$units}));
 
 779   foreach my $unit (values(%{$units})) {
 
 780     my $base_unit = $unit->{"original_base_unit"};
 
 782       $units->{$base_unit}->{"in_use"} = 1;
 
 783       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
 
 784       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
 
 785       $base_unit = $units->{$base_unit}->{"original_base_unit"};
 
 789   foreach my $unit (values(%{$units})) {
 
 790     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
 
 792     foreach my $table (qw(parts invoice orderitems)) {
 
 793       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
 
 795       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
 
 796         $query .= "= " . $dbh->quote($unit->{"name"});
 
 798         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
 
 799           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
 
 802       my ($count) = $dbh->selectrow_array($query);
 
 803       $form->dberror($query) if ($dbh->err);
 
 806         $unit->{"in_use"} = 1;
 
 812   $main::lxdebug->leave_sub();
 
 815 sub convertible_units {
 
 816   $main::lxdebug->enter_sub();
 
 820   my $filter_unit = shift;
 
 821   my $not_smaller = shift;
 
 825   $filter_unit = $units->{$filter_unit};
 
 827   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
 
 828     my $unit = $units->{$name};
 
 830     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
 
 831         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
 
 832       push @{$conv_units}, $unit;
 
 836   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
 
 838   $main::lxdebug->leave_sub();
 
 843 # if $a is translatable to $b, return the factor between them.
 
 846   $main::lxdebug->enter_sub(2);
 
 847   my ($this, $a, $b, $all_units) = @_;
 
 850     $all_units = $this->retrieve_all_units;
 
 853   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
 
 854   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
 
 855   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
 
 856   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
 
 859 sub unit_select_data {
 
 860   $main::lxdebug->enter_sub();
 
 862   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
 
 867     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
 
 870   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
 
 871     if (!$convertible_into ||
 
 872         ($units->{$convertible_into} &&
 
 873          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
 
 874       push @{$select}, { "name"      => $unit,
 
 875                          "base_unit" => $units->{$unit}->{"base_unit"},
 
 876                          "factor"    => $units->{$unit}->{"factor"},
 
 877                          "selected"  => ($unit eq $selected) ? "selected" : "" };
 
 881   $main::lxdebug->leave_sub();
 
 886 sub unit_select_html {
 
 887   $main::lxdebug->enter_sub();
 
 889   my ($self, $units, $name, $selected, $convertible_into) = @_;
 
 891   my $select = "<select name=${name}>";
 
 893   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
 
 894     if (!$convertible_into ||
 
 895         ($units->{$convertible_into} &&
 
 896          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
 
 897       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
 
 900   $select .= "</select>";
 
 902   $main::lxdebug->leave_sub();
 
 908   $main::lxdebug->enter_sub();
 
 912   my $units = $self->retrieve_all_units();
 
 917   while (2 <= scalar(@_)) {
 
 919     my $unit = $units->{shift(@_)};
 
 921     croak "No unit defined with name $unit" if (!defined $unit);
 
 924       $base_unit = $unit->{base_unit};
 
 925     } elsif ($base_unit ne $unit->{base_unit}) {
 
 926       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
 
 929     $sum += $qty * $unit->{factor};
 
 932   $main::lxdebug->leave_sub();
 
 938   $main::lxdebug->enter_sub();
 
 940   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
 
 942   SL::DB->client->with_transaction(sub {
 
 943     my $dbh = SL::DB->client->dbh;
 
 945     my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
 
 946     my ($sortkey) = selectrow_query($form, $dbh, $query);
 
 948     $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
 
 949       "VALUES (?, ?, ?, ?)";
 
 950     do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
 
 953       $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
 
 954       my $sth = $dbh->prepare($query);
 
 955       foreach my $lang (@{$languages}) {
 
 956         my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
 
 957         $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
 
 962   }) or do { die SL::DB->client->error };
 
 964   $main::lxdebug->leave_sub();
 
 968   my ($self, $myconfig, $form, $units, $delete_units) = @_;
 
 969   $main::lxdebug->enter_sub();
 
 971   my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
 
 973   $::lxdebug->leave_sub;
 
 978   my ($self, $myconfig, $form, $units, $delete_units) = @_;
 
 980   my $dbh = SL::DB->client->dbh;
 
 982   my ($base_unit, $unit, $sth, $query);
 
 984   $query = "DELETE FROM units_language";
 
 985   $dbh->do($query) || $form->dberror($query);
 
 987   if ($delete_units && (0 != scalar(@{$delete_units}))) {
 
 988     $query = "DELETE FROM units WHERE name IN (";
 
 989     map({ $query .= "?," } @{$delete_units});
 
 990     substr($query, -1, 1) = ")";
 
 991     $dbh->do($query, undef, @{$delete_units}) ||
 
 992       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
 
 995   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
 
 996   $sth = $dbh->prepare($query);
 
 998   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
 
 999   my $sth_lang = $dbh->prepare($query_lang);
 
1001   foreach $unit (values(%{$units})) {
 
1002     $unit->{"depth"} = 0;
 
1003     my $base_unit = $unit;
 
1004     while ($base_unit->{"base_unit"}) {
 
1006       $base_unit = $units->{$base_unit->{"base_unit"}};
 
1010   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
 
1011     if ($unit->{"LANGUAGES"}) {
 
1012       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
 
1013         next unless ($lang->{"id"} && $lang->{"localized"});
 
1014         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
 
1015         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
 
1019     next if ($unit->{"unchanged_unit"});
 
1021     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
 
1022     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
 
1026   $sth_lang->finish();
 
1032   $main::lxdebug->enter_sub();
 
1034   my ($self, $myconfig, $form) = @_;
 
1036   my $dbh = SL::DB->client->dbh;
 
1038   my $query = qq|SELECT
 
1042                    round(t.rate * 100, 2) AS rate,
 
1043                    tc.accno               AS taxnumber,
 
1044                    tc.description         AS account_description,
 
1045                    ssc.accno              AS skonto_chart_accno,
 
1046                    ssc.description        AS skonto_chart_description,
 
1047                    spc.accno              AS skonto_chart_purchase_accno,
 
1048                    spc.description        AS skonto_chart_purchase_description
 
1050                  LEFT JOIN chart tc  ON (tc.id = t.chart_id)
 
1051                  LEFT JOIN chart ssc ON (ssc.id = t.skonto_sales_chart_id)
 
1052                  LEFT JOIN chart spc ON (spc.id = t.skonto_purchase_chart_id)
 
1053                  ORDER BY taxkey, rate|;
 
1055   my $sth = $dbh->prepare($query);
 
1056   $sth->execute || $form->dberror($query);
 
1059   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1060     push @{ $form->{TAX} }, $ref;
 
1065   $main::lxdebug->leave_sub();
 
1068 sub get_tax_accounts {
 
1069   $main::lxdebug->enter_sub();
 
1071   my ($self, $myconfig, $form) = @_;
 
1073   my $dbh = SL::DB->client->dbh;
 
1075   # get Accounts from chart
 
1076   my $query = qq{ SELECT
 
1078                  accno || ' - ' || description AS taxaccount
 
1080                WHERE link LIKE '%_tax%'
 
1084   my $sth = $dbh->prepare($query);
 
1085   $sth->execute || $form->dberror($query);
 
1087   $form->{ACCOUNTS} = [];
 
1088   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1089     push @{ $form->{ACCOUNTS} }, $ref;
 
1092   $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
 
1093   $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
 
1095   $form->{skontochart_value_title_sub} = sub {
 
1099       $item->{accno} .' '. $item->{description},
 
1105   $main::lxdebug->leave_sub();
 
1109   $main::lxdebug->enter_sub();
 
1111   my ($self, $myconfig, $form) = @_;
 
1113   my $dbh = SL::DB->client->dbh;
 
1115   my $query = qq|SELECT
 
1118                    round(rate * 100, 2) AS rate,
 
1121                    (id IN (SELECT tax_id
 
1122                            FROM acc_trans)) AS tax_already_used,
 
1123                    skonto_sales_chart_id,
 
1124                    skonto_purchase_chart_id
 
1128   my $sth = $dbh->prepare($query);
 
1129   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
 
1131   my $ref = $sth->fetchrow_hashref("NAME_lc");
 
1133   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1137   # see if it is used by a taxkey
 
1138   $query = qq|SELECT count(*) FROM taxkeys
 
1139               WHERE tax_id = ? AND chart_id >0|;
 
1141   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
 
1143   $form->{orphaned} = !$form->{orphaned};
 
1146   if (!$form->{orphaned} ) {
 
1147     $query = qq|SELECT DISTINCT c.id, c.accno
 
1149                 JOIN   tax t ON (t.id = tk.tax_id)
 
1150                 JOIN chart c ON (c.id = tk.chart_id)
 
1151                 WHERE tk.tax_id = ?|;
 
1153     $sth = $dbh->prepare($query);
 
1154     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
 
1156     $form->{TAXINUSE} = [];
 
1157     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1158       push @{ $form->{TAXINUSE} }, $ref;
 
1164   $main::lxdebug->leave_sub();
 
1168   my ($self, $myconfig, $form) = @_;
 
1169   $main::lxdebug->enter_sub();
 
1171   my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
 
1173   $::lxdebug->leave_sub;
 
1178   my ($self, $myconfig, $form) = @_;
 
1181   my $dbh = SL::DB->client->dbh;
 
1183   $form->{rate} = $form->{rate} / 100;
 
1185   my $chart_categories = '';
 
1186   $chart_categories .= 'A' if $form->{asset};
 
1187   $chart_categories .= 'L' if $form->{liability};
 
1188   $chart_categories .= 'Q' if $form->{equity};
 
1189   $chart_categories .= 'I' if $form->{revenue};
 
1190   $chart_categories .= 'E' if $form->{expense};
 
1191   $chart_categories .= 'C' if $form->{costs};
 
1193   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);
 
1194   if ($form->{id} ne "") {
 
1195     $query = qq|UPDATE tax SET
 
1200                   skonto_sales_chart_id    = ?,
 
1201                   skonto_purchase_chart_id = ?,
 
1202                   chart_categories         = ?
 
1207     ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
 
1208     $query = qq|INSERT INTO tax (
 
1213                   skonto_sales_chart_id,
 
1214                   skonto_purchase_chart_id,
 
1218                 VALUES (?, ?, ?, ?, ?, ?,  ?, ?)|;
 
1220   push(@values, $form->{id});
 
1221   do_query($form, $dbh, $query, @values);
 
1223   foreach my $language_id (keys %{ $form->{translations} }) {
 
1224     GenericTranslations->save('dbh'              => $dbh,
 
1225                               'translation_type' => 'SL::DB::Tax/taxdescription',
 
1226                               'translation_id'   => $form->{id},
 
1227                               'language_id'      => $language_id,
 
1228                               'translation'      => $form->{translations}->{$language_id});
 
1233   $main::lxdebug->enter_sub();
 
1235   my ($self, $myconfig, $form) = @_;
 
1238   SL::DB->client->with_transaction(sub {
 
1239     $query = qq|DELETE FROM tax WHERE id = ?|;
 
1240     do_query($form, SL::DB->client->dbh, $query, $form->{id});
 
1242   }) or do { die SL::DB->client->error };
 
1244   $main::lxdebug->leave_sub();
 
1247 sub save_warehouse {
 
1248   $main::lxdebug->enter_sub();
 
1250   my ($self, $myconfig, $form) = @_;
 
1252   SL::DB->client->with_transaction(sub {
 
1253     my $dbh = SL::DB->client->dbh;
 
1255     my ($query, @values, $sth);
 
1258       $query        = qq|SELECT nextval('id')|;
 
1259       ($form->{id}) = selectrow_query($form, $dbh, $query);
 
1261       $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
 
1262       do_query($form, $dbh, $query, $form->{id});
 
1265     do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
 
1266              $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
 
1268     if (0 < $form->{number_of_new_bins}) {
 
1269       my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
 
1270       $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
 
1271       $sth   = prepare_query($form, $dbh, $query);
 
1273       foreach my $i (1..$form->{number_of_new_bins}) {
 
1274         do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
 
1280   }) or do { die SL::DB->client->error };
 
1282   $main::lxdebug->leave_sub();
 
1286   $main::lxdebug->enter_sub();
 
1288   my ($self, $myconfig, $form) = @_;
 
1290   SL::DB->client->with_transaction(sub {
 
1291     my $dbh = SL::DB->client->dbh;
 
1293     my ($query, @values, $sth);
 
1295     @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
 
1298       $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
 
1299       do_query($form, $dbh, $query, @values);
 
1302     $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
 
1303     $sth   = prepare_query($form, $dbh, $query);
 
1305     foreach my $row (1..$form->{rowcount}) {
 
1306       next if ($form->{"delete_${row}"});
 
1308       do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
 
1313   }) or do { die SL::DB->client->error };
 
1315   $main::lxdebug->leave_sub();
 
1318 sub delete_warehouse {
 
1319   $main::lxdebug->enter_sub();
 
1321   my ($self, $myconfig, $form) = @_;
 
1323   my $rc = SL::DB->client->with_transaction(sub {
 
1324     my $dbh = SL::DB->client->dbh;
 
1326     my $id      = conv_i($form->{id});
 
1327     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|;
 
1328     my ($count) = selectrow_query($form, $dbh, $query, $id);
 
1334     do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
 
1335     do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
 
1340   $main::lxdebug->leave_sub();
 
1345 sub get_all_warehouses {
 
1346   $main::lxdebug->enter_sub();
 
1348   my ($self, $myconfig, $form) = @_;
 
1350   my $dbh = SL::DB->client->dbh;
 
1352   my $query = qq|SELECT w.id, w.description, w.invalid,
 
1353                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
 
1355                  ORDER BY w.sortkey|;
 
1357   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
 
1359   $main::lxdebug->leave_sub();
 
1363   $main::lxdebug->enter_sub();
 
1365   my ($self, $myconfig, $form) = @_;
 
1367   my $dbh = SL::DB->client->dbh;
 
1369   my $id    = conv_i($form->{id});
 
1370   my $query = qq|SELECT w.description, w.invalid
 
1374   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
 
1376   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
1379    SELECT b.*, use.in_use
 
1382        SELECT DISTINCT bin_id, TRUE AS in_use FROM inventory
 
1384        SELECT DISTINCT bin_id, TRUE AS in_use FROM parts
 
1385      ) use ON use.bin_id = b.id
 
1386      WHERE b.warehouse_id = ?;
 
1389   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
1391   $main::lxdebug->leave_sub();
 
1394 sub get_eur_categories {
 
1395   my ($self, $myconfig, $form) = @_;
 
1397   my $dbh = SL::DB->client->dbh;
 
1398   my %eur_categories = selectall_as_map($form, $dbh, "select * from eur_categories order by id", 'id', 'description');
 
1400   return \%eur_categories;
 
1403 sub get_bwa_categories {
 
1404   my ($self, $myconfig, $form) = @_;
 
1406   my $dbh = SL::DB->client->dbh;
 
1407   my %bwa_categories = selectall_as_map($form, $dbh, "select * from bwa_categories order by id", 'id', 'description');
 
1409   return \%bwa_categories;