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