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