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