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