Verwaltung von Kundenquellen entfernt
[kivitendo-erp.git] / SL / AM.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
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.
21 #
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,
29 # MA 02110-1335, USA.
30 #======================================================================
31 #
32 # Administration module
33 #    Chart of Accounts
34 #    template routines
35 #    preferences
36 #
37 #======================================================================
38
39 package AM;
40
41 use Carp;
42 use Data::Dumper;
43 use Encode;
44 use List::MoreUtils qw(any);
45 use SL::DBUtils;
46 use SL::DB::AuthUser;
47 use SL::DB::Default;
48 use SL::DB::Employee;
49 use SL::DB::Chart;
50 use SL::DB;
51 use SL::GenericTranslations;
52
53 use strict;
54
55 sub get_account {
56   $main::lxdebug->enter_sub();
57
58   # fetch chart-related data and set form fields
59   # get_account is called by add_account in am.pl
60   # always sets $form->{TAXKEY} and default_accounts
61   # loads chart data when $form->{id} is passed
62
63   my ($self, $myconfig, $form) = @_;
64
65   # get default accounts
66   map { $form->{$_} = $::instance_conf->{$_} } qw(inventory_accno_id income_accno_id expense_accno_id);
67
68   require SL::DB::Tax;
69   my $taxes = SL::DB::Manager::Tax->get_all( with_objects => ['chart'] , sort_by => 'taxkey' );
70   $form->{TAXKEY} = [];
71   foreach my $tk ( @{$taxes} ) {
72     push @{ $form->{TAXKEY} },  { id          => $tk->id,
73                                   chart_accno => $tk->chart_id ? $tk->chart->accno : undef,
74                                   taxkey      => $tk->taxkey,
75                                   tax         => $tk->id . '--' . $tk->taxkey,
76                                   rate        => $tk->rate
77                                 };
78   };
79
80   if ($form->{id}) {
81
82     my $chart_obj = SL::DB::Manager::Chart->find_by(id => $form->{id}) || die "Can't open chart";
83
84     my @chart_fields = qw(accno description charttype category link pos_bilanz
85                           pos_eur pos_er new_chart_id valid_from pos_bwa datevautomatik);
86     foreach my $cf ( @chart_fields ) {
87       $form->{"$cf"} = $chart_obj->$cf;
88     }
89
90     my $active_taxkey = $chart_obj->get_active_taxkey;
91     $form->{$_}  = $active_taxkey->$_ foreach qw(taxkey_id pos_ustva tax_id startdate);
92     $form->{tax} = $active_taxkey->tax_id . '--' . $active_taxkey->taxkey_id;
93
94     # check if there are any transactions for this chart
95     $form->{orphaned} = $chart_obj->has_transaction ? 0 : 1;
96
97     # check if new account is active
98     # The old sql query was broken since at least 2006 and always returned 0
99     $form->{new_chart_valid} = $chart_obj->new_chart_valid;
100
101     # get the taxkeys of the account
102     $form->{ACCOUNT_TAXKEYS} = [];
103     foreach my $taxkey ( @{ $chart_obj->taxkeys } ) {
104       push @{ $form->{ACCOUNT_TAXKEYS} }, { id             => $taxkey->id,
105                                             chart_id       => $taxkey->chart_id,
106                                             tax_id         => $taxkey->tax_id,
107                                             taxkey_id      => $taxkey->taxkey_id,
108                                             pos_ustva      => $taxkey->pos_ustva,
109                                             startdate      => $taxkey->startdate->to_kivitendo,
110                                             taxdescription => $taxkey->tax->taxdescription,
111                                             rate           => $taxkey->tax->rate,
112                                             accno          => defined $taxkey->tax->chart_id ? $taxkey->tax->chart->accno : undef,
113                                           };
114     }
115
116     # get new accounts (Folgekonto). Find all charts with the same link
117     $form->{NEWACCOUNT} = $chart_obj->db->dbh->selectall_arrayref('select id, accno,description from chart where link = ? order by accno', {Slice => {}}, $chart_obj->link);
118
119   } else { # set to orphaned for new charts, so chart_type can be changed (needed by $AccountIsPosted)
120     $form->{orphaned} = 1;
121   };
122
123   $main::lxdebug->leave_sub();
124 }
125
126 sub save_account {
127   my ($self, $myconfig, $form) = @_;
128   $main::lxdebug->enter_sub();
129
130   my $rc = SL::DB->client->with_transaction(\&_save_account, $self, $myconfig, $form);
131
132   $::lxdebug->leave_sub;
133   return $rc;
134 }
135
136 sub _save_account {
137   # TODO: it should be forbidden to change an account to a heading if there
138   # have been bookings to this account in the past
139
140   my ($self, $myconfig, $form) = @_;
141
142   my $dbh = SL::DB->client->dbh;
143
144   for (qw(AR_include_in_dropdown AP_include_in_dropdown summary_account)) {
145     $form->{$form->{$_}} = $form->{$_} if $form->{$_};
146   }
147
148   # sanity check, can't have AR with AR_...
149   if ($form->{AR} || $form->{AP} || $form->{IC}) {
150     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)) {
151       $form->error($::locale->text('It is not allowed that a summary account occurs in a drop-down menu!'));
152     }
153   }
154
155   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);
156   $form->{link} = join ':', grep $_, map $form->{$_}, @link_order;
157
158   # strip blanks from accno
159   map { $form->{$_} =~ s/ //g; } qw(accno);
160
161   # collapse multiple (horizontal) whitespace in chart description (Ticket 148)
162   map { $form->{$_} =~ s/\h+/ /g } qw(description);
163
164   my ($query, $sth);
165
166   if ($form->{id} eq "NULL") {
167     $form->{id} = "";
168   }
169
170   $query = '
171     SELECT accno
172     FROM chart
173     WHERE accno = ?';
174
175   my @values = ($form->{accno});
176
177   if ( $form->{id} ) {
178     $query .= ' AND NOT id = ?';
179     push(@values, $form->{id});
180   }
181
182   my ($accno) = selectrow_query($form, $dbh, $query, @values);
183
184   if ($accno) {
185     $form->error($::locale->text('Account number not unique!'));
186   }
187
188
189   if (!$form->{id} || $form->{id} eq "") {
190     $query = qq|SELECT nextval('id')|;
191     ($form->{"id"}) = selectrow_query($form, $dbh, $query);
192     $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
193     do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
194   }
195
196   @values = ();
197
198
199   if ($form->{id}) {
200
201     # if charttype is heading make sure certain values are empty
202     # specifically, if charttype is changed from an existing account, empty the
203     # fields unnecessary for headings, so that e.g. heading doesn't appear in
204     # drop-down menues due to still having a valid "link" entry
205
206     if ( $form->{charttype} eq 'H' ) {
207       $form->{link} = '';
208       $form->{pos_bwa} = '';
209       $form->{pos_bilanz} = '';
210       $form->{pos_eur} = '';
211       $form->{new_chart_id} = '';
212       $form->{valid_from} = '';
213     };
214
215     $query = qq|UPDATE chart SET
216                   accno = ?,
217                   description = ?,
218                   charttype = ?,
219                   category = ?,
220                   link = ?,
221                   pos_bwa   = ?,
222                   pos_bilanz = ?,
223                   pos_eur = ?,
224                   pos_er = ?,
225                   new_chart_id = ?,
226                   valid_from = ?,
227                   datevautomatik = ?
228                 WHERE id = ?|;
229
230     @values = (
231                   $form->{accno},
232                   $form->{description},
233                   $form->{charttype},
234                   $form->{category},
235                   $form->{link},
236                   conv_i($form->{pos_bwa}),
237                   conv_i($form->{pos_bilanz}),
238                   conv_i($form->{pos_eur}),
239                   conv_i($form->{pos_er}),
240                   conv_i($form->{new_chart_id}),
241                   conv_date($form->{valid_from}),
242                   ($form->{datevautomatik} eq 'T') ? 'true':'false',
243                 $form->{id},
244     );
245
246
247   }
248
249   do_query($form, $dbh, $query, @values);
250
251   #Save Taxkeys
252
253   my @taxkeys = ();
254
255   my $MAX_TRIES = 10; # Maximum count of taxkeys in form
256   my $tk_count;
257
258   READTAXKEYS:
259   for $tk_count (0 .. $MAX_TRIES) {
260
261     # Loop control
262
263     # Check if the account already exists, else cancel
264
265     print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
266
267     last READTAXKEYS if ( $form->{'id'} == 0);
268
269     # check if there is a startdate
270     if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
271       $tk_count++;
272       next READTAXKEYS;
273     }
274
275     # Add valid taxkeys into the array
276     push @taxkeys ,
277       {
278         id        => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
279         tax_id    => conv_i($form->{"taxkey_tax_$tk_count"}),
280         startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
281         chart_id  => conv_i($form->{"id"}),
282         pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
283         delete    => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
284       };
285
286     $tk_count++;
287   }
288
289   TAXKEY:
290   for my $j (0 .. $#taxkeys){
291     if ( defined $taxkeys[$j]{'id'} ){
292       # delete Taxkey?
293
294       if ($taxkeys[$j]{'delete'}){
295         $query = qq{
296           DELETE FROM taxkeys WHERE id = ?
297         };
298
299         @values = ($taxkeys[$j]{'id'});
300
301         do_query($form, $dbh, $query, @values);
302
303         next TAXKEY;
304       }
305
306       # UPDATE Taxkey
307
308       $query = qq{
309         UPDATE taxkeys
310         SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
311             chart_id  = ?,
312             tax_id    = ?,
313             pos_ustva = ?,
314             startdate = ?
315         WHERE id = ?
316       };
317       @values = (
318         $taxkeys[$j]{'tax_id'},
319         $taxkeys[$j]{'chart_id'},
320         $taxkeys[$j]{'tax_id'},
321         $taxkeys[$j]{'pos_ustva'},
322         $taxkeys[$j]{'startdate'},
323         $taxkeys[$j]{'id'},
324       );
325       do_query($form, $dbh, $query, @values);
326     }
327     else {
328       # INSERT Taxkey
329
330       $query = qq{
331         INSERT INTO taxkeys (
332           taxkey_id,
333           chart_id,
334           tax_id,
335           pos_ustva,
336           startdate
337         )
338         VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
339       };
340       @values = (
341         $taxkeys[$j]{'tax_id'},
342         $taxkeys[$j]{'chart_id'},
343         $taxkeys[$j]{'tax_id'},
344         $taxkeys[$j]{'pos_ustva'},
345         $taxkeys[$j]{'startdate'},
346       );
347
348       do_query($form, $dbh, $query, @values);
349     }
350
351   }
352
353   # Update chart.taxkey_id to the latest from taxkeys for this chart.
354   $query = <<SQL;
355     UPDATE chart
356     SET taxkey_id = (
357       SELECT taxkey_id
358       FROM taxkeys
359       WHERE taxkeys.chart_id = chart.id
360       ORDER BY startdate DESC
361       LIMIT 1
362     )
363     WHERE id = ?
364 SQL
365
366   do_query($form, $dbh, $query, $form->{id});
367
368   return 1;
369 }
370
371 sub delete_account {
372   my ($self, $myconfig, $form) = @_;
373   $main::lxdebug->enter_sub();
374
375   my $rc = SL::DB->client->with_transaction(\&_delete_account, $self, $myconfig, $form);
376
377   $::lxdebug->leave_sub;
378   return $rc;
379 }
380
381 sub _delete_account {
382   my ($self, $myconfig, $form) = @_;
383
384   my $dbh = SL::DB->client->dbh;
385
386   my $query = qq|SELECT count(*) FROM acc_trans a
387                  WHERE a.chart_id = ?|;
388   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
389
390   if ($count) {
391     return;
392   }
393
394   $query = qq|DELETE FROM tax
395               WHERE chart_id = ?|;
396   do_query($form, $dbh, $query, $form->{id});
397
398   # delete account taxkeys
399   $query = qq|DELETE FROM taxkeys
400               WHERE chart_id = ?|;
401   do_query($form, $dbh, $query, $form->{id});
402
403   # delete chart of account record
404   # last step delete chart, because we have a constraint
405   # to taxkeys
406   $query = qq|DELETE FROM chart
407               WHERE id = ?|;
408   do_query($form, $dbh, $query, $form->{id});
409
410   return 1;
411 }
412
413 sub language {
414   $main::lxdebug->enter_sub();
415
416   my ($self, $myconfig, $form, $return_list) = @_;
417
418   my $dbh = SL::DB->client->dbh;
419
420   my $query =
421     "SELECT id, description, template_code, article_code, " .
422     "  output_numberformat, output_dateformat, output_longdates " .
423     "FROM language ORDER BY description";
424
425   my $sth = $dbh->prepare($query);
426   $sth->execute || $form->dberror($query);
427
428   my $ary = [];
429
430   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
431     push(@{ $ary }, $ref);
432   }
433
434   $sth->finish;
435
436   $main::lxdebug->leave_sub();
437
438   if ($return_list) {
439     return @{$ary};
440   } else {
441     $form->{ALL} = $ary;
442   }
443 }
444
445 sub get_language {
446   $main::lxdebug->enter_sub();
447
448   my ($self, $myconfig, $form) = @_;
449
450   my $dbh = SL::DB->client->dbh;
451
452   my $query =
453     "SELECT description, template_code, article_code, " .
454     "  output_numberformat, output_dateformat, output_longdates " .
455     "FROM language WHERE id = ?";
456   my $sth = $dbh->prepare($query);
457   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
458
459   my $ref = $sth->fetchrow_hashref("NAME_lc");
460
461   map { $form->{$_} = $ref->{$_} } keys %$ref;
462
463   $sth->finish;
464
465   $main::lxdebug->leave_sub();
466 }
467
468 sub get_language_details {
469   $main::lxdebug->enter_sub();
470
471   my ($self, $myconfig, $form, $id) = @_;
472
473   my $dbh = SL::DB->client->dbh;
474
475   my $query =
476     "SELECT template_code, " .
477     "  output_numberformat, output_dateformat, output_longdates " .
478     "FROM language WHERE id = ?";
479   my @res = selectrow_query($form, $dbh, $query, $id);
480
481   $main::lxdebug->leave_sub();
482
483   return @res;
484 }
485
486 sub save_language {
487   $main::lxdebug->enter_sub();
488
489   my ($self, $myconfig, $form) = @_;
490
491   SL::DB->client->with_transaction(sub {
492     my $dbh = SL::DB->client->dbh;
493     my (@values, $query);
494
495     map({ push(@values, $form->{$_}); }
496         qw(description template_code article_code
497            output_numberformat output_dateformat output_longdates));
498
499     # id is the old record
500     if ($form->{id}) {
501       $query =
502         "UPDATE language SET " .
503         "  description = ?, template_code = ?, article_code = ?, " .
504         "  output_numberformat = ?, output_dateformat = ?, " .
505         "  output_longdates = ? " .
506         "WHERE id = ?";
507       push(@values, $form->{id});
508     } else {
509       $query =
510         "INSERT INTO language (" .
511         "  description, template_code, article_code, " .
512         "  output_numberformat, output_dateformat, output_longdates" .
513         ") VALUES (?, ?, ?, ?, ?, ?)";
514     }
515     do_query($form, $dbh, $query, @values);
516     1;
517   }) or do { die SL::DB->client->error };
518
519   $main::lxdebug->leave_sub();
520 }
521
522 sub delete_language {
523   $main::lxdebug->enter_sub();
524
525   my ($self, $myconfig, $form) = @_;
526   my $query;
527
528   SL::DB->client->with_transaction(sub {
529     my $dbh = SL::DB->client->dbh;
530
531     foreach my $table (qw(generic_translations units_language)) {
532       $query = qq|DELETE FROM $table WHERE language_id = ?|;
533       do_query($form, $dbh, $query, $form->{"id"});
534     }
535
536     $query = "DELETE FROM language WHERE id = ?";
537     do_query($form, $dbh, $query, $form->{"id"});
538     1;
539   }) or do { die SL::DB->client->error };
540
541   $main::lxdebug->leave_sub();
542 }
543
544 sub prepare_template_filename {
545   $main::lxdebug->enter_sub();
546
547   my ($self, $myconfig, $form) = @_;
548
549   my ($filename, $display_filename);
550
551   if ($form->{type} eq "stylesheet") {
552     $filename = "css/$myconfig->{stylesheet}";
553     $display_filename = $myconfig->{stylesheet};
554
555   } else {
556     $filename = $form->{formname};
557
558     if ($form->{language}) {
559       my ($id, $template_code) = split(/--/, $form->{language});
560       $filename .= "_${template_code}";
561     }
562
563     if ($form->{printer}) {
564       my ($id, $template_code) = split(/--/, $form->{printer});
565       $filename .= "_${template_code}";
566     }
567
568     $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
569     if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
570       $filename =~ s|.*/||;
571     }
572     $display_filename = $filename;
573     $filename = SL::DB::Default->get->templates . "/$filename";
574   }
575
576   $main::lxdebug->leave_sub();
577
578   return ($filename, $display_filename);
579 }
580
581
582 sub load_template {
583   $main::lxdebug->enter_sub();
584
585   my ($self, $filename) = @_;
586
587   my ($content, $lines) = ("", 0);
588
589   local *TEMPLATE;
590
591   if (open(TEMPLATE, $filename)) {
592     while (<TEMPLATE>) {
593       $content .= $_;
594       $lines++;
595     }
596     close(TEMPLATE);
597   }
598
599   $content = Encode::decode('utf-8-strict', $content);
600
601   $main::lxdebug->leave_sub();
602
603   return ($content, $lines);
604 }
605
606 sub save_template {
607   $main::lxdebug->enter_sub();
608
609   my ($self, $filename, $content) = @_;
610
611   local *TEMPLATE;
612
613   my $error = "";
614
615   if (open(TEMPLATE, ">", $filename)) {
616     $content = Encode::encode('utf-8-strict', $content);
617     $content =~ s/\r\n/\n/g;
618     print(TEMPLATE $content);
619     close(TEMPLATE);
620   } else {
621     $error = $!;
622   }
623
624   $main::lxdebug->leave_sub();
625
626   return $error;
627 }
628
629 sub save_preferences {
630   $main::lxdebug->enter_sub();
631
632   my ($self, $form) = @_;
633
634   my $employee = SL::DB::Manager::Employee->find_by(login => $::myconfig{login});
635   $employee->update_attributes(name => $form->{name});
636
637   my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
638   $user->update_attributes(
639     config_values => {
640       %{ $user->config_values },
641       map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
642     });
643
644   $main::lxdebug->leave_sub();
645
646   return 1;
647 }
648
649 sub get_defaults {
650   $main::lxdebug->enter_sub();
651
652   my $self     = shift;
653   my %params   = @_;
654
655   my $myconfig = \%main::myconfig;
656   my $form     = $main::form;
657
658   my $dbh      = $params{dbh} || SL::DB->client->dbh;
659
660   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
661
662   $defaults->{weightunit} ||= 'kg';
663
664   $main::lxdebug->leave_sub();
665
666   return $defaults;
667 }
668
669 sub closedto {
670   $main::lxdebug->enter_sub();
671
672   my ($self, $myconfig, $form) = @_;
673
674   my $dbh = SL::DB->client->dbh;
675
676   my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
677   my $sth   = $dbh->prepare($query);
678   $sth->execute || $form->dberror($query);
679
680   ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
681
682   $sth->finish;
683
684   $main::lxdebug->leave_sub();
685 }
686
687 sub closebooks {
688   $main::lxdebug->enter_sub();
689
690   my ($self, $myconfig, $form) = @_;
691
692   SL::DB->client->with_transaction(sub {
693     my $dbh = SL::DB->client->dbh;
694
695     my ($query, @values);
696
697     # is currently NEVER trueish (no more hidden revtrans in $form)
698     # if ($form->{revtrans}) {
699     #   $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
700     # -> therefore you can only set this to false (which is already the default)
701     # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
702
703       $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
704       @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
705
706     # set close in defaults
707     do_query($form, $dbh, $query, @values);
708     1;
709   }) or do { die SL::DB->client->error };
710
711   $main::lxdebug->leave_sub();
712 }
713
714 sub get_base_unit {
715   my ($self, $units, $unit_name, $factor) = @_;
716
717   $factor = 1 unless ($factor);
718
719   my $unit = $units->{$unit_name};
720
721   if (!defined($unit) || !$unit->{"base_unit"} ||
722       ($unit_name eq $unit->{"base_unit"})) {
723     return ($unit_name, $factor);
724   }
725
726   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
727 }
728
729 sub retrieve_units {
730   $main::lxdebug->enter_sub();
731
732   my ($self, $myconfig, $form, $prefix) = @_;
733   $prefix ||= '';
734
735   my $dbh = SL::DB->client->dbh;
736
737   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
738
739   my $sth = prepare_execute_query($form, $dbh, $query);
740
741   my $units = {};
742   while (my $ref = $sth->fetchrow_hashref()) {
743     $units->{$ref->{"name"}} = $ref;
744   }
745   $sth->finish();
746
747   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
748   $sth = $dbh->prepare($query_lang);
749   $sth->execute() || $form->dberror($query_lang);
750   my @languages;
751   while (my $ref = $sth->fetchrow_hashref()) {
752     push(@languages, $ref);
753   }
754   $sth->finish();
755
756   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
757     "FROM units_language ul " .
758     "LEFT JOIN language l ON ul.language_id = l.id " .
759     "WHERE ul.unit = ?";
760   $sth = $dbh->prepare($query_lang);
761
762   foreach my $unit (values(%{$units})) {
763     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
764
765     $unit->{"LANGUAGES"} = {};
766     foreach my $lang (@languages) {
767       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
768     }
769
770     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
771     while (my $ref = $sth->fetchrow_hashref()) {
772       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
773     }
774   }
775   $sth->finish;
776
777   $main::lxdebug->leave_sub();
778
779   return $units;
780 }
781
782 sub retrieve_all_units {
783   $main::lxdebug->enter_sub();
784
785   my $self = shift;
786
787   if (!$::request->{cache}{all_units}) {
788     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
789   }
790
791   $main::lxdebug->leave_sub();
792
793   return $::request->{cache}{all_units};
794 }
795
796
797 sub translate_units {
798   $main::lxdebug->enter_sub();
799
800   my ($self, $form, $template_code, $unit, $amount) = @_;
801
802   my $units = $self->retrieve_units(\%main::myconfig, $form);
803
804   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
805   my $new_unit = $unit;
806   if ($h) {
807     if (($amount != 1) && $h->{"localized_plural"}) {
808       $new_unit = $h->{"localized_plural"};
809     } elsif ($h->{"localized"}) {
810       $new_unit = $h->{"localized"};
811     }
812   }
813
814   $main::lxdebug->leave_sub();
815
816   return $new_unit;
817 }
818
819 sub units_in_use {
820   $main::lxdebug->enter_sub();
821
822   my ($self, $myconfig, $form, $units) = @_;
823
824   my $dbh = SL::DB->client->dbh;
825
826   map({ $_->{"in_use"} = 0; } values(%{$units}));
827
828   foreach my $unit (values(%{$units})) {
829     my $base_unit = $unit->{"original_base_unit"};
830     while ($base_unit) {
831       $units->{$base_unit}->{"in_use"} = 1;
832       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
833       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
834       $base_unit = $units->{$base_unit}->{"original_base_unit"};
835     }
836   }
837
838   foreach my $unit (values(%{$units})) {
839     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
840
841     foreach my $table (qw(parts invoice orderitems)) {
842       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
843
844       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
845         $query .= "= " . $dbh->quote($unit->{"name"});
846       } else {
847         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
848           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
849       }
850
851       my ($count) = $dbh->selectrow_array($query);
852       $form->dberror($query) if ($dbh->err);
853
854       if ($count) {
855         $unit->{"in_use"} = 1;
856         last;
857       }
858     }
859   }
860
861   $main::lxdebug->leave_sub();
862 }
863
864 sub convertible_units {
865   $main::lxdebug->enter_sub();
866
867   my $self        = shift;
868   my $units       = shift;
869   my $filter_unit = shift;
870   my $not_smaller = shift;
871
872   my $conv_units = [];
873
874   $filter_unit = $units->{$filter_unit};
875
876   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
877     my $unit = $units->{$name};
878
879     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
880         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
881       push @{$conv_units}, $unit;
882     }
883   }
884
885   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
886
887   $main::lxdebug->leave_sub();
888
889   return \@sorted;
890 }
891
892 # if $a is translatable to $b, return the factor between them.
893 # else return 1
894 sub convert_unit {
895   $main::lxdebug->enter_sub(2);
896   my ($this, $a, $b, $all_units) = @_;
897
898   if (!$all_units) {
899     $all_units = $this->retrieve_all_units;
900   }
901
902   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
903   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
904   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
905   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
906 }
907
908 sub unit_select_data {
909   $main::lxdebug->enter_sub();
910
911   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
912
913   my $select = [];
914
915   if ($empty_entry) {
916     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
917   }
918
919   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
920     if (!$convertible_into ||
921         ($units->{$convertible_into} &&
922          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
923       push @{$select}, { "name"      => $unit,
924                          "base_unit" => $units->{$unit}->{"base_unit"},
925                          "factor"    => $units->{$unit}->{"factor"},
926                          "selected"  => ($unit eq $selected) ? "selected" : "" };
927     }
928   }
929
930   $main::lxdebug->leave_sub();
931
932   return $select;
933 }
934
935 sub unit_select_html {
936   $main::lxdebug->enter_sub();
937
938   my ($self, $units, $name, $selected, $convertible_into) = @_;
939
940   my $select = "<select name=${name}>";
941
942   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
943     if (!$convertible_into ||
944         ($units->{$convertible_into} &&
945          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
946       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
947     }
948   }
949   $select .= "</select>";
950
951   $main::lxdebug->leave_sub();
952
953   return $select;
954 }
955
956 sub sum_with_unit {
957   $main::lxdebug->enter_sub();
958
959   my $self  = shift;
960
961   my $units = $self->retrieve_all_units();
962
963   my $sum   = 0;
964   my $base_unit;
965
966   while (2 <= scalar(@_)) {
967     my $qty  = shift(@_);
968     my $unit = $units->{shift(@_)};
969
970     croak "No unit defined with name $unit" if (!defined $unit);
971
972     if (!$base_unit) {
973       $base_unit = $unit->{base_unit};
974     } elsif ($base_unit ne $unit->{base_unit}) {
975       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
976     }
977
978     $sum += $qty * $unit->{factor};
979   }
980
981   $main::lxdebug->leave_sub();
982
983   return $sum;
984 }
985
986 sub add_unit {
987   $main::lxdebug->enter_sub();
988
989   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
990
991   SL::DB->client->with_transaction(sub {
992     my $dbh = SL::DB->client->dbh;
993
994     my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
995     my ($sortkey) = selectrow_query($form, $dbh, $query);
996
997     $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
998       "VALUES (?, ?, ?, ?)";
999     do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1000
1001     if ($languages) {
1002       $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1003       my $sth = $dbh->prepare($query);
1004       foreach my $lang (@{$languages}) {
1005         my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1006         $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1007       }
1008       $sth->finish();
1009     }
1010     1;
1011   }) or do { die SL::DB->client->error };
1012
1013   $main::lxdebug->leave_sub();
1014 }
1015
1016 sub save_units {
1017   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1018   $main::lxdebug->enter_sub();
1019
1020   my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
1021
1022   $::lxdebug->leave_sub;
1023   return $rc;
1024 }
1025
1026 sub _save_units {
1027   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1028
1029   my $dbh = SL::DB->client->dbh;
1030
1031   my ($base_unit, $unit, $sth, $query);
1032
1033   $query = "DELETE FROM units_language";
1034   $dbh->do($query) || $form->dberror($query);
1035
1036   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1037     $query = "DELETE FROM units WHERE name IN (";
1038     map({ $query .= "?," } @{$delete_units});
1039     substr($query, -1, 1) = ")";
1040     $dbh->do($query, undef, @{$delete_units}) ||
1041       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1042   }
1043
1044   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1045   $sth = $dbh->prepare($query);
1046
1047   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1048   my $sth_lang = $dbh->prepare($query_lang);
1049
1050   foreach $unit (values(%{$units})) {
1051     $unit->{"depth"} = 0;
1052     my $base_unit = $unit;
1053     while ($base_unit->{"base_unit"}) {
1054       $unit->{"depth"}++;
1055       $base_unit = $units->{$base_unit->{"base_unit"}};
1056     }
1057   }
1058
1059   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1060     if ($unit->{"LANGUAGES"}) {
1061       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1062         next unless ($lang->{"id"} && $lang->{"localized"});
1063         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1064         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1065       }
1066     }
1067
1068     next if ($unit->{"unchanged_unit"});
1069
1070     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1071     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1072   }
1073
1074   $sth->finish();
1075   $sth_lang->finish();
1076
1077   return 1;
1078 }
1079
1080 sub taxes {
1081   $main::lxdebug->enter_sub();
1082
1083   my ($self, $myconfig, $form) = @_;
1084
1085   my $dbh = SL::DB->client->dbh;
1086
1087   my $query = qq|SELECT
1088                    t.id,
1089                    t.taxkey,
1090                    t.taxdescription,
1091                    round(t.rate * 100, 2) AS rate,
1092                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1093                    (SELECT description FROM chart WHERE id = chart_id) AS account_description,
1094                    (SELECT accno FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_accno,
1095                    (SELECT description FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_description,
1096                    (SELECT accno FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_accno,
1097                    (SELECT description FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_description
1098                  FROM tax t
1099                  ORDER BY taxkey, rate|;
1100
1101   my $sth = $dbh->prepare($query);
1102   $sth->execute || $form->dberror($query);
1103
1104   $form->{TAX} = [];
1105   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1106     push @{ $form->{TAX} }, $ref;
1107   }
1108
1109   $sth->finish;
1110
1111   $main::lxdebug->leave_sub();
1112 }
1113
1114 sub get_tax_accounts {
1115   $main::lxdebug->enter_sub();
1116
1117   my ($self, $myconfig, $form) = @_;
1118
1119   my $dbh = SL::DB->client->dbh;
1120
1121   # get Accounts from chart
1122   my $query = qq{ SELECT
1123                  id,
1124                  accno || ' - ' || description AS taxaccount
1125                FROM chart
1126                WHERE link LIKE '%_tax%'
1127                ORDER BY accno
1128              };
1129
1130   my $sth = $dbh->prepare($query);
1131   $sth->execute || $form->dberror($query);
1132
1133   $form->{ACCOUNTS} = [];
1134   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1135     push @{ $form->{ACCOUNTS} }, $ref;
1136   }
1137
1138   $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
1139   $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
1140
1141   $form->{skontochart_value_title_sub} = sub {
1142     my $item = shift;
1143     return [
1144       $item->{id},
1145       $item->{accno} .' '. $item->{description},
1146     ];
1147   };
1148
1149   $sth->finish;
1150
1151   $main::lxdebug->leave_sub();
1152 }
1153
1154 sub get_tax {
1155   $main::lxdebug->enter_sub();
1156
1157   my ($self, $myconfig, $form) = @_;
1158
1159   my $dbh = SL::DB->client->dbh;
1160
1161   my $query = qq|SELECT
1162                    taxkey,
1163                    taxdescription,
1164                    round(rate * 100, 2) AS rate,
1165                    chart_id,
1166                    chart_categories,
1167                    (id IN (SELECT tax_id
1168                            FROM acc_trans)) AS tax_already_used,
1169                    skonto_sales_chart_id,
1170                    skonto_purchase_chart_id
1171                  FROM tax
1172                  WHERE id = ? |;
1173
1174   my $sth = $dbh->prepare($query);
1175   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1176
1177   my $ref = $sth->fetchrow_hashref("NAME_lc");
1178
1179   map { $form->{$_} = $ref->{$_} } keys %$ref;
1180
1181   $sth->finish;
1182
1183   # see if it is used by a taxkey
1184   $query = qq|SELECT count(*) FROM taxkeys
1185               WHERE tax_id = ? AND chart_id >0|;
1186
1187   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1188
1189   $form->{orphaned} = !$form->{orphaned};
1190   $sth->finish;
1191
1192   if (!$form->{orphaned} ) {
1193     $query = qq|SELECT DISTINCT c.id, c.accno
1194                 FROM taxkeys tk
1195                 JOIN   tax t ON (t.id = tk.tax_id)
1196                 JOIN chart c ON (c.id = tk.chart_id)
1197                 WHERE tk.tax_id = ?|;
1198
1199     $sth = $dbh->prepare($query);
1200     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1201
1202     $form->{TAXINUSE} = [];
1203     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1204       push @{ $form->{TAXINUSE} }, $ref;
1205     }
1206
1207     $sth->finish;
1208   }
1209
1210   $main::lxdebug->leave_sub();
1211 }
1212
1213 sub save_tax {
1214   my ($self, $myconfig, $form) = @_;
1215   $main::lxdebug->enter_sub();
1216
1217   my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
1218
1219   $::lxdebug->leave_sub;
1220   return $rc;
1221 }
1222
1223 sub _save_tax {
1224   my ($self, $myconfig, $form) = @_;
1225   my $query;
1226
1227   my $dbh = SL::DB->client->dbh;
1228
1229   $form->{rate} = $form->{rate} / 100;
1230
1231   my $chart_categories = '';
1232   $chart_categories .= 'A' if $form->{asset};
1233   $chart_categories .= 'L' if $form->{liability};
1234   $chart_categories .= 'Q' if $form->{equity};
1235   $chart_categories .= 'I' if $form->{revenue};
1236   $chart_categories .= 'E' if $form->{expense};
1237   $chart_categories .= 'C' if $form->{costs};
1238
1239   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);
1240   if ($form->{id} ne "") {
1241     $query = qq|UPDATE tax SET
1242                   taxkey                   = ?,
1243                   taxdescription           = ?,
1244                   rate                     = ?,
1245                   chart_id                 = ?,
1246                   taxnumber                = (SELECT accno FROM chart WHERE id = ? ),
1247                   skonto_sales_chart_id    = ?,
1248                   skonto_purchase_chart_id = ?,
1249                   chart_categories         = ?
1250                 WHERE id = ?|;
1251
1252   } else {
1253     #ok
1254     ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
1255     $query = qq|INSERT INTO tax (
1256                   taxkey,
1257                   taxdescription,
1258                   rate,
1259                   chart_id,
1260                   taxnumber,
1261                   skonto_sales_chart_id,
1262                   skonto_purchase_chart_id,
1263                   chart_categories,
1264                   id
1265                 )
1266                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?), ?, ?,  ?, ?)|;
1267   }
1268   push(@values, $form->{id});
1269   do_query($form, $dbh, $query, @values);
1270
1271   foreach my $language_id (keys %{ $form->{translations} }) {
1272     GenericTranslations->save('dbh'              => $dbh,
1273                               'translation_type' => 'SL::DB::Tax/taxdescription',
1274                               'translation_id'   => $form->{id},
1275                               'language_id'      => $language_id,
1276                               'translation'      => $form->{translations}->{$language_id});
1277   }
1278 }
1279
1280 sub delete_tax {
1281   $main::lxdebug->enter_sub();
1282
1283   my ($self, $myconfig, $form) = @_;
1284   my $query;
1285
1286   SL::DB->client->with_transaction(sub {
1287     $query = qq|DELETE FROM tax WHERE id = ?|;
1288     do_query($form, SL::DB->client->dbh, $query, $form->{id});
1289     1;
1290   }) or do { die SL::DB->client->error };
1291
1292   $main::lxdebug->leave_sub();
1293 }
1294
1295 sub save_price_factor {
1296   $main::lxdebug->enter_sub();
1297
1298   my ($self, $myconfig, $form) = @_;
1299
1300   SL::DB->client->with_transaction(sub {
1301     my $dbh = SL::DB->client->dbh;
1302
1303     my $query;
1304     my @values = ($form->{description}, conv_i($form->{factor}));
1305
1306     if ($form->{id}) {
1307       $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1308       push @values, conv_i($form->{id});
1309
1310     } else {
1311       $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1312     }
1313
1314     do_query($form, $dbh, $query, @values);
1315     1;
1316   }) or do { die SL::DB->client->error };
1317
1318   $main::lxdebug->leave_sub();
1319 }
1320
1321 sub get_all_price_factors {
1322   $main::lxdebug->enter_sub();
1323
1324   my ($self, $myconfig, $form) = @_;
1325
1326   my $dbh = SL::DB->client->dbh;
1327
1328   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1329
1330   $main::lxdebug->leave_sub();
1331 }
1332
1333 sub get_price_factor {
1334   $main::lxdebug->enter_sub();
1335
1336   my ($self, $myconfig, $form) = @_;
1337
1338   # connect to database
1339   my $dbh = SL::DB->client->dbh;
1340
1341   my $query = qq|SELECT description, factor,
1342                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
1343                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
1344                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1345                  FROM price_factors WHERE id = ?|;
1346
1347   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1348
1349   $main::lxdebug->leave_sub();
1350 }
1351
1352 sub delete_price_factor {
1353   $main::lxdebug->enter_sub();
1354
1355   my ($self, $myconfig, $form) = @_;
1356
1357   SL::DB->client->with_transaction(sub {
1358     do_query($form, SL::DB->client->dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1359     1;
1360   }) or do { die SL::DB->client->error };
1361
1362   $main::lxdebug->leave_sub();
1363 }
1364
1365 sub save_warehouse {
1366   $main::lxdebug->enter_sub();
1367
1368   my ($self, $myconfig, $form) = @_;
1369
1370   SL::DB->client->with_transaction(sub {
1371     my $dbh = SL::DB->client->dbh;
1372
1373     my ($query, @values, $sth);
1374
1375     if (!$form->{id}) {
1376       $query        = qq|SELECT nextval('id')|;
1377       ($form->{id}) = selectrow_query($form, $dbh, $query);
1378
1379       $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1380       do_query($form, $dbh, $query, $form->{id});
1381     }
1382
1383     do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1384              $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1385
1386     if (0 < $form->{number_of_new_bins}) {
1387       my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
1388       $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1389       $sth   = prepare_query($form, $dbh, $query);
1390
1391       foreach my $i (1..$form->{number_of_new_bins}) {
1392         do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
1393       }
1394
1395       $sth->finish();
1396     }
1397     1;
1398   }) or do { die SL::DB->client->error };
1399
1400   $main::lxdebug->leave_sub();
1401 }
1402
1403 sub save_bins {
1404   $main::lxdebug->enter_sub();
1405
1406   my ($self, $myconfig, $form) = @_;
1407
1408   SL::DB->client->with_transaction(sub {
1409     my $dbh = SL::DB->client->dbh;
1410
1411     my ($query, @values, $sth);
1412
1413     @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1414
1415     if (@values) {
1416       $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1417       do_query($form, $dbh, $query, @values);
1418     }
1419
1420     $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1421     $sth   = prepare_query($form, $dbh, $query);
1422
1423     foreach my $row (1..$form->{rowcount}) {
1424       next if ($form->{"delete_${row}"});
1425
1426       do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1427     }
1428
1429     $sth->finish();
1430     1;
1431   }) or do { die SL::DB->client->error };
1432
1433   $main::lxdebug->leave_sub();
1434 }
1435
1436 sub delete_warehouse {
1437   $main::lxdebug->enter_sub();
1438
1439   my ($self, $myconfig, $form) = @_;
1440
1441   my $rc = SL::DB->client->with_transaction(sub {
1442     my $dbh = SL::DB->client->dbh;
1443
1444     my $id      = conv_i($form->{id});
1445     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|;
1446     my ($count) = selectrow_query($form, $dbh, $query, $id);
1447
1448     if ($count) {
1449       return 0;
1450     }
1451
1452     do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
1453     do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
1454
1455     return 1;
1456   });
1457
1458   $main::lxdebug->leave_sub();
1459
1460   return $rc;
1461 }
1462
1463 sub get_all_warehouses {
1464   $main::lxdebug->enter_sub();
1465
1466   my ($self, $myconfig, $form) = @_;
1467
1468   my $dbh = SL::DB->client->dbh;
1469
1470   my $query = qq|SELECT w.id, w.description, w.invalid,
1471                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
1472                  FROM warehouse w
1473                  ORDER BY w.sortkey|;
1474
1475   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
1476
1477   $main::lxdebug->leave_sub();
1478 }
1479
1480 sub get_warehouse {
1481   $main::lxdebug->enter_sub();
1482
1483   my ($self, $myconfig, $form) = @_;
1484
1485   my $dbh = SL::DB->client->dbh;
1486
1487   my $id    = conv_i($form->{id});
1488   my $query = qq|SELECT w.description, w.invalid
1489                  FROM warehouse w
1490                  WHERE w.id = ?|;
1491
1492   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
1493
1494   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1495
1496   $query = <<SQL;
1497     SELECT b.*,
1498       (   EXISTS(SELECT i.bin_id FROM inventory i WHERE i.bin_id = b.id LIMIT 1)
1499        OR EXISTS(SELECT p.bin_id FROM parts     p WHERE p.bin_id = b.id LIMIT 1))
1500       AS in_use
1501     FROM bin b
1502     WHERE b.warehouse_id = ?
1503 SQL
1504
1505   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1506
1507   $main::lxdebug->leave_sub();
1508 }
1509
1510 1;