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