Merge branch 'master' into dev
[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   $query = qq|DELETE FROM tax
479               WHERE chart_id = ?|;
480   do_query($form, $dbh, $query, $form->{id});
481
482   # delete chart of account record
483   $query = qq|DELETE FROM chart
484               WHERE id = ?|;
485   do_query($form, $dbh, $query, $form->{id});
486
487   # delete account taxkeys
488   $query = qq|DELETE FROM taxkeys
489               WHERE chart_id = ?|;
490   do_query($form, $dbh, $query, $form->{id});
491
492   # commit and redirect
493   my $rc = $dbh->commit;
494   $dbh->disconnect;
495
496   $main::lxdebug->leave_sub();
497
498   return $rc;
499 }
500
501 sub lead {
502   $main::lxdebug->enter_sub();
503
504   my ($self, $myconfig, $form) = @_;
505
506   # connect to database
507   my $dbh = $form->dbconnect($myconfig);
508
509   my $query = qq|SELECT id, lead
510                  FROM leads
511                  ORDER BY 2|;
512
513   my $sth = $dbh->prepare($query);
514   $sth->execute || $form->dberror($query);
515
516   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
517     push @{ $form->{ALL} }, $ref;
518   }
519
520   $sth->finish;
521   $dbh->disconnect;
522
523   $main::lxdebug->leave_sub();
524 }
525
526 sub get_lead {
527   $main::lxdebug->enter_sub();
528
529   my ($self, $myconfig, $form) = @_;
530
531   # connect to database
532   my $dbh = $form->dbconnect($myconfig);
533
534   my $query =
535     qq|SELECT l.id, l.lead | .
536     qq|FROM leads l | .
537     qq|WHERE l.id = ?|;
538   my $sth = $dbh->prepare($query);
539   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
540
541   my $ref = $sth->fetchrow_hashref("NAME_lc");
542
543   map { $form->{$_} = $ref->{$_} } keys %$ref;
544
545   $sth->finish;
546
547   $dbh->disconnect;
548
549   $main::lxdebug->leave_sub();
550 }
551
552 sub save_lead {
553   $main::lxdebug->enter_sub();
554
555   my ($self, $myconfig, $form) = @_;
556   my ($query);
557
558   # connect to database
559   my $dbh = $form->dbconnect($myconfig);
560
561   my @values = ($form->{description});
562   # id is the old record
563   if ($form->{id}) {
564     $query = qq|UPDATE leads SET
565                 lead = ?
566                 WHERE id = ?|;
567     push(@values, $form->{id});
568   } else {
569     $query = qq|INSERT INTO leads
570                 (lead)
571                 VALUES (?)|;
572   }
573   do_query($form, $dbh, $query, @values);
574
575   $dbh->disconnect;
576
577   $main::lxdebug->leave_sub();
578 }
579
580 sub delete_lead {
581   $main::lxdebug->enter_sub();
582
583   my ($self, $myconfig, $form) = @_;
584   my ($query);
585
586   # connect to database
587   my $dbh = $form->dbconnect($myconfig);
588
589   $query = qq|DELETE FROM leads
590               WHERE id = ?|;
591   do_query($form, $dbh, $query, $form->{id});
592
593   $dbh->disconnect;
594
595   $main::lxdebug->leave_sub();
596 }
597
598 sub language {
599   $main::lxdebug->enter_sub();
600
601   my ($self, $myconfig, $form, $return_list) = @_;
602
603   # connect to database
604   my $dbh = $form->dbconnect($myconfig);
605
606   my $query =
607     "SELECT id, description, template_code, article_code, " .
608     "  output_numberformat, output_dateformat, output_longdates " .
609     "FROM language ORDER BY description";
610
611   my $sth = $dbh->prepare($query);
612   $sth->execute || $form->dberror($query);
613
614   my $ary = [];
615
616   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
617     push(@{ $ary }, $ref);
618   }
619
620   $sth->finish;
621   $dbh->disconnect;
622
623   $main::lxdebug->leave_sub();
624
625   if ($return_list) {
626     return @{$ary};
627   } else {
628     $form->{ALL} = $ary;
629   }
630 }
631
632 sub get_language {
633   $main::lxdebug->enter_sub();
634
635   my ($self, $myconfig, $form) = @_;
636
637   # connect to database
638   my $dbh = $form->dbconnect($myconfig);
639
640   my $query =
641     "SELECT description, template_code, article_code, " .
642     "  output_numberformat, output_dateformat, output_longdates " .
643     "FROM language WHERE id = ?";
644   my $sth = $dbh->prepare($query);
645   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
646
647   my $ref = $sth->fetchrow_hashref("NAME_lc");
648
649   map { $form->{$_} = $ref->{$_} } keys %$ref;
650
651   $sth->finish;
652
653   $dbh->disconnect;
654
655   $main::lxdebug->leave_sub();
656 }
657
658 sub get_language_details {
659   $main::lxdebug->enter_sub();
660
661   my ($self, $myconfig, $form, $id) = @_;
662
663   # connect to database
664   my $dbh = $form->dbconnect($myconfig);
665
666   my $query =
667     "SELECT template_code, " .
668     "  output_numberformat, output_dateformat, output_longdates " .
669     "FROM language WHERE id = ?";
670   my @res = selectrow_query($form, $dbh, $query, $id);
671   $dbh->disconnect;
672
673   $main::lxdebug->leave_sub();
674
675   return @res;
676 }
677
678 sub save_language {
679   $main::lxdebug->enter_sub();
680
681   my ($self, $myconfig, $form) = @_;
682
683   # connect to database
684   my $dbh = $form->dbconnect($myconfig);
685   my (@values, $query);
686
687   map({ push(@values, $form->{$_}); }
688       qw(description template_code article_code
689          output_numberformat output_dateformat output_longdates));
690
691   # id is the old record
692   if ($form->{id}) {
693     $query =
694       "UPDATE language SET " .
695       "  description = ?, template_code = ?, article_code = ?, " .
696       "  output_numberformat = ?, output_dateformat = ?, " .
697       "  output_longdates = ? " .
698       "WHERE id = ?";
699     push(@values, $form->{id});
700   } else {
701     $query =
702       "INSERT INTO language (" .
703       "  description, template_code, article_code, " .
704       "  output_numberformat, output_dateformat, output_longdates" .
705       ") VALUES (?, ?, ?, ?, ?, ?)";
706   }
707   do_query($form, $dbh, $query, @values);
708
709   $dbh->disconnect;
710
711   $main::lxdebug->leave_sub();
712 }
713
714 sub delete_language {
715   $main::lxdebug->enter_sub();
716
717   my ($self, $myconfig, $form) = @_;
718   my $query;
719
720   # connect to database
721   my $dbh = $form->dbconnect_noauto($myconfig);
722
723   foreach my $table (qw(generic_translations units_language)) {
724     $query = qq|DELETE FROM $table WHERE language_id = ?|;
725     do_query($form, $dbh, $query, $form->{"id"});
726   }
727
728   $query = "DELETE FROM language WHERE id = ?";
729   do_query($form, $dbh, $query, $form->{"id"});
730
731   $dbh->commit();
732   $dbh->disconnect;
733
734   $main::lxdebug->leave_sub();
735 }
736
737
738 sub buchungsgruppe {
739   $main::lxdebug->enter_sub();
740
741   my ($self, $myconfig, $form) = @_;
742
743   # connect to database
744   my $dbh = $form->dbconnect($myconfig);
745
746   my $query = qq|SELECT id, description,
747                  inventory_accno_id,
748                  (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
749                  income_accno_id_0,
750                  (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
751                  expense_accno_id_0,
752                  (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
753                  income_accno_id_1,
754                  (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
755                  expense_accno_id_1,
756                  (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
757                  income_accno_id_2,
758                  (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
759                  expense_accno_id_2,
760                  (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
761                  income_accno_id_3,
762                  (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
763                  expense_accno_id_3,
764                  (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
765                  FROM buchungsgruppen
766                  ORDER BY sortkey|;
767
768   my $sth = $dbh->prepare($query);
769   $sth->execute || $form->dberror($query);
770
771   $form->{ALL} = [];
772   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
773     push @{ $form->{ALL} }, $ref;
774   }
775
776   $sth->finish;
777   $dbh->disconnect;
778
779   $main::lxdebug->leave_sub();
780 }
781
782 sub get_buchungsgruppe {
783   $main::lxdebug->enter_sub();
784
785   my ($self, $myconfig, $form) = @_;
786   my $query;
787
788   # connect to database
789   my $dbh = $form->dbconnect($myconfig);
790
791   if ($form->{id}) {
792     $query =
793       qq|SELECT description, inventory_accno_id,
794          (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
795          income_accno_id_0,
796          (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
797          expense_accno_id_0,
798          (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
799          income_accno_id_1,
800          (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
801          expense_accno_id_1,
802          (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
803          income_accno_id_2,
804          (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
805          expense_accno_id_2,
806          (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
807          income_accno_id_3,
808          (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
809          expense_accno_id_3,
810          (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
811          FROM buchungsgruppen
812          WHERE id = ?|;
813     my $sth = $dbh->prepare($query);
814     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
815
816     my $ref = $sth->fetchrow_hashref("NAME_lc");
817
818     map { $form->{$_} = $ref->{$_} } keys %$ref;
819
820     $sth->finish;
821
822     $query =
823       qq|SELECT count(id) = 0 AS orphaned
824          FROM parts
825          WHERE buchungsgruppen_id = ?|;
826     ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
827   }
828
829   $query = "SELECT inventory_accno_id, income_accno_id, expense_accno_id ".
830     "FROM defaults";
831   ($form->{"std_inventory_accno_id"}, $form->{"std_income_accno_id"},
832    $form->{"std_expense_accno_id"}) = selectrow_query($form, $dbh, $query);
833
834   my $module = "IC";
835   $query = qq|SELECT c.accno, c.description, c.link, c.id,
836               d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
837               FROM chart c, defaults d
838               WHERE c.link LIKE '%$module%'
839               ORDER BY c.accno|;
840
841
842   my $sth = $dbh->prepare($query);
843   $sth->execute || $form->dberror($query);
844   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
845     foreach my $key (split(/:/, $ref->{link})) {
846       if (!$form->{"std_inventory_accno_id"} && ($key eq "IC")) {
847         $form->{"std_inventory_accno_id"} = $ref->{"id"};
848       }
849       if ($key =~ /$module/) {
850         if (   ($ref->{id} eq $ref->{inventory_accno_id})
851             || ($ref->{id} eq $ref->{income_accno_id})
852             || ($ref->{id} eq $ref->{expense_accno_id})) {
853           push @{ $form->{"${module}_links"}{$key} },
854             { accno       => $ref->{accno},
855               description => $ref->{description},
856               selected    => "selected",
857               id          => $ref->{id} };
858         } else {
859           push @{ $form->{"${module}_links"}{$key} },
860             { accno       => $ref->{accno},
861               description => $ref->{description},
862               selected    => "",
863               id          => $ref->{id} };
864         }
865       }
866     }
867   }
868   $sth->finish;
869
870
871   $dbh->disconnect;
872
873   $main::lxdebug->leave_sub();
874 }
875
876 sub save_buchungsgruppe {
877   $main::lxdebug->enter_sub();
878
879   my ($self, $myconfig, $form) = @_;
880
881   # connect to database
882   my $dbh = $form->dbconnect($myconfig);
883
884   my @values = ($form->{description}, $form->{inventory_accno_id},
885                 $form->{income_accno_id_0}, $form->{expense_accno_id_0},
886                 $form->{income_accno_id_1}, $form->{expense_accno_id_1},
887                 $form->{income_accno_id_2}, $form->{expense_accno_id_2},
888                 $form->{income_accno_id_3}, $form->{expense_accno_id_3});
889
890   my $query;
891
892   # id is the old record
893   if ($form->{id}) {
894     $query = qq|UPDATE buchungsgruppen SET
895                 description = ?, inventory_accno_id = ?,
896                 income_accno_id_0 = ?, expense_accno_id_0 = ?,
897                 income_accno_id_1 = ?, expense_accno_id_1 = ?,
898                 income_accno_id_2 = ?, expense_accno_id_2 = ?,
899                 income_accno_id_3 = ?, expense_accno_id_3 = ?
900                 WHERE id = ?|;
901     push(@values, $form->{id});
902   } else {
903     $query = qq|SELECT COALESCE(MAX(sortkey) + 1, 1) FROM buchungsgruppen|;
904     my ($sortkey) = $dbh->selectrow_array($query);
905     $form->dberror($query) if ($dbh->err);
906     push(@values, $sortkey);
907     $query = qq|INSERT INTO buchungsgruppen
908                 (description, inventory_accno_id,
909                 income_accno_id_0, expense_accno_id_0,
910                 income_accno_id_1, expense_accno_id_1,
911                 income_accno_id_2, expense_accno_id_2,
912                 income_accno_id_3, expense_accno_id_3,
913                 sortkey)
914                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
915   }
916   do_query($form, $dbh, $query, @values);
917
918   $dbh->disconnect;
919
920   $main::lxdebug->leave_sub();
921 }
922
923 sub delete_buchungsgruppe {
924   $main::lxdebug->enter_sub();
925
926   my ($self, $myconfig, $form) = @_;
927
928   # connect to database
929   my $dbh = $form->dbconnect($myconfig);
930
931   my $query = qq|DELETE FROM buchungsgruppen WHERE id = ?|;
932   do_query($form, $dbh, $query, $form->{id});
933
934   $dbh->disconnect;
935
936   $main::lxdebug->leave_sub();
937 }
938
939 sub swap_sortkeys {
940   $main::lxdebug->enter_sub();
941
942   my ($self, $myconfig, $form, $table) = @_;
943
944   # connect to database
945   my $dbh = $form->get_standard_dbh($myconfig);
946
947   my $query =
948     qq|SELECT
949        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey1,
950        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey2|;
951   my @values   = ($form->{"id1"}, $form->{"id2"});
952   my @sortkeys = selectrow_query($form, $dbh, $query, @values);
953
954   $query  = qq|UPDATE $table SET sortkey = ? WHERE id = ?|;
955   my $sth = prepare_query($form, $dbh, $query);
956
957   do_statement($form, $sth, $query, $sortkeys[1], $form->{"id1"});
958   do_statement($form, $sth, $query, $sortkeys[0], $form->{"id2"});
959
960   $sth->finish();
961
962   $dbh->commit();
963
964   $main::lxdebug->leave_sub();
965 }
966
967 sub prepare_template_filename {
968   $main::lxdebug->enter_sub();
969
970   my ($self, $myconfig, $form) = @_;
971
972   my ($filename, $display_filename);
973
974   if ($form->{type} eq "stylesheet") {
975     $filename = "css/$myconfig->{stylesheet}";
976     $display_filename = $myconfig->{stylesheet};
977
978   } else {
979     $filename = $form->{formname};
980
981     if ($form->{language}) {
982       my ($id, $template_code) = split(/--/, $form->{language});
983       $filename .= "_${template_code}";
984     }
985
986     if ($form->{printer}) {
987       my ($id, $template_code) = split(/--/, $form->{printer});
988       $filename .= "_${template_code}";
989     }
990
991     $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
992     if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
993       $filename =~ s|.*/||;
994     }
995     $display_filename = $filename;
996     $filename = "$myconfig->{templates}/$filename";
997   }
998
999   $main::lxdebug->leave_sub();
1000
1001   return ($filename, $display_filename);
1002 }
1003
1004
1005 sub load_template {
1006   $main::lxdebug->enter_sub();
1007
1008   my ($self, $filename) = @_;
1009
1010   my ($content, $lines) = ("", 0);
1011
1012   local *TEMPLATE;
1013
1014   if (open(TEMPLATE, $filename)) {
1015     while (<TEMPLATE>) {
1016       $content .= $_;
1017       $lines++;
1018     }
1019     close(TEMPLATE);
1020   }
1021
1022   $content = Encode::decode('utf-8-strict', $content) if $::locale->is_utf8;
1023
1024   $main::lxdebug->leave_sub();
1025
1026   return ($content, $lines);
1027 }
1028
1029 sub save_template {
1030   $main::lxdebug->enter_sub();
1031
1032   my ($self, $filename, $content) = @_;
1033
1034   local *TEMPLATE;
1035
1036   my $error = "";
1037
1038   if (open(TEMPLATE, ">", $filename)) {
1039     $content = Encode::encode('utf-8-strict', $content) if $::locale->is_utf8;
1040     $content =~ s/\r\n/\n/g;
1041     print(TEMPLATE $content);
1042     close(TEMPLATE);
1043   } else {
1044     $error = $!;
1045   }
1046
1047   $main::lxdebug->leave_sub();
1048
1049   return $error;
1050 }
1051
1052 sub save_defaults {
1053   $main::lxdebug->enter_sub();
1054
1055   my $self     = shift;
1056   my %params   = @_;
1057
1058   my $myconfig = \%main::myconfig;
1059   my $form     = $main::form;
1060
1061   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1062
1063   my %accnos;
1064   map { ($accnos{$_}) = split(m/--/, $form->{$_}) } qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno ar_paid_accno);
1065
1066   $form->{curr}  =~ s/ //g;
1067   my @currencies =  grep { $_ ne '' } split m/:/, $form->{curr};
1068   my $currency   =  join ':', @currencies;
1069
1070   # these defaults are database wide
1071
1072   my $query =
1073     qq|UPDATE defaults SET
1074         inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?),
1075         income_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1076         expense_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1077         fxgain_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1078         fxloss_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1079         ar_paid_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1080         invnumber          = ?,
1081         cnnumber           = ?,
1082         sonumber           = ?,
1083         ponumber           = ?,
1084         sqnumber           = ?,
1085         rfqnumber          = ?,
1086         customernumber     = ?,
1087         vendornumber       = ?,
1088         articlenumber      = ?,
1089         servicenumber      = ?,
1090         sdonumber          = ?,
1091         pdonumber          = ?,
1092         curr               = ?,
1093         businessnumber     = ?,
1094         weightunit         = ?,
1095         language_id        = ?|;
1096   my @values = ($accnos{inventory_accno}, $accnos{income_accno}, $accnos{expense_accno},
1097                 $accnos{fxgain_accno},    $accnos{fxloss_accno}, $accnos{ar_paid_accno},
1098                 $form->{invnumber},       $form->{cnnumber},
1099                 $form->{sonumber},        $form->{ponumber},
1100                 $form->{sqnumber},        $form->{rfqnumber},
1101                 $form->{customernumber},  $form->{vendornumber},
1102                 $form->{articlenumber},   $form->{servicenumber},
1103                 $form->{sdonumber},       $form->{pdonumber},
1104                 $currency,
1105                 $form->{businessnumber},  $form->{weightunit},
1106                 conv_i($form->{language_id}));
1107   do_query($form, $dbh, $query, @values);
1108
1109   $dbh->commit();
1110
1111   $main::lxdebug->leave_sub();
1112 }
1113
1114
1115 sub save_preferences {
1116   $main::lxdebug->enter_sub();
1117
1118   my ($self, $myconfig, $form) = @_;
1119
1120   my $dbh = $form->get_standard_dbh($myconfig);
1121
1122   my ($currency, $businessnumber) = selectrow_query($form, $dbh, qq|SELECT curr, businessnumber FROM defaults|);
1123
1124   # update name
1125   my $query = qq|UPDATE employee SET name = ? WHERE login = ?|;
1126   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1127
1128   my $rc = $dbh->commit();
1129
1130   # save first currency in myconfig
1131   $currency               =~ s/:.*//;
1132   $form->{currency}       =  $currency;
1133
1134   $form->{businessnumber} =  $businessnumber;
1135
1136   $myconfig = User->new(login => $form->{login});
1137
1138   foreach my $item (keys %$form) {
1139     $myconfig->{$item} = $form->{$item};
1140   }
1141
1142   $myconfig->save_member;
1143
1144   my $auth = $main::auth;
1145
1146   $main::lxdebug->leave_sub();
1147
1148   return $rc;
1149 }
1150
1151 sub get_defaults {
1152   $main::lxdebug->enter_sub();
1153
1154   my $self     = shift;
1155   my %params   = @_;
1156
1157   my $myconfig = \%main::myconfig;
1158   my $form     = $main::form;
1159
1160   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1161
1162   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
1163
1164   $defaults->{weightunit} ||= 'kg';
1165
1166   $main::lxdebug->leave_sub();
1167
1168   return $defaults;
1169 }
1170
1171 sub defaultaccounts {
1172   $main::lxdebug->enter_sub();
1173
1174   my ($self, $myconfig, $form) = @_;
1175
1176   # connect to database
1177   my $dbh = $form->dbconnect($myconfig);
1178
1179   # get defaults from defaults table
1180   my $query = qq|SELECT * FROM defaults|;
1181   my $sth   = $dbh->prepare($query);
1182   $sth->execute || $form->dberror($query);
1183
1184   $form->{defaults}               = $sth->fetchrow_hashref("NAME_lc");
1185   $form->{defaults}{IC}           = $form->{defaults}{inventory_accno_id};
1186   $form->{defaults}{IC_income}    = $form->{defaults}{income_accno_id};
1187   $form->{defaults}{IC_expense}   = $form->{defaults}{expense_accno_id};
1188   $form->{defaults}{FX_gain}      = $form->{defaults}{fxgain_accno_id};
1189   $form->{defaults}{FX_loss}      = $form->{defaults}{fxloss_accno_id};
1190   $form->{defaults}{AR_paid}      = $form->{defaults}{ar_paid_accno_id};
1191
1192   $form->{defaults}{weightunit} ||= 'kg';
1193
1194   $sth->finish;
1195
1196   $query = qq|SELECT c.id, c.accno, c.description, c.link
1197               FROM chart c
1198               WHERE c.link LIKE '%IC%'
1199               ORDER BY c.accno|;
1200   $sth = $dbh->prepare($query);
1201   $sth->execute || $self->dberror($query);
1202
1203   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1204     foreach my $key (split(/:/, $ref->{link})) {
1205       if ($key =~ /IC/) {
1206         my $nkey = $key;
1207         if ($key =~ /cogs/) {
1208           $nkey = "IC_expense";
1209         }
1210         if ($key =~ /sale/) {
1211           $nkey = "IC_income";
1212         }
1213         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1214                                              id          => $ref->{id},
1215                                              description => $ref->{description}
1216         );
1217       }
1218     }
1219   }
1220   $sth->finish;
1221
1222   $query = qq|SELECT c.id, c.accno, c.description
1223               FROM chart c
1224               WHERE c.category = 'I'
1225               AND c.charttype = 'A'
1226               ORDER BY c.accno|;
1227   $sth = $dbh->prepare($query);
1228   $sth->execute || $self->dberror($query);
1229
1230   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1231     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1232                                              id          => $ref->{id},
1233                                              description => $ref->{description}
1234     );
1235   }
1236   $sth->finish;
1237
1238   $query = qq|SELECT c.id, c.accno, c.description
1239               FROM chart c
1240               WHERE c.category = 'E'
1241               AND c.charttype = 'A'
1242               ORDER BY c.accno|;
1243   $sth = $dbh->prepare($query);
1244   $sth->execute || $self->dberror($query);
1245
1246   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1247     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1248                                              id          => $ref->{id},
1249                                              description => $ref->{description}
1250     );
1251   }
1252   $sth->finish;
1253
1254   # now get the tax rates and numbers
1255   $query = qq|SELECT c.id, c.accno, c.description,
1256               t.rate * 100 AS rate, t.taxnumber
1257               FROM chart c, tax t
1258               WHERE c.id = t.chart_id|;
1259
1260   $sth = $dbh->prepare($query);
1261   $sth->execute || $form->dberror($query);
1262
1263   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1264     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1265     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1266     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1267       if $ref->{taxnumber};
1268     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1269   }
1270   # Abfrage für Standard Umlaufvermögenskonto
1271   $query =
1272     qq|SELECT id, accno, description, link | .
1273     qq|FROM chart | .
1274     qq|WHERE link LIKE ? |.
1275     qq|ORDER BY accno|;
1276   $sth = prepare_execute_query($form, $dbh, $query, '%AR%');
1277   $sth->execute || $form->dberror($query);#
1278   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1279     foreach my $item (split(/:/, $ref->{link})) {
1280       if ($item eq "AR_paid") {
1281         %{ $form->{IC}{AR_paid}{ $ref->{accno} } } = (
1282                                              id          => $ref->{id},
1283                                              description => $ref->{description}
1284           );
1285       }
1286     }
1287   }
1288
1289   $sth->finish;
1290   $dbh->disconnect;
1291
1292   $main::lxdebug->leave_sub();
1293 }
1294
1295 sub closedto {
1296   $main::lxdebug->enter_sub();
1297
1298   my ($self, $myconfig, $form) = @_;
1299
1300   my $dbh = $form->dbconnect($myconfig);
1301
1302   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1303   my $sth   = $dbh->prepare($query);
1304   $sth->execute || $form->dberror($query);
1305
1306   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1307
1308   $sth->finish;
1309
1310   $dbh->disconnect;
1311
1312   $main::lxdebug->leave_sub();
1313 }
1314
1315 sub closebooks {
1316   $main::lxdebug->enter_sub();
1317
1318   my ($self, $myconfig, $form) = @_;
1319
1320   my $dbh = $form->dbconnect($myconfig);
1321
1322   my ($query, @values);
1323
1324   if ($form->{revtrans}) {
1325     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1326
1327   } elsif ($form->{closedto}) {
1328     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1329     @values = (conv_date($form->{closedto}));
1330
1331   } else {
1332     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1333   }
1334
1335   # set close in defaults
1336   do_query($form, $dbh, $query, @values);
1337
1338   $dbh->disconnect;
1339
1340   $main::lxdebug->leave_sub();
1341 }
1342
1343 sub get_base_unit {
1344   my ($self, $units, $unit_name, $factor) = @_;
1345
1346   $factor = 1 unless ($factor);
1347
1348   my $unit = $units->{$unit_name};
1349
1350   if (!defined($unit) || !$unit->{"base_unit"} ||
1351       ($unit_name eq $unit->{"base_unit"})) {
1352     return ($unit_name, $factor);
1353   }
1354
1355   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1356 }
1357
1358 sub retrieve_units {
1359   $main::lxdebug->enter_sub();
1360
1361   my ($self, $myconfig, $form, $prefix) = @_;
1362   $prefix ||= '';
1363
1364   my $dbh = $form->get_standard_dbh;
1365
1366   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1367
1368   my $sth = prepare_execute_query($form, $dbh, $query);
1369
1370   my $units = {};
1371   while (my $ref = $sth->fetchrow_hashref()) {
1372     $units->{$ref->{"name"}} = $ref;
1373   }
1374   $sth->finish();
1375
1376   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1377   $sth = $dbh->prepare($query_lang);
1378   $sth->execute() || $form->dberror($query_lang);
1379   my @languages;
1380   while (my $ref = $sth->fetchrow_hashref()) {
1381     push(@languages, $ref);
1382   }
1383   $sth->finish();
1384
1385   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1386     "FROM units_language ul " .
1387     "LEFT JOIN language l ON ul.language_id = l.id " .
1388     "WHERE ul.unit = ?";
1389   $sth = $dbh->prepare($query_lang);
1390
1391   foreach my $unit (values(%{$units})) {
1392     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1393
1394     $unit->{"LANGUAGES"} = {};
1395     foreach my $lang (@languages) {
1396       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1397     }
1398
1399     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1400     while (my $ref = $sth->fetchrow_hashref()) {
1401       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1402     }
1403   }
1404   $sth->finish;
1405
1406   $main::lxdebug->leave_sub();
1407
1408   return $units;
1409 }
1410
1411 sub retrieve_all_units {
1412   $main::lxdebug->enter_sub();
1413
1414   my $self = shift;
1415
1416   if (!$::request->{cache}{all_units}) {
1417     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
1418   }
1419
1420   $main::lxdebug->leave_sub();
1421
1422   return $::request->{cache}{all_units};
1423 }
1424
1425
1426 sub translate_units {
1427   $main::lxdebug->enter_sub();
1428
1429   my ($self, $form, $template_code, $unit, $amount) = @_;
1430
1431   my $units = $self->retrieve_units(\%main::myconfig, $form);
1432
1433   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1434   my $new_unit = $unit;
1435   if ($h) {
1436     if (($amount != 1) && $h->{"localized_plural"}) {
1437       $new_unit = $h->{"localized_plural"};
1438     } elsif ($h->{"localized"}) {
1439       $new_unit = $h->{"localized"};
1440     }
1441   }
1442
1443   $main::lxdebug->leave_sub();
1444
1445   return $new_unit;
1446 }
1447
1448 sub units_in_use {
1449   $main::lxdebug->enter_sub();
1450
1451   my ($self, $myconfig, $form, $units) = @_;
1452
1453   my $dbh = $form->dbconnect($myconfig);
1454
1455   map({ $_->{"in_use"} = 0; } values(%{$units}));
1456
1457   foreach my $unit (values(%{$units})) {
1458     my $base_unit = $unit->{"original_base_unit"};
1459     while ($base_unit) {
1460       $units->{$base_unit}->{"in_use"} = 1;
1461       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1462       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1463       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1464     }
1465   }
1466
1467   foreach my $unit (values(%{$units})) {
1468     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1469
1470     foreach my $table (qw(parts invoice orderitems)) {
1471       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1472
1473       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1474         $query .= "= " . $dbh->quote($unit->{"name"});
1475       } else {
1476         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1477           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1478       }
1479
1480       my ($count) = $dbh->selectrow_array($query);
1481       $form->dberror($query) if ($dbh->err);
1482
1483       if ($count) {
1484         $unit->{"in_use"} = 1;
1485         last;
1486       }
1487     }
1488   }
1489
1490   $dbh->disconnect();
1491
1492   $main::lxdebug->leave_sub();
1493 }
1494
1495 sub convertible_units {
1496   $main::lxdebug->enter_sub();
1497
1498   my $self        = shift;
1499   my $units       = shift;
1500   my $filter_unit = shift;
1501   my $not_smaller = shift;
1502
1503   my $conv_units = [];
1504
1505   $filter_unit = $units->{$filter_unit};
1506
1507   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1508     my $unit = $units->{$name};
1509
1510     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1511         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1512       push @{$conv_units}, $unit;
1513     }
1514   }
1515
1516   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1517
1518   $main::lxdebug->leave_sub();
1519
1520   return \@sorted;
1521 }
1522
1523 # if $a is translatable to $b, return the factor between them.
1524 # else return 1
1525 sub convert_unit {
1526   $main::lxdebug->enter_sub(2);
1527   my ($this, $a, $b, $all_units) = @_;
1528
1529   if (!$all_units) {
1530     $all_units = $this->retrieve_all_units;
1531   }
1532
1533   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1534   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1535   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1536   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1537 }
1538
1539 sub unit_select_data {
1540   $main::lxdebug->enter_sub();
1541
1542   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1543
1544   my $select = [];
1545
1546   if ($empty_entry) {
1547     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1548   }
1549
1550   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1551     if (!$convertible_into ||
1552         ($units->{$convertible_into} &&
1553          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1554       push @{$select}, { "name"      => $unit,
1555                          "base_unit" => $units->{$unit}->{"base_unit"},
1556                          "factor"    => $units->{$unit}->{"factor"},
1557                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1558     }
1559   }
1560
1561   $main::lxdebug->leave_sub();
1562
1563   return $select;
1564 }
1565
1566 sub unit_select_html {
1567   $main::lxdebug->enter_sub();
1568
1569   my ($self, $units, $name, $selected, $convertible_into) = @_;
1570
1571   my $select = "<select name=${name}>";
1572
1573   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1574     if (!$convertible_into ||
1575         ($units->{$convertible_into} &&
1576          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1577       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1578     }
1579   }
1580   $select .= "</select>";
1581
1582   $main::lxdebug->leave_sub();
1583
1584   return $select;
1585 }
1586
1587 sub sum_with_unit {
1588   $main::lxdebug->enter_sub();
1589
1590   my $self  = shift;
1591
1592   my $units = $self->retrieve_all_units();
1593
1594   my $sum   = 0;
1595   my $base_unit;
1596
1597   while (2 <= scalar(@_)) {
1598     my $qty  = shift(@_);
1599     my $unit = $units->{shift(@_)};
1600
1601     croak "No unit defined with name $unit" if (!defined $unit);
1602
1603     if (!$base_unit) {
1604       $base_unit = $unit->{base_unit};
1605     } elsif ($base_unit ne $unit->{base_unit}) {
1606       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1607     }
1608
1609     $sum += $qty * $unit->{factor};
1610   }
1611
1612   $main::lxdebug->leave_sub();
1613
1614   return wantarray ? ($sum, $base_unit) : $sum;
1615 }
1616
1617 sub add_unit {
1618   $main::lxdebug->enter_sub();
1619
1620   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1621
1622   my $dbh = $form->dbconnect_noauto($myconfig);
1623
1624   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1625   my ($sortkey) = selectrow_query($form, $dbh, $query);
1626
1627   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1628     "VALUES (?, ?, ?, ?)";
1629   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1630
1631   if ($languages) {
1632     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1633     my $sth = $dbh->prepare($query);
1634     foreach my $lang (@{$languages}) {
1635       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1636       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1637     }
1638     $sth->finish();
1639   }
1640
1641   $dbh->commit();
1642   $dbh->disconnect();
1643
1644   $main::lxdebug->leave_sub();
1645 }
1646
1647 sub save_units {
1648   $main::lxdebug->enter_sub();
1649
1650   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1651
1652   my $dbh = $form->dbconnect_noauto($myconfig);
1653
1654   my ($base_unit, $unit, $sth, $query);
1655
1656   $query = "DELETE FROM units_language";
1657   $dbh->do($query) || $form->dberror($query);
1658
1659   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1660     $query = "DELETE FROM units WHERE name IN (";
1661     map({ $query .= "?," } @{$delete_units});
1662     substr($query, -1, 1) = ")";
1663     $dbh->do($query, undef, @{$delete_units}) ||
1664       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1665   }
1666
1667   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1668   $sth = $dbh->prepare($query);
1669
1670   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1671   my $sth_lang = $dbh->prepare($query_lang);
1672
1673   foreach $unit (values(%{$units})) {
1674     $unit->{"depth"} = 0;
1675     my $base_unit = $unit;
1676     while ($base_unit->{"base_unit"}) {
1677       $unit->{"depth"}++;
1678       $base_unit = $units->{$base_unit->{"base_unit"}};
1679     }
1680   }
1681
1682   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1683     if ($unit->{"LANGUAGES"}) {
1684       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1685         next unless ($lang->{"id"} && $lang->{"localized"});
1686         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1687         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1688       }
1689     }
1690
1691     next if ($unit->{"unchanged_unit"});
1692
1693     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1694     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1695   }
1696
1697   $sth->finish();
1698   $sth_lang->finish();
1699   $dbh->commit();
1700   $dbh->disconnect();
1701
1702   $main::lxdebug->leave_sub();
1703 }
1704
1705 sub taxes {
1706   $main::lxdebug->enter_sub();
1707
1708   my ($self, $myconfig, $form) = @_;
1709
1710   # connect to database
1711   my $dbh = $form->dbconnect($myconfig);
1712
1713   my $query = qq|SELECT
1714                    t.id,
1715                    t.taxkey,
1716                    t.taxdescription,
1717                    round(t.rate * 100, 2) AS rate,
1718                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1719                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
1720                  FROM tax t
1721                  ORDER BY taxkey|;
1722
1723   my $sth = $dbh->prepare($query);
1724   $sth->execute || $form->dberror($query);
1725
1726   $form->{TAX} = [];
1727   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1728     push @{ $form->{TAX} }, $ref;
1729   }
1730
1731   $sth->finish;
1732   $dbh->disconnect;
1733
1734   $main::lxdebug->leave_sub();
1735 }
1736
1737 sub get_tax_accounts {
1738   $main::lxdebug->enter_sub();
1739
1740   my ($self, $myconfig, $form) = @_;
1741
1742   my $dbh = $form->dbconnect($myconfig);
1743
1744   # get Accounts from chart
1745   my $query = qq{ SELECT
1746                  id,
1747                  accno || ' - ' || description AS taxaccount
1748                FROM chart
1749                WHERE link LIKE '%_tax%'
1750                ORDER BY accno
1751              };
1752
1753   my $sth = $dbh->prepare($query);
1754   $sth->execute || $form->dberror($query);
1755
1756   $form->{ACCOUNTS} = [];
1757   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1758     push @{ $form->{ACCOUNTS} }, $ref;
1759   }
1760
1761   $sth->finish;
1762
1763   $dbh->disconnect;
1764
1765   $main::lxdebug->leave_sub();
1766 }
1767
1768 sub get_tax {
1769   $main::lxdebug->enter_sub();
1770
1771   my ($self, $myconfig, $form) = @_;
1772
1773   # connect to database
1774   my $dbh = $form->dbconnect($myconfig);
1775
1776   my $query = qq|SELECT
1777                    taxkey,
1778                    taxdescription,
1779                    round(rate * 100, 2) AS rate,
1780                    chart_id,
1781                    (id IN (SELECT tax_id
1782                            FROM acc_trans)) AS tax_already_used
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;