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