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