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