Merge branch 'erzeugnisnummern'
[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., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Administration module
32 #    Chart of Accounts
33 #    template routines
34 #    preferences
35 #
36 #======================================================================
37
38 package AM;
39
40 use Carp;
41 use Data::Dumper;
42 use Encode;
43 use SL::DBUtils;
44
45 use strict;
46
47 sub get_account {
48   $main::lxdebug->enter_sub();
49
50   my ($self, $myconfig, $form) = @_;
51
52   # connect to database
53   my $dbh = $form->dbconnect($myconfig);
54   my $query = qq{
55     SELECT c.accno, c.description, c.charttype, c.category,
56       c.link, c.pos_bilanz, c.pos_eur, c.new_chart_id, c.valid_from,
57       c.pos_bwa, datevautomatik,
58       tk.taxkey_id, tk.pos_ustva, tk.tax_id,
59       tk.tax_id || '--' || tk.taxkey_id AS tax, tk.startdate
60     FROM chart c
61     LEFT JOIN taxkeys tk
62     ON (c.id=tk.chart_id AND tk.id =
63       (SELECT id FROM taxkeys
64        WHERE taxkeys.chart_id = c.id AND startdate <= current_date
65        ORDER BY startdate DESC LIMIT 1))
66     WHERE c.id = ?
67     };
68
69
70   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
71   my $sth = $dbh->prepare($query);
72   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
73
74   my $ref = $sth->fetchrow_hashref("NAME_lc");
75
76   foreach my $key (keys %$ref) {
77     $form->{"$key"} = $ref->{"$key"};
78   }
79
80   $sth->finish;
81
82   # get default accounts
83   $query = qq|SELECT inventory_accno_id, income_accno_id, expense_accno_id
84               FROM defaults|;
85   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
86   $sth = $dbh->prepare($query);
87   $sth->execute || $form->dberror($query);
88
89   $ref = $sth->fetchrow_hashref("NAME_lc");
90
91   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
92
93   $sth->finish;
94
95
96
97   # get taxkeys and description
98   $query = qq{
99     SELECT
100       id,
101       (SELECT accno FROM chart WHERE id=tax.chart_id) AS chart_accno,
102       taxkey,
103       id||'--'||taxkey AS tax,
104       taxdescription,
105       rate
106     FROM tax ORDER BY taxkey
107   };
108   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
109   $sth = $dbh->prepare($query);
110   $sth->execute || $form->dberror($query);
111
112   $form->{TAXKEY} = [];
113
114   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
115     push @{ $form->{TAXKEY} }, $ref;
116   }
117
118   $sth->finish;
119   if ($form->{id}) {
120     # get new accounts
121     $query = qq|SELECT id, accno,description
122                 FROM chart
123                 WHERE link = ?
124                 ORDER BY accno|;
125     $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
126     $sth = $dbh->prepare($query);
127     $sth->execute($form->{link}) || $form->dberror($query . " ($form->{link})");
128
129     $form->{NEWACCOUNT} = [];
130     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
131       push @{ $form->{NEWACCOUNT} }, $ref;
132     }
133
134     $sth->finish;
135
136     # get the taxkeys of account
137
138     $query = qq{
139       SELECT
140         tk.id,
141         tk.chart_id,
142         c.accno,
143         tk.tax_id,
144         t.taxdescription,
145         t.rate,
146         tk.taxkey_id,
147         tk.pos_ustva,
148         tk.startdate
149       FROM taxkeys tk
150       LEFT JOIN   tax t ON (t.id = tk.tax_id)
151       LEFT JOIN chart c ON (c.id = t.chart_id)
152
153       WHERE tk.chart_id = ?
154       ORDER BY startdate DESC
155     };
156     $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
157     $sth = $dbh->prepare($query);
158
159     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
160
161     $form->{ACCOUNT_TAXKEYS} = [];
162
163     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
164       push @{ $form->{ACCOUNT_TAXKEYS} }, $ref;
165     }
166
167     $sth->finish;
168
169   }
170   # check if we have any transactions
171   $query = qq|SELECT a.trans_id FROM acc_trans a
172               WHERE a.chart_id = ?|;
173   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
174   $sth = $dbh->prepare($query);
175   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
176
177   ($form->{orphaned}) = $sth->fetchrow_array;
178   $form->{orphaned} = !$form->{orphaned};
179   $sth->finish;
180
181   # check if new account is active
182   $form->{new_chart_valid} = 0;
183   if ($form->{new_chart_id}) {
184     $query = qq|SELECT current_date-valid_from FROM chart
185                 WHERE id = ?|;
186     $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
187     my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
188     if ($count >=0) {
189       $form->{new_chart_valid} = 1;
190     }
191     $sth->finish;
192   }
193
194   $dbh->disconnect;
195
196   $main::lxdebug->leave_sub();
197 }
198
199 sub save_account {
200   $main::lxdebug->enter_sub();
201
202   # TODO: it should be forbidden to change an account to a heading if there
203   # have been bookings to this account in the past
204
205   my ($self, $myconfig, $form) = @_;
206
207   # connect to database, turn off AutoCommit
208   my $dbh = $form->dbconnect_noauto($myconfig);
209
210   # sanity check, can't have AR with AR_...
211   if ($form->{AR} || $form->{AP} || $form->{IC}) {
212     map { delete $form->{$_} }
213       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);
214   }
215
216   for (qw(AR_include_in_dropdown AP_include_in_dropdown)) {
217     $form->{$form->{$_}} = $form->{$_} if $form->{$_};
218   }
219
220   $form->{link} = "";
221   foreach my $item ($form->{AR},            $form->{AR_amount},
222                     $form->{AR_tax},        $form->{AR_paid},
223                     $form->{AP},            $form->{AP_amount},
224                     $form->{AP_tax},        $form->{AP_paid},
225                     $form->{IC},            $form->{IC_sale},
226                     $form->{IC_cogs},       $form->{IC_taxpart},
227                     $form->{IC_income},     $form->{IC_expense},
228                     $form->{IC_taxservice}
229     ) {
230     $form->{link} .= "${item}:" if ($item);
231   }
232   chop $form->{link};
233
234   # strip blanks from accno
235   map { $form->{$_} =~ s/ //g; } qw(accno);
236
237   my ($query, $sth);
238
239   if ($form->{id} eq "NULL") {
240     $form->{id} = "";
241   }
242
243   $query = '
244     SELECT accno
245     FROM chart
246     WHERE accno = ?';
247
248   my @values = ($form->{accno});
249
250   if ( $form->{id} ) {
251     $query .= ' AND NOT id = ?';
252     push(@values, $form->{id});
253   }
254
255   my ($accno) = selectrow_query($form, $dbh, $query, @values);
256
257   if ($accno) {
258     $form->error($::locale->text('Account number not unique!'));
259   }
260
261
262   if (!$form->{id} || $form->{id} eq "") {
263     $query = qq|SELECT nextval('id')|;
264     ($form->{"id"}) = selectrow_query($form, $dbh, $query);
265     $query = qq|INSERT INTO chart (id, accno, link) VALUES (?, ?, ?)|;
266     do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"}, '');
267   }
268
269   @values = ();
270
271
272   if ($form->{id}) {
273
274     # if charttype is heading make sure certain values are empty
275     # specifically, if charttype is changed from an existing account, empty the
276     # fields unnecessary for headings, so that e.g. heading doesn't appear in
277     # drop-down menues due to still having a valid "link" entry
278
279     if ( $form->{charttype} eq 'H' ) {
280       $form->{link} = '';
281       $form->{pos_bwa} = '';
282       $form->{pos_bilanz} = '';
283       $form->{pos_eur} = '';
284       $form->{new_chart_id} = '';
285       $form->{valid_from} = '';
286     };
287
288     $query = qq|UPDATE chart SET
289                   accno = ?,
290                   description = ?,
291                   charttype = ?,
292                   category = ?,
293                   link = ?,
294                   pos_bwa   = ?,
295                   pos_bilanz = ?,
296                   pos_eur = ?,
297                   new_chart_id = ?,
298                   valid_from = ?,
299                   datevautomatik = ?
300                 WHERE id = ?|;
301
302     @values = (
303                   $form->{accno},
304                   $form->{description},
305                   $form->{charttype},
306                   $form->{category},
307                   $form->{link},
308                   conv_i($form->{pos_bwa}),
309                   conv_i($form->{pos_bilanz}),
310                   conv_i($form->{pos_eur}),
311                   conv_i($form->{new_chart_id}),
312                   conv_date($form->{valid_from}),
313                   ($form->{datevautomatik} eq 'T') ? 'true':'false',
314                 $form->{id},
315     );
316
317
318   }
319
320   do_query($form, $dbh, $query, @values);
321
322   #Save Taxkeys
323
324   my @taxkeys = ();
325
326   my $MAX_TRIES = 10; # Maximum count of taxkeys in form
327   my $tk_count;
328
329   READTAXKEYS:
330   for $tk_count (0 .. $MAX_TRIES) {
331
332     # Loop control
333
334     # Check if the account already exists, else cancel
335
336     print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
337
338     last READTAXKEYS if ( $form->{'id'} == 0);
339
340     # check if there is a startdate
341     if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
342       $tk_count++;
343       next READTAXKEYS;
344     }
345
346     # Add valid taxkeys into the array
347     push @taxkeys ,
348       {
349         id        => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
350         tax_id    => conv_i($form->{"taxkey_tax_$tk_count"}),
351         startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
352         chart_id  => conv_i($form->{"id"}),
353         pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
354         delete    => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
355       };
356
357     $tk_count++;
358   }
359
360   TAXKEY:
361   for my $j (0 .. $#taxkeys){
362     if ( defined $taxkeys[$j]{'id'} ){
363       # delete Taxkey?
364
365       if ($taxkeys[$j]{'delete'}){
366         $query = qq{
367           DELETE FROM taxkeys WHERE id = ?
368         };
369
370         @values = ($taxkeys[$j]{'id'});
371
372         do_query($form, $dbh, $query, @values);
373
374         next TAXKEY;
375       }
376
377       # UPDATE Taxkey
378
379       $query = qq{
380         UPDATE taxkeys
381         SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
382             chart_id  = ?,
383             tax_id    = ?,
384             pos_ustva = ?,
385             startdate = ?
386         WHERE id = ?
387       };
388       @values = (
389         $taxkeys[$j]{'tax_id'},
390         $taxkeys[$j]{'chart_id'},
391         $taxkeys[$j]{'tax_id'},
392         $taxkeys[$j]{'pos_ustva'},
393         $taxkeys[$j]{'startdate'},
394         $taxkeys[$j]{'id'},
395       );
396       do_query($form, $dbh, $query, @values);
397     }
398     else {
399       # INSERT Taxkey
400
401       $query = qq{
402         INSERT INTO taxkeys (
403           taxkey_id,
404           chart_id,
405           tax_id,
406           pos_ustva,
407           startdate
408         )
409         VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
410       };
411       @values = (
412         $taxkeys[$j]{'tax_id'},
413         $taxkeys[$j]{'chart_id'},
414         $taxkeys[$j]{'tax_id'},
415         $taxkeys[$j]{'pos_ustva'},
416         $taxkeys[$j]{'startdate'},
417       );
418
419       do_query($form, $dbh, $query, @values);
420     }
421
422   }
423
424   # Update chart.taxkey_id to the latest from taxkeys for this chart.
425   $query = <<SQL;
426     UPDATE chart
427     SET taxkey_id = (
428       SELECT taxkey_id
429       FROM taxkeys
430       WHERE taxkeys.chart_id = chart.id
431       ORDER BY startdate DESC
432       LIMIT 1
433     )
434     WHERE id = ?
435 SQL
436
437   do_query($form, $dbh, $query, $form->{id});
438
439   # commit
440   my $rc = $dbh->commit;
441   $dbh->disconnect;
442
443   $main::lxdebug->leave_sub();
444
445   return $rc;
446 }
447
448 sub delete_account {
449   $main::lxdebug->enter_sub();
450
451   my ($self, $myconfig, $form) = @_;
452
453   # connect to database, turn off AutoCommit
454   my $dbh = $form->dbconnect_noauto($myconfig);
455
456   my $query = qq|SELECT count(*) FROM acc_trans a
457                  WHERE a.chart_id = ?|;
458   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
459
460   if ($count) {
461     $dbh->disconnect;
462     $main::lxdebug->leave_sub();
463     return;
464   }
465
466   # set inventory_accno_id, income_accno_id, expense_accno_id to defaults
467   foreach my $type (qw(inventory income expense)) {
468     $query =
469       qq|UPDATE parts | .
470       qq|SET ${type}_accno_id = (SELECT ${type}_accno_id FROM defaults) | .
471       qq|WHERE ${type}_accno_id = ?|;
472     do_query($form, $dbh, $query, $form->{id});
473   }
474
475   $query = qq|DELETE FROM tax
476               WHERE chart_id = ?|;
477   do_query($form, $dbh, $query, $form->{id});
478
479   # delete chart of account record
480   $query = qq|DELETE FROM chart
481               WHERE id = ?|;
482   do_query($form, $dbh, $query, $form->{id});
483
484   # delete account taxkeys
485   $query = qq|DELETE FROM taxkeys
486               WHERE chart_id = ?|;
487   do_query($form, $dbh, $query, $form->{id});
488
489   # commit and redirect
490   my $rc = $dbh->commit;
491   $dbh->disconnect;
492
493   $main::lxdebug->leave_sub();
494
495   return $rc;
496 }
497
498 sub lead {
499   $main::lxdebug->enter_sub();
500
501   my ($self, $myconfig, $form) = @_;
502
503   # connect to database
504   my $dbh = $form->dbconnect($myconfig);
505
506   my $query = qq|SELECT id, lead
507                  FROM leads
508                  ORDER BY 2|;
509
510   my $sth = $dbh->prepare($query);
511   $sth->execute || $form->dberror($query);
512
513   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
514     push @{ $form->{ALL} }, $ref;
515   }
516
517   $sth->finish;
518   $dbh->disconnect;
519
520   $main::lxdebug->leave_sub();
521 }
522
523 sub get_lead {
524   $main::lxdebug->enter_sub();
525
526   my ($self, $myconfig, $form) = @_;
527
528   # connect to database
529   my $dbh = $form->dbconnect($myconfig);
530
531   my $query =
532     qq|SELECT l.id, l.lead | .
533     qq|FROM leads l | .
534     qq|WHERE l.id = ?|;
535   my $sth = $dbh->prepare($query);
536   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
537
538   my $ref = $sth->fetchrow_hashref("NAME_lc");
539
540   map { $form->{$_} = $ref->{$_} } keys %$ref;
541
542   $sth->finish;
543
544   $dbh->disconnect;
545
546   $main::lxdebug->leave_sub();
547 }
548
549 sub save_lead {
550   $main::lxdebug->enter_sub();
551
552   my ($self, $myconfig, $form) = @_;
553   my ($query);
554
555   # connect to database
556   my $dbh = $form->dbconnect($myconfig);
557
558   my @values = ($form->{description});
559   # id is the old record
560   if ($form->{id}) {
561     $query = qq|UPDATE leads SET
562                 lead = ?
563                 WHERE id = ?|;
564     push(@values, $form->{id});
565   } else {
566     $query = qq|INSERT INTO leads
567                 (lead)
568                 VALUES (?)|;
569   }
570   do_query($form, $dbh, $query, @values);
571
572   $dbh->disconnect;
573
574   $main::lxdebug->leave_sub();
575 }
576
577 sub delete_lead {
578   $main::lxdebug->enter_sub();
579
580   my ($self, $myconfig, $form) = @_;
581   my ($query);
582
583   # connect to database
584   my $dbh = $form->dbconnect($myconfig);
585
586   $query = qq|DELETE FROM leads
587               WHERE id = ?|;
588   do_query($form, $dbh, $query, $form->{id});
589
590   $dbh->disconnect;
591
592   $main::lxdebug->leave_sub();
593 }
594
595 sub language {
596   $main::lxdebug->enter_sub();
597
598   my ($self, $myconfig, $form, $return_list) = @_;
599
600   # connect to database
601   my $dbh = $form->dbconnect($myconfig);
602
603   my $query =
604     "SELECT id, description, template_code, article_code, " .
605     "  output_numberformat, output_dateformat, output_longdates " .
606     "FROM language ORDER BY description";
607
608   my $sth = $dbh->prepare($query);
609   $sth->execute || $form->dberror($query);
610
611   my $ary = [];
612
613   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
614     push(@{ $ary }, $ref);
615   }
616
617   $sth->finish;
618   $dbh->disconnect;
619
620   $main::lxdebug->leave_sub();
621
622   if ($return_list) {
623     return @{$ary};
624   } else {
625     $form->{ALL} = $ary;
626   }
627 }
628
629 sub get_language {
630   $main::lxdebug->enter_sub();
631
632   my ($self, $myconfig, $form) = @_;
633
634   # connect to database
635   my $dbh = $form->dbconnect($myconfig);
636
637   my $query =
638     "SELECT description, template_code, article_code, " .
639     "  output_numberformat, output_dateformat, output_longdates " .
640     "FROM language WHERE id = ?";
641   my $sth = $dbh->prepare($query);
642   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
643
644   my $ref = $sth->fetchrow_hashref("NAME_lc");
645
646   map { $form->{$_} = $ref->{$_} } keys %$ref;
647
648   $sth->finish;
649
650   $dbh->disconnect;
651
652   $main::lxdebug->leave_sub();
653 }
654
655 sub get_language_details {
656   $main::lxdebug->enter_sub();
657
658   my ($self, $myconfig, $form, $id) = @_;
659
660   # connect to database
661   my $dbh = $form->dbconnect($myconfig);
662
663   my $query =
664     "SELECT template_code, " .
665     "  output_numberformat, output_dateformat, output_longdates " .
666     "FROM language WHERE id = ?";
667   my @res = selectrow_query($form, $dbh, $query, $id);
668   $dbh->disconnect;
669
670   $main::lxdebug->leave_sub();
671
672   return @res;
673 }
674
675 sub save_language {
676   $main::lxdebug->enter_sub();
677
678   my ($self, $myconfig, $form) = @_;
679
680   # connect to database
681   my $dbh = $form->dbconnect($myconfig);
682   my (@values, $query);
683
684   map({ push(@values, $form->{$_}); }
685       qw(description template_code article_code
686          output_numberformat output_dateformat output_longdates));
687
688   # id is the old record
689   if ($form->{id}) {
690     $query =
691       "UPDATE language SET " .
692       "  description = ?, template_code = ?, article_code = ?, " .
693       "  output_numberformat = ?, output_dateformat = ?, " .
694       "  output_longdates = ? " .
695       "WHERE id = ?";
696     push(@values, $form->{id});
697   } else {
698     $query =
699       "INSERT INTO language (" .
700       "  description, template_code, article_code, " .
701       "  output_numberformat, output_dateformat, output_longdates" .
702       ") VALUES (?, ?, ?, ?, ?, ?)";
703   }
704   do_query($form, $dbh, $query, @values);
705
706   $dbh->disconnect;
707
708   $main::lxdebug->leave_sub();
709 }
710
711 sub delete_language {
712   $main::lxdebug->enter_sub();
713
714   my ($self, $myconfig, $form) = @_;
715   my $query;
716
717   # connect to database
718   my $dbh = $form->dbconnect_noauto($myconfig);
719
720   foreach my $table (qw(generic_translations units_language)) {
721     $query = qq|DELETE FROM $table WHERE language_id = ?|;
722     do_query($form, $dbh, $query, $form->{"id"});
723   }
724
725   $query = "DELETE FROM language WHERE id = ?";
726   do_query($form, $dbh, $query, $form->{"id"});
727
728   $dbh->commit();
729   $dbh->disconnect;
730
731   $main::lxdebug->leave_sub();
732 }
733
734
735 sub buchungsgruppe {
736   $main::lxdebug->enter_sub();
737
738   my ($self, $myconfig, $form) = @_;
739
740   # connect to database
741   my $dbh = $form->dbconnect($myconfig);
742
743   my $query = qq|SELECT id, description,
744                  inventory_accno_id,
745                  (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
746                  income_accno_id_0,
747                  (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
748                  expense_accno_id_0,
749                  (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
750                  income_accno_id_1,
751                  (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
752                  expense_accno_id_1,
753                  (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
754                  income_accno_id_2,
755                  (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
756                  expense_accno_id_2,
757                  (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
758                  income_accno_id_3,
759                  (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
760                  expense_accno_id_3,
761                  (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
762                  FROM buchungsgruppen
763                  ORDER BY sortkey|;
764
765   my $sth = $dbh->prepare($query);
766   $sth->execute || $form->dberror($query);
767
768   $form->{ALL} = [];
769   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
770     push @{ $form->{ALL} }, $ref;
771   }
772
773   $sth->finish;
774   $dbh->disconnect;
775
776   $main::lxdebug->leave_sub();
777 }
778
779 sub get_buchungsgruppe {
780   $main::lxdebug->enter_sub();
781
782   my ($self, $myconfig, $form) = @_;
783   my $query;
784
785   # connect to database
786   my $dbh = $form->dbconnect($myconfig);
787
788   if ($form->{id}) {
789     $query =
790       qq|SELECT description, inventory_accno_id,
791          (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
792          income_accno_id_0,
793          (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
794          expense_accno_id_0,
795          (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
796          income_accno_id_1,
797          (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
798          expense_accno_id_1,
799          (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
800          income_accno_id_2,
801          (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
802          expense_accno_id_2,
803          (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
804          income_accno_id_3,
805          (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
806          expense_accno_id_3,
807          (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
808          FROM buchungsgruppen
809          WHERE id = ?|;
810     my $sth = $dbh->prepare($query);
811     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
812
813     my $ref = $sth->fetchrow_hashref("NAME_lc");
814
815     map { $form->{$_} = $ref->{$_} } keys %$ref;
816
817     $sth->finish;
818
819     $query =
820       qq|SELECT count(id) = 0 AS orphaned
821          FROM parts
822          WHERE buchungsgruppen_id = ?|;
823     ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
824   }
825
826   $query = "SELECT inventory_accno_id, income_accno_id, expense_accno_id ".
827     "FROM defaults";
828   ($form->{"std_inventory_accno_id"}, $form->{"std_income_accno_id"},
829    $form->{"std_expense_accno_id"}) = selectrow_query($form, $dbh, $query);
830
831   my $module = "IC";
832   $query = qq|SELECT c.accno, c.description, c.link, c.id,
833               d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
834               FROM chart c, defaults d
835               WHERE c.link LIKE '%$module%'
836               ORDER BY c.accno|;
837
838
839   my $sth = $dbh->prepare($query);
840   $sth->execute || $form->dberror($query);
841   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
842     foreach my $key (split(/:/, $ref->{link})) {
843       if (!$form->{"std_inventory_accno_id"} && ($key eq "IC")) {
844         $form->{"std_inventory_accno_id"} = $ref->{"id"};
845       }
846       if ($key =~ /$module/) {
847         if (   ($ref->{id} eq $ref->{inventory_accno_id})
848             || ($ref->{id} eq $ref->{income_accno_id})
849             || ($ref->{id} eq $ref->{expense_accno_id})) {
850           push @{ $form->{"${module}_links"}{$key} },
851             { accno       => $ref->{accno},
852               description => $ref->{description},
853               selected    => "selected",
854               id          => $ref->{id} };
855         } else {
856           push @{ $form->{"${module}_links"}{$key} },
857             { accno       => $ref->{accno},
858               description => $ref->{description},
859               selected    => "",
860               id          => $ref->{id} };
861         }
862       }
863     }
864   }
865   $sth->finish;
866
867
868   $dbh->disconnect;
869
870   $main::lxdebug->leave_sub();
871 }
872
873 sub save_buchungsgruppe {
874   $main::lxdebug->enter_sub();
875
876   my ($self, $myconfig, $form) = @_;
877
878   # connect to database
879   my $dbh = $form->dbconnect($myconfig);
880
881   my @values = ($form->{description}, $form->{inventory_accno_id},
882                 $form->{income_accno_id_0}, $form->{expense_accno_id_0},
883                 $form->{income_accno_id_1}, $form->{expense_accno_id_1},
884                 $form->{income_accno_id_2}, $form->{expense_accno_id_2},
885                 $form->{income_accno_id_3}, $form->{expense_accno_id_3});
886
887   my $query;
888
889   # id is the old record
890   if ($form->{id}) {
891     $query = qq|UPDATE buchungsgruppen SET
892                 description = ?, inventory_accno_id = ?,
893                 income_accno_id_0 = ?, expense_accno_id_0 = ?,
894                 income_accno_id_1 = ?, expense_accno_id_1 = ?,
895                 income_accno_id_2 = ?, expense_accno_id_2 = ?,
896                 income_accno_id_3 = ?, expense_accno_id_3 = ?
897                 WHERE id = ?|;
898     push(@values, $form->{id});
899   } else {
900     $query = qq|SELECT COALESCE(MAX(sortkey) + 1, 1) FROM buchungsgruppen|;
901     my ($sortkey) = $dbh->selectrow_array($query);
902     $form->dberror($query) if ($dbh->err);
903     push(@values, $sortkey);
904     $query = qq|INSERT INTO buchungsgruppen
905                 (description, inventory_accno_id,
906                 income_accno_id_0, expense_accno_id_0,
907                 income_accno_id_1, expense_accno_id_1,
908                 income_accno_id_2, expense_accno_id_2,
909                 income_accno_id_3, expense_accno_id_3,
910                 sortkey)
911                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
912   }
913   do_query($form, $dbh, $query, @values);
914
915   $dbh->disconnect;
916
917   $main::lxdebug->leave_sub();
918 }
919
920 sub delete_buchungsgruppe {
921   $main::lxdebug->enter_sub();
922
923   my ($self, $myconfig, $form) = @_;
924
925   # connect to database
926   my $dbh = $form->dbconnect($myconfig);
927
928   my $query = qq|DELETE FROM buchungsgruppen WHERE id = ?|;
929   do_query($form, $dbh, $query, $form->{id});
930
931   $dbh->disconnect;
932
933   $main::lxdebug->leave_sub();
934 }
935
936 sub swap_sortkeys {
937   $main::lxdebug->enter_sub();
938
939   my ($self, $myconfig, $form, $table) = @_;
940
941   # connect to database
942   my $dbh = $form->get_standard_dbh($myconfig);
943
944   my $query =
945     qq|SELECT
946        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey1,
947        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey2|;
948   my @values   = ($form->{"id1"}, $form->{"id2"});
949   my @sortkeys = selectrow_query($form, $dbh, $query, @values);
950
951   $query  = qq|UPDATE $table SET sortkey = ? WHERE id = ?|;
952   my $sth = prepare_query($form, $dbh, $query);
953
954   do_statement($form, $sth, $query, $sortkeys[1], $form->{"id1"});
955   do_statement($form, $sth, $query, $sortkeys[0], $form->{"id2"});
956
957   $sth->finish();
958
959   $dbh->commit();
960
961   $main::lxdebug->leave_sub();
962 }
963
964 sub prepare_template_filename {
965   $main::lxdebug->enter_sub();
966
967   my ($self, $myconfig, $form) = @_;
968
969   my ($filename, $display_filename);
970
971   if ($form->{type} eq "stylesheet") {
972     $filename = "css/$myconfig->{stylesheet}";
973     $display_filename = $myconfig->{stylesheet};
974
975   } else {
976     $filename = $form->{formname};
977
978     if ($form->{language}) {
979       my ($id, $template_code) = split(/--/, $form->{language});
980       $filename .= "_${template_code}";
981     }
982
983     if ($form->{printer}) {
984       my ($id, $template_code) = split(/--/, $form->{printer});
985       $filename .= "_${template_code}";
986     }
987
988     $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
989     if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
990       $filename =~ s|.*/||;
991     }
992     $display_filename = $filename;
993     $filename = "$myconfig->{templates}/$filename";
994   }
995
996   $main::lxdebug->leave_sub();
997
998   return ($filename, $display_filename);
999 }
1000
1001
1002 sub load_template {
1003   $main::lxdebug->enter_sub();
1004
1005   my ($self, $filename) = @_;
1006
1007   my ($content, $lines) = ("", 0);
1008
1009   local *TEMPLATE;
1010
1011   if (open(TEMPLATE, $filename)) {
1012     while (<TEMPLATE>) {
1013       $content .= $_;
1014       $lines++;
1015     }
1016     close(TEMPLATE);
1017   }
1018
1019   $content = Encode::decode('utf-8-strict', $content) if $::locale->is_utf8;
1020
1021   $main::lxdebug->leave_sub();
1022
1023   return ($content, $lines);
1024 }
1025
1026 sub save_template {
1027   $main::lxdebug->enter_sub();
1028
1029   my ($self, $filename, $content) = @_;
1030
1031   local *TEMPLATE;
1032
1033   my $error = "";
1034
1035   if (open(TEMPLATE, ">", $filename)) {
1036     $content = Encode::encode('utf-8-strict', $content) if $::locale->is_utf8;
1037     $content =~ s/\r\n/\n/g;
1038     print(TEMPLATE $content);
1039     close(TEMPLATE);
1040   } else {
1041     $error = $!;
1042   }
1043
1044   $main::lxdebug->leave_sub();
1045
1046   return $error;
1047 }
1048
1049 sub save_defaults {
1050   $main::lxdebug->enter_sub();
1051
1052   my $self     = shift;
1053   my %params   = @_;
1054
1055   my $myconfig = \%main::myconfig;
1056   my $form     = $main::form;
1057
1058   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1059
1060   my %accnos;
1061   map { ($accnos{$_}) = split(m/--/, $form->{$_}) } qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno ar_paid_accno);
1062
1063   $form->{curr}  =~ s/ //g;
1064   my @currencies =  grep { $_ ne '' } split m/:/, $form->{curr};
1065   my $currency   =  join ':', @currencies;
1066
1067   # these defaults are database wide
1068
1069   my $query =
1070     qq|UPDATE defaults SET
1071         inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?),
1072         income_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1073         expense_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1074         fxgain_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1075         fxloss_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1076         ar_paid_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1077         invnumber          = ?,
1078         cnnumber           = ?,
1079         sonumber           = ?,
1080         ponumber           = ?,
1081         sqnumber           = ?,
1082         rfqnumber          = ?,
1083         customernumber     = ?,
1084         vendornumber       = ?,
1085         articlenumber      = ?,
1086         servicenumber      = ?,
1087         assemblynumber     = ?,
1088         sdonumber          = ?,
1089         pdonumber          = ?,
1090         curr               = ?,
1091         businessnumber     = ?,
1092         weightunit         = ?,
1093         language_id        = ?|;
1094   my @values = ($accnos{inventory_accno}, $accnos{income_accno}, $accnos{expense_accno},
1095                 $accnos{fxgain_accno},    $accnos{fxloss_accno}, $accnos{ar_paid_accno},
1096                 $form->{invnumber},       $form->{cnnumber},
1097                 $form->{sonumber},        $form->{ponumber},
1098                 $form->{sqnumber},        $form->{rfqnumber},
1099                 $form->{customernumber},  $form->{vendornumber},
1100                 $form->{articlenumber},   $form->{servicenumber},
1101                 $form->{assemblynumber},
1102                 $form->{sdonumber},       $form->{pdonumber},
1103                 $currency,
1104                 $form->{businessnumber},  $form->{weightunit},
1105                 conv_i($form->{language_id}));
1106   do_query($form, $dbh, $query, @values);
1107
1108   $dbh->commit();
1109
1110   $main::lxdebug->leave_sub();
1111 }
1112
1113
1114 sub save_preferences {
1115   $main::lxdebug->enter_sub();
1116
1117   my ($self, $myconfig, $form) = @_;
1118
1119   my $dbh = $form->get_standard_dbh($myconfig);
1120
1121   my ($currency, $businessnumber) = selectrow_query($form, $dbh, qq|SELECT curr, businessnumber FROM defaults|);
1122
1123   # update name
1124   my $query = qq|UPDATE employee SET name = ? WHERE login = ?|;
1125   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1126
1127   my $rc = $dbh->commit();
1128
1129   # save first currency in myconfig
1130   $currency               =~ s/:.*//;
1131   $form->{currency}       =  $currency;
1132
1133   $form->{businessnumber} =  $businessnumber;
1134
1135   $myconfig = User->new(login => $form->{login});
1136
1137   foreach my $item (keys %$form) {
1138     $myconfig->{$item} = $form->{$item};
1139   }
1140
1141   $myconfig->save_member;
1142
1143   my $auth = $main::auth;
1144
1145   $main::lxdebug->leave_sub();
1146
1147   return $rc;
1148 }
1149
1150 sub get_defaults {
1151   $main::lxdebug->enter_sub();
1152
1153   my $self     = shift;
1154   my %params   = @_;
1155
1156   my $myconfig = \%main::myconfig;
1157   my $form     = $main::form;
1158
1159   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1160
1161   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
1162
1163   $defaults->{weightunit} ||= 'kg';
1164
1165   $main::lxdebug->leave_sub();
1166
1167   return $defaults;
1168 }
1169
1170 sub defaultaccounts {
1171   $main::lxdebug->enter_sub();
1172
1173   my ($self, $myconfig, $form) = @_;
1174
1175   # connect to database
1176   my $dbh = $form->dbconnect($myconfig);
1177
1178   # get defaults from defaults table
1179   my $query = qq|SELECT * FROM defaults|;
1180   my $sth   = $dbh->prepare($query);
1181   $sth->execute || $form->dberror($query);
1182
1183   $form->{defaults}               = $sth->fetchrow_hashref("NAME_lc");
1184   $form->{defaults}{IC}           = $form->{defaults}{inventory_accno_id};
1185   $form->{defaults}{IC_income}    = $form->{defaults}{income_accno_id};
1186   $form->{defaults}{IC_expense}   = $form->{defaults}{expense_accno_id};
1187   $form->{defaults}{FX_gain}      = $form->{defaults}{fxgain_accno_id};
1188   $form->{defaults}{FX_loss}      = $form->{defaults}{fxloss_accno_id};
1189   $form->{defaults}{AR_paid}      = $form->{defaults}{ar_paid_accno_id};
1190
1191   $form->{defaults}{weightunit} ||= 'kg';
1192
1193   $sth->finish;
1194
1195   $query = qq|SELECT c.id, c.accno, c.description, c.link
1196               FROM chart c
1197               WHERE c.link LIKE '%IC%'
1198               ORDER BY c.accno|;
1199   $sth = $dbh->prepare($query);
1200   $sth->execute || $self->dberror($query);
1201
1202   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1203     foreach my $key (split(/:/, $ref->{link})) {
1204       if ($key =~ /IC/) {
1205         my $nkey = $key;
1206         if ($key =~ /cogs/) {
1207           $nkey = "IC_expense";
1208         }
1209         if ($key =~ /sale/) {
1210           $nkey = "IC_income";
1211         }
1212         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1213                                              id          => $ref->{id},
1214                                              description => $ref->{description}
1215         );
1216       }
1217     }
1218   }
1219   $sth->finish;
1220
1221   $query = qq|SELECT c.id, c.accno, c.description
1222               FROM chart c
1223               WHERE c.category = 'I'
1224               AND c.charttype = 'A'
1225               ORDER BY c.accno|;
1226   $sth = $dbh->prepare($query);
1227   $sth->execute || $self->dberror($query);
1228
1229   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1230     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1231                                              id          => $ref->{id},
1232                                              description => $ref->{description}
1233     );
1234   }
1235   $sth->finish;
1236
1237   $query = qq|SELECT c.id, c.accno, c.description
1238               FROM chart c
1239               WHERE c.category = 'E'
1240               AND c.charttype = 'A'
1241               ORDER BY c.accno|;
1242   $sth = $dbh->prepare($query);
1243   $sth->execute || $self->dberror($query);
1244
1245   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1246     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1247                                              id          => $ref->{id},
1248                                              description => $ref->{description}
1249     );
1250   }
1251   $sth->finish;
1252
1253   # now get the tax rates and numbers
1254   $query = qq|SELECT c.id, c.accno, c.description,
1255               t.rate * 100 AS rate, t.taxnumber
1256               FROM chart c, tax t
1257               WHERE c.id = t.chart_id|;
1258
1259   $sth = $dbh->prepare($query);
1260   $sth->execute || $form->dberror($query);
1261
1262   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1263     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1264     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1265     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1266       if $ref->{taxnumber};
1267     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1268   }
1269   # Abfrage für Standard Umlaufvermögenskonto
1270   $query =
1271     qq|SELECT id, accno, description, link | .
1272     qq|FROM chart | .
1273     qq|WHERE link LIKE ? |.
1274     qq|ORDER BY accno|;
1275   $sth = prepare_execute_query($form, $dbh, $query, '%AR%');
1276   $sth->execute || $form->dberror($query);#
1277   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1278     foreach my $item (split(/:/, $ref->{link})) {
1279       if ($item eq "AR_paid") {
1280         %{ $form->{IC}{AR_paid}{ $ref->{accno} } } = (
1281                                              id          => $ref->{id},
1282                                              description => $ref->{description}
1283           );
1284       }
1285     }
1286   }
1287
1288   $sth->finish;
1289   $dbh->disconnect;
1290
1291   $main::lxdebug->leave_sub();
1292 }
1293
1294 sub closedto {
1295   $main::lxdebug->enter_sub();
1296
1297   my ($self, $myconfig, $form) = @_;
1298
1299   my $dbh = $form->dbconnect($myconfig);
1300
1301   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1302   my $sth   = $dbh->prepare($query);
1303   $sth->execute || $form->dberror($query);
1304
1305   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1306
1307   $sth->finish;
1308
1309   $dbh->disconnect;
1310
1311   $main::lxdebug->leave_sub();
1312 }
1313
1314 sub closebooks {
1315   $main::lxdebug->enter_sub();
1316
1317   my ($self, $myconfig, $form) = @_;
1318
1319   my $dbh = $form->dbconnect($myconfig);
1320
1321   my ($query, @values);
1322
1323   if ($form->{revtrans}) {
1324     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1325
1326   } elsif ($form->{closedto}) {
1327     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1328     @values = (conv_date($form->{closedto}));
1329
1330   } else {
1331     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1332   }
1333
1334   # set close in defaults
1335   do_query($form, $dbh, $query, @values);
1336
1337   $dbh->disconnect;
1338
1339   $main::lxdebug->leave_sub();
1340 }
1341
1342 sub get_base_unit {
1343   my ($self, $units, $unit_name, $factor) = @_;
1344
1345   $factor = 1 unless ($factor);
1346
1347   my $unit = $units->{$unit_name};
1348
1349   if (!defined($unit) || !$unit->{"base_unit"} ||
1350       ($unit_name eq $unit->{"base_unit"})) {
1351     return ($unit_name, $factor);
1352   }
1353
1354   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1355 }
1356
1357 sub retrieve_units {
1358   $main::lxdebug->enter_sub();
1359
1360   my ($self, $myconfig, $form, $prefix) = @_;
1361   $prefix ||= '';
1362
1363   my $dbh = $form->get_standard_dbh;
1364
1365   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1366
1367   my $sth = prepare_execute_query($form, $dbh, $query);
1368
1369   my $units = {};
1370   while (my $ref = $sth->fetchrow_hashref()) {
1371     $units->{$ref->{"name"}} = $ref;
1372   }
1373   $sth->finish();
1374
1375   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1376   $sth = $dbh->prepare($query_lang);
1377   $sth->execute() || $form->dberror($query_lang);
1378   my @languages;
1379   while (my $ref = $sth->fetchrow_hashref()) {
1380     push(@languages, $ref);
1381   }
1382   $sth->finish();
1383
1384   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1385     "FROM units_language ul " .
1386     "LEFT JOIN language l ON ul.language_id = l.id " .
1387     "WHERE ul.unit = ?";
1388   $sth = $dbh->prepare($query_lang);
1389
1390   foreach my $unit (values(%{$units})) {
1391     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1392
1393     $unit->{"LANGUAGES"} = {};
1394     foreach my $lang (@languages) {
1395       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1396     }
1397
1398     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1399     while (my $ref = $sth->fetchrow_hashref()) {
1400       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1401     }
1402   }
1403   $sth->finish;
1404
1405   $main::lxdebug->leave_sub();
1406
1407   return $units;
1408 }
1409
1410 sub retrieve_all_units {
1411   $main::lxdebug->enter_sub();
1412
1413   my $self = shift;
1414
1415   if (!$::request->{cache}{all_units}) {
1416     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
1417   }
1418
1419   $main::lxdebug->leave_sub();
1420
1421   return $::request->{cache}{all_units};
1422 }
1423
1424
1425 sub translate_units {
1426   $main::lxdebug->enter_sub();
1427
1428   my ($self, $form, $template_code, $unit, $amount) = @_;
1429
1430   my $units = $self->retrieve_units(\%main::myconfig, $form);
1431
1432   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1433   my $new_unit = $unit;
1434   if ($h) {
1435     if (($amount != 1) && $h->{"localized_plural"}) {
1436       $new_unit = $h->{"localized_plural"};
1437     } elsif ($h->{"localized"}) {
1438       $new_unit = $h->{"localized"};
1439     }
1440   }
1441
1442   $main::lxdebug->leave_sub();
1443
1444   return $new_unit;
1445 }
1446
1447 sub units_in_use {
1448   $main::lxdebug->enter_sub();
1449
1450   my ($self, $myconfig, $form, $units) = @_;
1451
1452   my $dbh = $form->dbconnect($myconfig);
1453
1454   map({ $_->{"in_use"} = 0; } values(%{$units}));
1455
1456   foreach my $unit (values(%{$units})) {
1457     my $base_unit = $unit->{"original_base_unit"};
1458     while ($base_unit) {
1459       $units->{$base_unit}->{"in_use"} = 1;
1460       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1461       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1462       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1463     }
1464   }
1465
1466   foreach my $unit (values(%{$units})) {
1467     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1468
1469     foreach my $table (qw(parts invoice orderitems)) {
1470       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1471
1472       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1473         $query .= "= " . $dbh->quote($unit->{"name"});
1474       } else {
1475         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1476           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1477       }
1478
1479       my ($count) = $dbh->selectrow_array($query);
1480       $form->dberror($query) if ($dbh->err);
1481
1482       if ($count) {
1483         $unit->{"in_use"} = 1;
1484         last;
1485       }
1486     }
1487   }
1488
1489   $dbh->disconnect();
1490
1491   $main::lxdebug->leave_sub();
1492 }
1493
1494 sub convertible_units {
1495   $main::lxdebug->enter_sub();
1496
1497   my $self        = shift;
1498   my $units       = shift;
1499   my $filter_unit = shift;
1500   my $not_smaller = shift;
1501
1502   my $conv_units = [];
1503
1504   $filter_unit = $units->{$filter_unit};
1505
1506   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1507     my $unit = $units->{$name};
1508
1509     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1510         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1511       push @{$conv_units}, $unit;
1512     }
1513   }
1514
1515   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1516
1517   $main::lxdebug->leave_sub();
1518
1519   return \@sorted;
1520 }
1521
1522 # if $a is translatable to $b, return the factor between them.
1523 # else return 1
1524 sub convert_unit {
1525   $main::lxdebug->enter_sub(2);
1526   my ($this, $a, $b, $all_units) = @_;
1527
1528   if (!$all_units) {
1529     $all_units = $this->retrieve_all_units;
1530   }
1531
1532   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1533   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1534   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1535   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1536 }
1537
1538 sub unit_select_data {
1539   $main::lxdebug->enter_sub();
1540
1541   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1542
1543   my $select = [];
1544
1545   if ($empty_entry) {
1546     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1547   }
1548
1549   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1550     if (!$convertible_into ||
1551         ($units->{$convertible_into} &&
1552          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1553       push @{$select}, { "name"      => $unit,
1554                          "base_unit" => $units->{$unit}->{"base_unit"},
1555                          "factor"    => $units->{$unit}->{"factor"},
1556                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1557     }
1558   }
1559
1560   $main::lxdebug->leave_sub();
1561
1562   return $select;
1563 }
1564
1565 sub unit_select_html {
1566   $main::lxdebug->enter_sub();
1567
1568   my ($self, $units, $name, $selected, $convertible_into) = @_;
1569
1570   my $select = "<select name=${name}>";
1571
1572   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1573     if (!$convertible_into ||
1574         ($units->{$convertible_into} &&
1575          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1576       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1577     }
1578   }
1579   $select .= "</select>";
1580
1581   $main::lxdebug->leave_sub();
1582
1583   return $select;
1584 }
1585
1586 sub sum_with_unit {
1587   $main::lxdebug->enter_sub();
1588
1589   my $self  = shift;
1590
1591   my $units = $self->retrieve_all_units();
1592
1593   my $sum   = 0;
1594   my $base_unit;
1595
1596   while (2 <= scalar(@_)) {
1597     my $qty  = shift(@_);
1598     my $unit = $units->{shift(@_)};
1599
1600     croak "No unit defined with name $unit" if (!defined $unit);
1601
1602     if (!$base_unit) {
1603       $base_unit = $unit->{base_unit};
1604     } elsif ($base_unit ne $unit->{base_unit}) {
1605       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1606     }
1607
1608     $sum += $qty * $unit->{factor};
1609   }
1610
1611   $main::lxdebug->leave_sub();
1612
1613   return wantarray ? ($sum, $base_unit) : $sum;
1614 }
1615
1616 sub add_unit {
1617   $main::lxdebug->enter_sub();
1618
1619   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1620
1621   my $dbh = $form->dbconnect_noauto($myconfig);
1622
1623   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1624   my ($sortkey) = selectrow_query($form, $dbh, $query);
1625
1626   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1627     "VALUES (?, ?, ?, ?)";
1628   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1629
1630   if ($languages) {
1631     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1632     my $sth = $dbh->prepare($query);
1633     foreach my $lang (@{$languages}) {
1634       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1635       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1636     }
1637     $sth->finish();
1638   }
1639
1640   $dbh->commit();
1641   $dbh->disconnect();
1642
1643   $main::lxdebug->leave_sub();
1644 }
1645
1646 sub save_units {
1647   $main::lxdebug->enter_sub();
1648
1649   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1650
1651   my $dbh = $form->dbconnect_noauto($myconfig);
1652
1653   my ($base_unit, $unit, $sth, $query);
1654
1655   $query = "DELETE FROM units_language";
1656   $dbh->do($query) || $form->dberror($query);
1657
1658   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1659     $query = "DELETE FROM units WHERE name IN (";
1660     map({ $query .= "?," } @{$delete_units});
1661     substr($query, -1, 1) = ")";
1662     $dbh->do($query, undef, @{$delete_units}) ||
1663       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1664   }
1665
1666   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1667   $sth = $dbh->prepare($query);
1668
1669   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1670   my $sth_lang = $dbh->prepare($query_lang);
1671
1672   foreach $unit (values(%{$units})) {
1673     $unit->{"depth"} = 0;
1674     my $base_unit = $unit;
1675     while ($base_unit->{"base_unit"}) {
1676       $unit->{"depth"}++;
1677       $base_unit = $units->{$base_unit->{"base_unit"}};
1678     }
1679   }
1680
1681   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1682     if ($unit->{"LANGUAGES"}) {
1683       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1684         next unless ($lang->{"id"} && $lang->{"localized"});
1685         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1686         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1687       }
1688     }
1689
1690     next if ($unit->{"unchanged_unit"});
1691
1692     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1693     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1694   }
1695
1696   $sth->finish();
1697   $sth_lang->finish();
1698   $dbh->commit();
1699   $dbh->disconnect();
1700
1701   $main::lxdebug->leave_sub();
1702 }
1703
1704 sub taxes {
1705   $main::lxdebug->enter_sub();
1706
1707   my ($self, $myconfig, $form) = @_;
1708
1709   # connect to database
1710   my $dbh = $form->dbconnect($myconfig);
1711
1712   my $query = qq|SELECT
1713                    t.id,
1714                    t.taxkey,
1715                    t.taxdescription,
1716                    round(t.rate * 100, 2) AS rate,
1717                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1718                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
1719                  FROM tax t
1720                  ORDER BY taxkey|;
1721
1722   my $sth = $dbh->prepare($query);
1723   $sth->execute || $form->dberror($query);
1724
1725   $form->{TAX} = [];
1726   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1727     push @{ $form->{TAX} }, $ref;
1728   }
1729
1730   $sth->finish;
1731   $dbh->disconnect;
1732
1733   $main::lxdebug->leave_sub();
1734 }
1735
1736 sub get_tax_accounts {
1737   $main::lxdebug->enter_sub();
1738
1739   my ($self, $myconfig, $form) = @_;
1740
1741   my $dbh = $form->dbconnect($myconfig);
1742
1743   # get Accounts from chart
1744   my $query = qq{ SELECT
1745                  id,
1746                  accno || ' - ' || description AS taxaccount
1747                FROM chart
1748                WHERE link LIKE '%_tax%'
1749                ORDER BY accno
1750              };
1751
1752   my $sth = $dbh->prepare($query);
1753   $sth->execute || $form->dberror($query);
1754
1755   $form->{ACCOUNTS} = [];
1756   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1757     push @{ $form->{ACCOUNTS} }, $ref;
1758   }
1759
1760   $sth->finish;
1761
1762   $dbh->disconnect;
1763
1764   $main::lxdebug->leave_sub();
1765 }
1766
1767 sub get_tax {
1768   $main::lxdebug->enter_sub();
1769
1770   my ($self, $myconfig, $form) = @_;
1771
1772   # connect to database
1773   my $dbh = $form->dbconnect($myconfig);
1774
1775   my $query = qq|SELECT
1776                    taxkey,
1777                    taxdescription,
1778                    round(rate * 100, 2) AS rate,
1779                    chart_id,
1780                    (id IN (SELECT tax_id
1781                            FROM acc_trans)) AS tax_already_used
1782                  FROM tax
1783                  WHERE id = ? |;
1784
1785   my $sth = $dbh->prepare($query);
1786   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1787
1788   my $ref = $sth->fetchrow_hashref("NAME_lc");
1789
1790   map { $form->{$_} = $ref->{$_} } keys %$ref;
1791
1792   $sth->finish;
1793
1794   # see if it is used by a taxkey
1795   $query = qq|SELECT count(*) FROM taxkeys
1796               WHERE tax_id = ? AND chart_id >0|;
1797
1798   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1799
1800   $form->{orphaned} = !$form->{orphaned};
1801   $sth->finish;
1802
1803   if (!$form->{orphaned} ) {
1804     $query = qq|SELECT DISTINCT c.id, c.accno
1805                 FROM taxkeys tk
1806                 JOIN   tax t ON (t.id = tk.tax_id)
1807                 JOIN chart c ON (c.id = tk.chart_id)
1808                 WHERE tk.tax_id = ?|;
1809
1810     $sth = $dbh->prepare($query);
1811     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1812
1813     $form->{TAXINUSE} = [];
1814     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1815       push @{ $form->{TAXINUSE} }, $ref;
1816     }
1817
1818     $sth->finish;
1819   }
1820
1821   $dbh->disconnect;
1822
1823   $main::lxdebug->leave_sub();
1824 }
1825
1826 sub save_tax {
1827   $main::lxdebug->enter_sub();
1828
1829   my ($self, $myconfig, $form) = @_;
1830   my $query;
1831
1832   # connect to database
1833   my $dbh = $form->get_standard_dbh($myconfig);
1834
1835   $form->{rate} = $form->{rate} / 100;
1836
1837   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
1838   if ($form->{id} ne "") {
1839     $query = qq|UPDATE tax SET
1840                   taxkey         = ?,
1841                   taxdescription = ?,
1842                   rate           = ?,
1843                   chart_id       = ?,
1844                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
1845                 WHERE id = ?|;
1846     push(@values, $form->{id});
1847
1848   } else {
1849     #ok
1850     $query = qq|INSERT INTO tax (
1851                   taxkey,
1852                   taxdescription,
1853                   rate,
1854                   chart_id,
1855                   taxnumber
1856                 )
1857                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
1858   }
1859   do_query($form, $dbh, $query, @values);
1860
1861   $dbh->commit();
1862
1863   $main::lxdebug->leave_sub();
1864 }
1865
1866 sub delete_tax {
1867   $main::lxdebug->enter_sub();
1868
1869   my ($self, $myconfig, $form) = @_;
1870   my $query;
1871
1872   # connect to database
1873   my $dbh = $form->get_standard_dbh($myconfig);
1874
1875   $query = qq|DELETE FROM tax
1876               WHERE id = ?|;
1877   do_query($form, $dbh, $query, $form->{id});
1878
1879   $dbh->commit();
1880
1881   $main::lxdebug->leave_sub();
1882 }
1883
1884 sub save_price_factor {
1885   $main::lxdebug->enter_sub();
1886
1887   my ($self, $myconfig, $form) = @_;
1888
1889   # connect to database
1890   my $dbh = $form->get_standard_dbh($myconfig);
1891
1892   my $query;
1893   my @values = ($form->{description}, conv_i($form->{factor}));
1894
1895   if ($form->{id}) {
1896     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1897     push @values, conv_i($form->{id});
1898
1899   } else {
1900     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1901   }
1902
1903   do_query($form, $dbh, $query, @values);
1904
1905   $dbh->commit();
1906
1907   $main::lxdebug->leave_sub();
1908 }
1909
1910 sub get_all_price_factors {
1911   $main::lxdebug->enter_sub();
1912
1913   my ($self, $myconfig, $form) = @_;
1914
1915   # connect to database
1916   my $dbh = $form->get_standard_dbh($myconfig);
1917
1918   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1919
1920   $main::lxdebug->leave_sub();
1921 }
1922
1923 sub get_price_factor {
1924   $main::lxdebug->enter_sub();
1925
1926   my ($self, $myconfig, $form) = @_;
1927
1928   # connect to database
1929   my $dbh = $form->get_standard_dbh($myconfig);
1930
1931   my $query = qq|SELECT description, factor,
1932                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
1933                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
1934                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1935                  FROM price_factors WHERE id = ?|;
1936
1937   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1938
1939   $main::lxdebug->leave_sub();
1940 }
1941
1942 sub delete_price_factor {
1943   $main::lxdebug->enter_sub();
1944
1945   my ($self, $myconfig, $form) = @_;
1946
1947   # connect to database
1948   my $dbh = $form->get_standard_dbh($myconfig);
1949
1950   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1951   $dbh->commit();
1952
1953   $main::lxdebug->leave_sub();
1954 }
1955
1956 sub save_warehouse {
1957   $main::lxdebug->enter_sub();
1958
1959   my ($self, $myconfig, $form) = @_;
1960
1961   # connect to database
1962   my $dbh = $form->get_standard_dbh($myconfig);
1963
1964   my ($query, @values, $sth);
1965
1966   if (!$form->{id}) {
1967     $query        = qq|SELECT nextval('id')|;
1968     ($form->{id}) = selectrow_query($form, $dbh, $query);
1969
1970     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1971     do_query($form, $dbh, $query, $form->{id});
1972   }
1973
1974   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1975            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1976
1977   if (0 < $form->{number_of_new_bins}) {
1978     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1979     $sth   = prepare_query($form, $dbh, $query);
1980
1981     foreach my $i (1..$form->{number_of_new_bins}) {
1982       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
1983     }
1984
1985     $sth->finish();
1986   }
1987
1988   $dbh->commit();
1989
1990   $main::lxdebug->leave_sub();
1991 }
1992
1993 sub save_bins {
1994   $main::lxdebug->enter_sub();
1995
1996   my ($self, $myconfig, $form) = @_;
1997
1998   # connect to database
1999   my $dbh = $form->get_standard_dbh($myconfig);
2000
2001   my ($query, @values, $commit_necessary, $sth);
2002
2003   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
2004
2005   if (@values) {
2006     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
2007     do_query($form, $dbh, $query, @values);
2008
2009     $commit_necessary = 1;
2010   }
2011
2012   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
2013   $sth   = prepare_query($form, $dbh, $query);
2014
2015   foreach my $row (1..$form->{rowcount}) {
2016     next if ($form->{"delete_${row}"});
2017
2018     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
2019
2020     $commit_necessary = 1;
2021   }
2022
2023   $sth->finish();
2024
2025   $dbh->commit() if ($commit_necessary);
2026
2027   $main::lxdebug->leave_sub();
2028 }
2029
2030 sub delete_warehouse {
2031   $main::lxdebug->enter_sub();
2032
2033   my ($self, $myconfig, $form) = @_;
2034
2035   # connect to database
2036   my $dbh = $form->get_standard_dbh($myconfig);
2037
2038   my $id      = conv_i($form->{id});
2039   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|;
2040   my ($count) = selectrow_query($form, $dbh, $query, $id);
2041
2042   if ($count) {
2043     $main::lxdebug->leave_sub();
2044     return 0;
2045   }
2046
2047   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2048   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2049
2050   $dbh->commit();
2051
2052   $main::lxdebug->leave_sub();
2053
2054   return 1;
2055 }
2056
2057 sub get_all_warehouses {
2058   $main::lxdebug->enter_sub();
2059
2060   my ($self, $myconfig, $form) = @_;
2061
2062   # connect to database
2063   my $dbh = $form->get_standard_dbh($myconfig);
2064
2065   my $query = qq|SELECT w.id, w.description, w.invalid,
2066                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2067                  FROM warehouse w
2068                  ORDER BY w.sortkey|;
2069
2070   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2071
2072   $main::lxdebug->leave_sub();
2073 }
2074
2075 sub get_warehouse {
2076   $main::lxdebug->enter_sub();
2077
2078   my ($self, $myconfig, $form) = @_;
2079
2080   # connect to database
2081   my $dbh = $form->get_standard_dbh($myconfig);
2082
2083   my $id    = conv_i($form->{id});
2084   my $query = qq|SELECT w.description, w.invalid
2085                  FROM warehouse w
2086                  WHERE w.id = ?|;
2087
2088   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2089
2090   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2091
2092   $query = qq|SELECT b.*, EXISTS
2093                 (SELECT i.warehouse_id
2094                  FROM inventory i
2095                  WHERE i.bin_id = b.id
2096                  LIMIT 1)
2097                 AS in_use
2098               FROM bin b
2099               WHERE b.warehouse_id = ?|;
2100
2101   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2102
2103   $main::lxdebug->leave_sub();
2104 }
2105
2106 1;