Erstelle Tabelle currencies
[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
1291   #Get currencies:
1292   $query = qq|SELECT curr FROM currencies ORDER BY id|;
1293
1294   $form->{CURRENCIES} = [];
1295
1296   $sth = prepare_execute_query($form, $dbh, $query);
1297   $sth->execute || $form->dberror($query);
1298   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1299     push @{ $form->{ CURRENCIES } } , $ref;
1300   }
1301   $sth->finish;
1302
1303   #Which of them is the default currency?
1304   $query = qq|SELECT curr AS defaultcurrency FROM currencies WHERE id = (SELECT curr FROM defaults LIMIT 1);|;
1305   $sth   = $dbh->prepare($query);
1306   $sth->execute || $form->dberror($query);
1307
1308   $form->{defaultcurrency}               = ($sth->fetchrow_hashref("NAME_lc"))->{defaultcurrency};
1309
1310   $sth->finish;
1311
1312   $dbh->disconnect;
1313
1314   $main::lxdebug->leave_sub();
1315 }
1316
1317 sub closedto {
1318   $main::lxdebug->enter_sub();
1319
1320   my ($self, $myconfig, $form) = @_;
1321
1322   my $dbh = $form->dbconnect($myconfig);
1323
1324   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1325   my $sth   = $dbh->prepare($query);
1326   $sth->execute || $form->dberror($query);
1327
1328   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1329
1330   $sth->finish;
1331
1332   $dbh->disconnect;
1333
1334   $main::lxdebug->leave_sub();
1335 }
1336
1337 sub closebooks {
1338   $main::lxdebug->enter_sub();
1339
1340   my ($self, $myconfig, $form) = @_;
1341
1342   my $dbh = $form->dbconnect($myconfig);
1343
1344   my ($query, @values);
1345
1346   if ($form->{revtrans}) {
1347     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1348
1349   } elsif ($form->{closedto}) {
1350     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1351     @values = (conv_date($form->{closedto}));
1352
1353   } else {
1354     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1355   }
1356
1357   # set close in defaults
1358   do_query($form, $dbh, $query, @values);
1359
1360   $dbh->disconnect;
1361
1362   $main::lxdebug->leave_sub();
1363 }
1364
1365 sub get_base_unit {
1366   my ($self, $units, $unit_name, $factor) = @_;
1367
1368   $factor = 1 unless ($factor);
1369
1370   my $unit = $units->{$unit_name};
1371
1372   if (!defined($unit) || !$unit->{"base_unit"} ||
1373       ($unit_name eq $unit->{"base_unit"})) {
1374     return ($unit_name, $factor);
1375   }
1376
1377   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1378 }
1379
1380 sub retrieve_units {
1381   $main::lxdebug->enter_sub();
1382
1383   my ($self, $myconfig, $form, $prefix) = @_;
1384   $prefix ||= '';
1385
1386   my $dbh = $form->get_standard_dbh;
1387
1388   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1389
1390   my $sth = prepare_execute_query($form, $dbh, $query);
1391
1392   my $units = {};
1393   while (my $ref = $sth->fetchrow_hashref()) {
1394     $units->{$ref->{"name"}} = $ref;
1395   }
1396   $sth->finish();
1397
1398   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1399   $sth = $dbh->prepare($query_lang);
1400   $sth->execute() || $form->dberror($query_lang);
1401   my @languages;
1402   while (my $ref = $sth->fetchrow_hashref()) {
1403     push(@languages, $ref);
1404   }
1405   $sth->finish();
1406
1407   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1408     "FROM units_language ul " .
1409     "LEFT JOIN language l ON ul.language_id = l.id " .
1410     "WHERE ul.unit = ?";
1411   $sth = $dbh->prepare($query_lang);
1412
1413   foreach my $unit (values(%{$units})) {
1414     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1415
1416     $unit->{"LANGUAGES"} = {};
1417     foreach my $lang (@languages) {
1418       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1419     }
1420
1421     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1422     while (my $ref = $sth->fetchrow_hashref()) {
1423       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1424     }
1425   }
1426   $sth->finish;
1427
1428   $main::lxdebug->leave_sub();
1429
1430   return $units;
1431 }
1432
1433 sub retrieve_all_units {
1434   $main::lxdebug->enter_sub();
1435
1436   my $self = shift;
1437
1438   if (!$::request->{cache}{all_units}) {
1439     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
1440   }
1441
1442   $main::lxdebug->leave_sub();
1443
1444   return $::request->{cache}{all_units};
1445 }
1446
1447
1448 sub translate_units {
1449   $main::lxdebug->enter_sub();
1450
1451   my ($self, $form, $template_code, $unit, $amount) = @_;
1452
1453   my $units = $self->retrieve_units(\%main::myconfig, $form);
1454
1455   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1456   my $new_unit = $unit;
1457   if ($h) {
1458     if (($amount != 1) && $h->{"localized_plural"}) {
1459       $new_unit = $h->{"localized_plural"};
1460     } elsif ($h->{"localized"}) {
1461       $new_unit = $h->{"localized"};
1462     }
1463   }
1464
1465   $main::lxdebug->leave_sub();
1466
1467   return $new_unit;
1468 }
1469
1470 sub units_in_use {
1471   $main::lxdebug->enter_sub();
1472
1473   my ($self, $myconfig, $form, $units) = @_;
1474
1475   my $dbh = $form->dbconnect($myconfig);
1476
1477   map({ $_->{"in_use"} = 0; } values(%{$units}));
1478
1479   foreach my $unit (values(%{$units})) {
1480     my $base_unit = $unit->{"original_base_unit"};
1481     while ($base_unit) {
1482       $units->{$base_unit}->{"in_use"} = 1;
1483       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1484       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1485       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1486     }
1487   }
1488
1489   foreach my $unit (values(%{$units})) {
1490     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1491
1492     foreach my $table (qw(parts invoice orderitems)) {
1493       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1494
1495       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1496         $query .= "= " . $dbh->quote($unit->{"name"});
1497       } else {
1498         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1499           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1500       }
1501
1502       my ($count) = $dbh->selectrow_array($query);
1503       $form->dberror($query) if ($dbh->err);
1504
1505       if ($count) {
1506         $unit->{"in_use"} = 1;
1507         last;
1508       }
1509     }
1510   }
1511
1512   $dbh->disconnect();
1513
1514   $main::lxdebug->leave_sub();
1515 }
1516
1517 sub convertible_units {
1518   $main::lxdebug->enter_sub();
1519
1520   my $self        = shift;
1521   my $units       = shift;
1522   my $filter_unit = shift;
1523   my $not_smaller = shift;
1524
1525   my $conv_units = [];
1526
1527   $filter_unit = $units->{$filter_unit};
1528
1529   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1530     my $unit = $units->{$name};
1531
1532     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1533         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1534       push @{$conv_units}, $unit;
1535     }
1536   }
1537
1538   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1539
1540   $main::lxdebug->leave_sub();
1541
1542   return \@sorted;
1543 }
1544
1545 # if $a is translatable to $b, return the factor between them.
1546 # else return 1
1547 sub convert_unit {
1548   $main::lxdebug->enter_sub(2);
1549   my ($this, $a, $b, $all_units) = @_;
1550
1551   if (!$all_units) {
1552     $all_units = $this->retrieve_all_units;
1553   }
1554
1555   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1556   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1557   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1558   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1559 }
1560
1561 sub unit_select_data {
1562   $main::lxdebug->enter_sub();
1563
1564   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1565
1566   my $select = [];
1567
1568   if ($empty_entry) {
1569     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1570   }
1571
1572   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1573     if (!$convertible_into ||
1574         ($units->{$convertible_into} &&
1575          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1576       push @{$select}, { "name"      => $unit,
1577                          "base_unit" => $units->{$unit}->{"base_unit"},
1578                          "factor"    => $units->{$unit}->{"factor"},
1579                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1580     }
1581   }
1582
1583   $main::lxdebug->leave_sub();
1584
1585   return $select;
1586 }
1587
1588 sub unit_select_html {
1589   $main::lxdebug->enter_sub();
1590
1591   my ($self, $units, $name, $selected, $convertible_into) = @_;
1592
1593   my $select = "<select name=${name}>";
1594
1595   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1596     if (!$convertible_into ||
1597         ($units->{$convertible_into} &&
1598          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1599       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1600     }
1601   }
1602   $select .= "</select>";
1603
1604   $main::lxdebug->leave_sub();
1605
1606   return $select;
1607 }
1608
1609 sub sum_with_unit {
1610   $main::lxdebug->enter_sub();
1611
1612   my $self  = shift;
1613
1614   my $units = $self->retrieve_all_units();
1615
1616   my $sum   = 0;
1617   my $base_unit;
1618
1619   while (2 <= scalar(@_)) {
1620     my $qty  = shift(@_);
1621     my $unit = $units->{shift(@_)};
1622
1623     croak "No unit defined with name $unit" if (!defined $unit);
1624
1625     if (!$base_unit) {
1626       $base_unit = $unit->{base_unit};
1627     } elsif ($base_unit ne $unit->{base_unit}) {
1628       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1629     }
1630
1631     $sum += $qty * $unit->{factor};
1632   }
1633
1634   $main::lxdebug->leave_sub();
1635
1636   return wantarray ? ($sum, $base_unit) : $sum;
1637 }
1638
1639 sub add_unit {
1640   $main::lxdebug->enter_sub();
1641
1642   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1643
1644   my $dbh = $form->dbconnect_noauto($myconfig);
1645
1646   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1647   my ($sortkey) = selectrow_query($form, $dbh, $query);
1648
1649   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1650     "VALUES (?, ?, ?, ?)";
1651   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1652
1653   if ($languages) {
1654     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1655     my $sth = $dbh->prepare($query);
1656     foreach my $lang (@{$languages}) {
1657       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1658       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1659     }
1660     $sth->finish();
1661   }
1662
1663   $dbh->commit();
1664   $dbh->disconnect();
1665
1666   $main::lxdebug->leave_sub();
1667 }
1668
1669 sub save_units {
1670   $main::lxdebug->enter_sub();
1671
1672   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1673
1674   my $dbh = $form->dbconnect_noauto($myconfig);
1675
1676   my ($base_unit, $unit, $sth, $query);
1677
1678   $query = "DELETE FROM units_language";
1679   $dbh->do($query) || $form->dberror($query);
1680
1681   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1682     $query = "DELETE FROM units WHERE name IN (";
1683     map({ $query .= "?," } @{$delete_units});
1684     substr($query, -1, 1) = ")";
1685     $dbh->do($query, undef, @{$delete_units}) ||
1686       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1687   }
1688
1689   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1690   $sth = $dbh->prepare($query);
1691
1692   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1693   my $sth_lang = $dbh->prepare($query_lang);
1694
1695   foreach $unit (values(%{$units})) {
1696     $unit->{"depth"} = 0;
1697     my $base_unit = $unit;
1698     while ($base_unit->{"base_unit"}) {
1699       $unit->{"depth"}++;
1700       $base_unit = $units->{$base_unit->{"base_unit"}};
1701     }
1702   }
1703
1704   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1705     if ($unit->{"LANGUAGES"}) {
1706       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1707         next unless ($lang->{"id"} && $lang->{"localized"});
1708         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1709         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1710       }
1711     }
1712
1713     next if ($unit->{"unchanged_unit"});
1714
1715     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1716     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1717   }
1718
1719   $sth->finish();
1720   $sth_lang->finish();
1721   $dbh->commit();
1722   $dbh->disconnect();
1723
1724   $main::lxdebug->leave_sub();
1725 }
1726
1727 sub taxes {
1728   $main::lxdebug->enter_sub();
1729
1730   my ($self, $myconfig, $form) = @_;
1731
1732   # connect to database
1733   my $dbh = $form->dbconnect($myconfig);
1734
1735   my $query = qq|SELECT
1736                    t.id,
1737                    t.taxkey,
1738                    t.taxdescription,
1739                    round(t.rate * 100, 2) AS rate,
1740                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1741                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
1742                  FROM tax t
1743                  ORDER BY taxkey|;
1744
1745   my $sth = $dbh->prepare($query);
1746   $sth->execute || $form->dberror($query);
1747
1748   $form->{TAX} = [];
1749   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1750     push @{ $form->{TAX} }, $ref;
1751   }
1752
1753   $sth->finish;
1754   $dbh->disconnect;
1755
1756   $main::lxdebug->leave_sub();
1757 }
1758
1759 sub get_tax_accounts {
1760   $main::lxdebug->enter_sub();
1761
1762   my ($self, $myconfig, $form) = @_;
1763
1764   my $dbh = $form->dbconnect($myconfig);
1765
1766   # get Accounts from chart
1767   my $query = qq{ SELECT
1768                  id,
1769                  accno || ' - ' || description AS taxaccount
1770                FROM chart
1771                WHERE link LIKE '%_tax%'
1772                ORDER BY accno
1773              };
1774
1775   my $sth = $dbh->prepare($query);
1776   $sth->execute || $form->dberror($query);
1777
1778   $form->{ACCOUNTS} = [];
1779   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1780     push @{ $form->{ACCOUNTS} }, $ref;
1781   }
1782
1783   $sth->finish;
1784
1785   $dbh->disconnect;
1786
1787   $main::lxdebug->leave_sub();
1788 }
1789
1790 sub get_tax {
1791   $main::lxdebug->enter_sub();
1792
1793   my ($self, $myconfig, $form) = @_;
1794
1795   # connect to database
1796   my $dbh = $form->dbconnect($myconfig);
1797
1798   my $query = qq|SELECT
1799                    taxkey,
1800                    taxdescription,
1801                    round(rate * 100, 2) AS rate,
1802                    chart_id,
1803                    (id IN (SELECT tax_id
1804                            FROM acc_trans)) AS tax_already_used
1805                  FROM tax
1806                  WHERE id = ? |;
1807
1808   my $sth = $dbh->prepare($query);
1809   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1810
1811   my $ref = $sth->fetchrow_hashref("NAME_lc");
1812
1813   map { $form->{$_} = $ref->{$_} } keys %$ref;
1814
1815   $sth->finish;
1816
1817   # see if it is used by a taxkey
1818   $query = qq|SELECT count(*) FROM taxkeys
1819               WHERE tax_id = ? AND chart_id >0|;
1820
1821   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1822
1823   $form->{orphaned} = !$form->{orphaned};
1824   $sth->finish;
1825
1826   if (!$form->{orphaned} ) {
1827     $query = qq|SELECT DISTINCT c.id, c.accno
1828                 FROM taxkeys tk
1829                 JOIN   tax t ON (t.id = tk.tax_id)
1830                 JOIN chart c ON (c.id = tk.chart_id)
1831                 WHERE tk.tax_id = ?|;
1832
1833     $sth = $dbh->prepare($query);
1834     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1835
1836     $form->{TAXINUSE} = [];
1837     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1838       push @{ $form->{TAXINUSE} }, $ref;
1839     }
1840
1841     $sth->finish;
1842   }
1843
1844   $dbh->disconnect;
1845
1846   $main::lxdebug->leave_sub();
1847 }
1848
1849 sub save_tax {
1850   $main::lxdebug->enter_sub();
1851
1852   my ($self, $myconfig, $form) = @_;
1853   my $query;
1854
1855   # connect to database
1856   my $dbh = $form->get_standard_dbh($myconfig);
1857
1858   $form->{rate} = $form->{rate} / 100;
1859
1860   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
1861   if ($form->{id} ne "") {
1862     $query = qq|UPDATE tax SET
1863                   taxkey         = ?,
1864                   taxdescription = ?,
1865                   rate           = ?,
1866                   chart_id       = ?,
1867                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
1868                 WHERE id = ?|;
1869     push(@values, $form->{id});
1870
1871   } else {
1872     #ok
1873     $query = qq|INSERT INTO tax (
1874                   taxkey,
1875                   taxdescription,
1876                   rate,
1877                   chart_id,
1878                   taxnumber
1879                 )
1880                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
1881   }
1882   do_query($form, $dbh, $query, @values);
1883
1884   $dbh->commit();
1885
1886   $main::lxdebug->leave_sub();
1887 }
1888
1889 sub delete_tax {
1890   $main::lxdebug->enter_sub();
1891
1892   my ($self, $myconfig, $form) = @_;
1893   my $query;
1894
1895   # connect to database
1896   my $dbh = $form->get_standard_dbh($myconfig);
1897
1898   $query = qq|DELETE FROM tax
1899               WHERE id = ?|;
1900   do_query($form, $dbh, $query, $form->{id});
1901
1902   $dbh->commit();
1903
1904   $main::lxdebug->leave_sub();
1905 }
1906
1907 sub save_price_factor {
1908   $main::lxdebug->enter_sub();
1909
1910   my ($self, $myconfig, $form) = @_;
1911
1912   # connect to database
1913   my $dbh = $form->get_standard_dbh($myconfig);
1914
1915   my $query;
1916   my @values = ($form->{description}, conv_i($form->{factor}));
1917
1918   if ($form->{id}) {
1919     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1920     push @values, conv_i($form->{id});
1921
1922   } else {
1923     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1924   }
1925
1926   do_query($form, $dbh, $query, @values);
1927
1928   $dbh->commit();
1929
1930   $main::lxdebug->leave_sub();
1931 }
1932
1933 sub get_all_price_factors {
1934   $main::lxdebug->enter_sub();
1935
1936   my ($self, $myconfig, $form) = @_;
1937
1938   # connect to database
1939   my $dbh = $form->get_standard_dbh($myconfig);
1940
1941   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1942
1943   $main::lxdebug->leave_sub();
1944 }
1945
1946 sub get_price_factor {
1947   $main::lxdebug->enter_sub();
1948
1949   my ($self, $myconfig, $form) = @_;
1950
1951   # connect to database
1952   my $dbh = $form->get_standard_dbh($myconfig);
1953
1954   my $query = qq|SELECT description, factor,
1955                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
1956                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
1957                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1958                  FROM price_factors WHERE id = ?|;
1959
1960   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1961
1962   $main::lxdebug->leave_sub();
1963 }
1964
1965 sub delete_price_factor {
1966   $main::lxdebug->enter_sub();
1967
1968   my ($self, $myconfig, $form) = @_;
1969
1970   # connect to database
1971   my $dbh = $form->get_standard_dbh($myconfig);
1972
1973   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1974   $dbh->commit();
1975
1976   $main::lxdebug->leave_sub();
1977 }
1978
1979 sub save_warehouse {
1980   $main::lxdebug->enter_sub();
1981
1982   my ($self, $myconfig, $form) = @_;
1983
1984   # connect to database
1985   my $dbh = $form->get_standard_dbh($myconfig);
1986
1987   my ($query, @values, $sth);
1988
1989   if (!$form->{id}) {
1990     $query        = qq|SELECT nextval('id')|;
1991     ($form->{id}) = selectrow_query($form, $dbh, $query);
1992
1993     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1994     do_query($form, $dbh, $query, $form->{id});
1995   }
1996
1997   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1998            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1999
2000   if (0 < $form->{number_of_new_bins}) {
2001     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
2002     $sth   = prepare_query($form, $dbh, $query);
2003
2004     foreach my $i (1..$form->{number_of_new_bins}) {
2005       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
2006     }
2007
2008     $sth->finish();
2009   }
2010
2011   $dbh->commit();
2012
2013   $main::lxdebug->leave_sub();
2014 }
2015
2016 sub save_bins {
2017   $main::lxdebug->enter_sub();
2018
2019   my ($self, $myconfig, $form) = @_;
2020
2021   # connect to database
2022   my $dbh = $form->get_standard_dbh($myconfig);
2023
2024   my ($query, @values, $commit_necessary, $sth);
2025
2026   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
2027
2028   if (@values) {
2029     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
2030     do_query($form, $dbh, $query, @values);
2031
2032     $commit_necessary = 1;
2033   }
2034
2035   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
2036   $sth   = prepare_query($form, $dbh, $query);
2037
2038   foreach my $row (1..$form->{rowcount}) {
2039     next if ($form->{"delete_${row}"});
2040
2041     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
2042
2043     $commit_necessary = 1;
2044   }
2045
2046   $sth->finish();
2047
2048   $dbh->commit() if ($commit_necessary);
2049
2050   $main::lxdebug->leave_sub();
2051 }
2052
2053 sub delete_warehouse {
2054   $main::lxdebug->enter_sub();
2055
2056   my ($self, $myconfig, $form) = @_;
2057
2058   # connect to database
2059   my $dbh = $form->get_standard_dbh($myconfig);
2060
2061   my $id      = conv_i($form->{id});
2062   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|;
2063   my ($count) = selectrow_query($form, $dbh, $query, $id);
2064
2065   if ($count) {
2066     $main::lxdebug->leave_sub();
2067     return 0;
2068   }
2069
2070   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2071   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2072
2073   $dbh->commit();
2074
2075   $main::lxdebug->leave_sub();
2076
2077   return 1;
2078 }
2079
2080 sub get_all_warehouses {
2081   $main::lxdebug->enter_sub();
2082
2083   my ($self, $myconfig, $form) = @_;
2084
2085   # connect to database
2086   my $dbh = $form->get_standard_dbh($myconfig);
2087
2088   my $query = qq|SELECT w.id, w.description, w.invalid,
2089                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2090                  FROM warehouse w
2091                  ORDER BY w.sortkey|;
2092
2093   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2094
2095   $main::lxdebug->leave_sub();
2096 }
2097
2098 sub get_warehouse {
2099   $main::lxdebug->enter_sub();
2100
2101   my ($self, $myconfig, $form) = @_;
2102
2103   # connect to database
2104   my $dbh = $form->get_standard_dbh($myconfig);
2105
2106   my $id    = conv_i($form->{id});
2107   my $query = qq|SELECT w.description, w.invalid
2108                  FROM warehouse w
2109                  WHERE w.id = ?|;
2110
2111   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2112
2113   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2114
2115   $query = qq|SELECT b.*, EXISTS
2116                 (SELECT i.warehouse_id
2117                  FROM inventory i
2118                  WHERE i.bin_id = b.id
2119                  LIMIT 1)
2120                 AS in_use
2121               FROM bin b
2122               WHERE b.warehouse_id = ?|;
2123
2124   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2125
2126   $main::lxdebug->leave_sub();
2127 }
2128
2129 1;