f73456c8cc85dcb9a86f0a9c0120d99d092d8ef8
[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(translation_payment_terms 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 payment {
1148   $main::lxdebug->enter_sub();
1149
1150   my ($self, $myconfig, $form) = @_;
1151
1152   # connect to database
1153   my $dbh = $form->dbconnect($myconfig);
1154
1155   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
1156
1157   my $sth = $dbh->prepare($query);
1158   $sth->execute || $form->dberror($query);
1159
1160   $form->{ALL} = [];
1161   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1162     push @{ $form->{ALL} }, $ref;
1163   }
1164
1165   $sth->finish;
1166   $dbh->disconnect;
1167
1168   $main::lxdebug->leave_sub();
1169 }
1170
1171 sub get_payment {
1172   $main::lxdebug->enter_sub();
1173
1174   my ($self, $myconfig, $form) = @_;
1175
1176   # connect to database
1177   my $dbh = $form->dbconnect($myconfig);
1178
1179   my $query = qq|SELECT * FROM payment_terms WHERE id = ?|;
1180   my $sth = $dbh->prepare($query);
1181   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1182
1183   my $ref = $sth->fetchrow_hashref("NAME_lc");
1184   map { $form->{$_} = $ref->{$_} } keys %$ref;
1185   $sth->finish();
1186
1187   $query =
1188     qq|SELECT t.language_id, t.description_long, l.description AS language | .
1189     qq|FROM translation_payment_terms t | .
1190     qq|LEFT JOIN language l ON t.language_id = l.id | .
1191     qq|WHERE t.payment_terms_id = ? | .
1192     qq|UNION | .
1193     qq|SELECT l.id AS language_id, NULL AS description_long, | .
1194     qq|  l.description AS language | .
1195     qq|FROM language l|;
1196   $sth = $dbh->prepare($query);
1197   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1198
1199   my %mapping;
1200   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1201     $mapping{ $ref->{"language_id"} } = $ref
1202       unless (defined($mapping{ $ref->{"language_id"} }));
1203   }
1204   $sth->finish;
1205
1206   $form->{"TRANSLATION"} = [sort({ $a->{"language"} cmp $b->{"language"} }
1207                                  values(%mapping))];
1208
1209   $dbh->disconnect;
1210
1211   $main::lxdebug->leave_sub();
1212 }
1213
1214 sub save_payment {
1215   $main::lxdebug->enter_sub();
1216
1217   my ($self, $myconfig, $form) = @_;
1218
1219   # connect to database
1220   my $dbh = $form->dbconnect_noauto($myconfig);
1221
1222   my $query;
1223
1224   if (!$form->{id}) {
1225     $query = qq|SELECT nextval('id'), COALESCE(MAX(sortkey) + 1, 1) | .
1226       qq|FROM payment_terms|;
1227     my $sortkey;
1228     ($form->{id}, $sortkey) = selectrow_query($form, $dbh, $query);
1229
1230     $query = qq|INSERT INTO payment_terms (id, sortkey) VALUES (?, ?)|;
1231     do_query($form, $dbh, $query, $form->{id}, $sortkey);
1232
1233   } else {
1234     $query =
1235       qq|DELETE FROM translation_payment_terms | .
1236       qq|WHERE payment_terms_id = ?|;
1237     do_query($form, $dbh, $query, $form->{"id"});
1238   }
1239
1240   $query = qq|UPDATE payment_terms SET
1241               description = ?, description_long = ?,
1242               terms_netto = ?, terms_skonto = ?,
1243               percent_skonto = ?
1244               WHERE id = ?|;
1245   my @values = ($form->{description}, $form->{description_long},
1246                 $form->{terms_netto} * 1, $form->{terms_skonto} * 1,
1247                 $form->{percent_skonto} * 1,
1248                 $form->{id});
1249   do_query($form, $dbh, $query, @values);
1250
1251   $query = qq|SELECT id FROM language|;
1252   my @language_ids;
1253   my $sth = $dbh->prepare($query);
1254   $sth->execute() || $form->dberror($query);
1255
1256   while (my ($id) = $sth->fetchrow_array()) {
1257     push(@language_ids, $id);
1258   }
1259   $sth->finish();
1260
1261   $query =
1262     qq|INSERT INTO translation_payment_terms | .
1263     qq|(language_id, payment_terms_id, description_long) | .
1264     qq|VALUES (?, ?, ?)|;
1265   $sth = $dbh->prepare($query);
1266
1267   foreach my $language_id (@language_ids) {
1268     do_statement($form, $sth, $query, $language_id, $form->{"id"},
1269                  $form->{"description_long_${language_id}"});
1270   }
1271   $sth->finish();
1272
1273   $dbh->commit();
1274   $dbh->disconnect;
1275
1276   $main::lxdebug->leave_sub();
1277 }
1278
1279 sub delete_payment {
1280   $main::lxdebug->enter_sub();
1281
1282   my ($self, $myconfig, $form) = @_;
1283
1284   # connect to database
1285   my $dbh = $form->dbconnect_noauto($myconfig);
1286
1287   my $query =
1288     qq|DELETE FROM translation_payment_terms WHERE payment_terms_id = ?|;
1289   do_query($form, $dbh, $query, $form->{"id"});
1290
1291   $query = qq|DELETE FROM payment_terms WHERE id = ?|;
1292   do_query($form, $dbh, $query, $form->{"id"});
1293
1294   $dbh->commit();
1295   $dbh->disconnect;
1296
1297   $main::lxdebug->leave_sub();
1298 }
1299
1300
1301 sub prepare_template_filename {
1302   $main::lxdebug->enter_sub();
1303
1304   my ($self, $myconfig, $form) = @_;
1305
1306   my ($filename, $display_filename);
1307
1308   if ($form->{type} eq "stylesheet") {
1309     $filename = "css/$myconfig->{stylesheet}";
1310     $display_filename = $myconfig->{stylesheet};
1311
1312   } else {
1313     $filename = $form->{formname};
1314
1315     if ($form->{language}) {
1316       my ($id, $template_code) = split(/--/, $form->{language});
1317       $filename .= "_${template_code}";
1318     }
1319
1320     if ($form->{printer}) {
1321       my ($id, $template_code) = split(/--/, $form->{printer});
1322       $filename .= "_${template_code}";
1323     }
1324
1325     $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
1326     $filename =~ s|.*/||;
1327     $display_filename = $filename;
1328     $filename = "$myconfig->{templates}/$filename";
1329   }
1330
1331   $main::lxdebug->leave_sub();
1332
1333   return ($filename, $display_filename);
1334 }
1335
1336
1337 sub load_template {
1338   $main::lxdebug->enter_sub();
1339
1340   my ($self, $filename) = @_;
1341
1342   my ($content, $lines) = ("", 0);
1343
1344   local *TEMPLATE;
1345
1346   if (open(TEMPLATE, $filename)) {
1347     while (<TEMPLATE>) {
1348       $content .= $_;
1349       $lines++;
1350     }
1351     close(TEMPLATE);
1352   }
1353
1354   $content = Encode::decode('utf-8-strict', $content) if $::locale->is_utf8;
1355
1356   $main::lxdebug->leave_sub();
1357
1358   return ($content, $lines);
1359 }
1360
1361 sub save_template {
1362   $main::lxdebug->enter_sub();
1363
1364   my ($self, $filename, $content) = @_;
1365
1366   local *TEMPLATE;
1367
1368   my $error = "";
1369
1370   if (open(TEMPLATE, ">$filename")) {
1371     $content = Encode::encode('utf-8-strict', $content) if $::locale->is_utf8;
1372     $content =~ s/\r\n/\n/g;
1373     print(TEMPLATE $content);
1374     close(TEMPLATE);
1375   } else {
1376     $error = $!;
1377   }
1378
1379   $main::lxdebug->leave_sub();
1380
1381   return $error;
1382 }
1383
1384 sub save_defaults {
1385   $main::lxdebug->enter_sub();
1386
1387   my $self     = shift;
1388   my %params   = @_;
1389
1390   my $myconfig = \%main::myconfig;
1391   my $form     = $main::form;
1392
1393   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1394
1395   my %accnos;
1396   map { ($accnos{$_}) = split(m/--/, $form->{$_}) } qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno ar_paid_accno);
1397
1398   $form->{curr}  =~ s/ //g;
1399   my @currencies =  grep { $_ ne '' } split m/:/, $form->{curr};
1400   my $currency   =  join ':', @currencies;
1401
1402   # these defaults are database wide
1403
1404   my $query =
1405     qq|UPDATE defaults SET
1406         inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?),
1407         income_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1408         expense_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1409         fxgain_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1410         fxloss_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1411         ar_paid_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1412         invnumber          = ?,
1413         cnnumber           = ?,
1414         sonumber           = ?,
1415         ponumber           = ?,
1416         sqnumber           = ?,
1417         rfqnumber          = ?,
1418         customernumber     = ?,
1419         vendornumber       = ?,
1420         articlenumber      = ?,
1421         servicenumber      = ?,
1422         sdonumber          = ?,
1423         pdonumber          = ?,
1424         curr               = ?,
1425         businessnumber     = ?,
1426         weightunit         = ?|;
1427   my @values = ($accnos{inventory_accno}, $accnos{income_accno}, $accnos{expense_accno},
1428                 $accnos{fxgain_accno},    $accnos{fxloss_accno}, $accnos{ar_paid_accno},
1429                 $form->{invnumber},       $form->{cnnumber},
1430                 $form->{sonumber},        $form->{ponumber},
1431                 $form->{sqnumber},        $form->{rfqnumber},
1432                 $form->{customernumber},  $form->{vendornumber},
1433                 $form->{articlenumber},   $form->{servicenumber},
1434                 $form->{sdonumber},       $form->{pdonumber},
1435                 $currency,
1436                 $form->{businessnumber},  $form->{weightunit});
1437   do_query($form, $dbh, $query, @values);
1438
1439   $dbh->commit();
1440
1441   $main::lxdebug->leave_sub();
1442 }
1443
1444
1445 sub save_preferences {
1446   $main::lxdebug->enter_sub();
1447
1448   my ($self, $myconfig, $form) = @_;
1449
1450   my $dbh = $form->get_standard_dbh($myconfig);
1451
1452   my ($currency, $businessnumber) = selectrow_query($form, $dbh, qq|SELECT curr, businessnumber FROM defaults|);
1453
1454   # update name
1455   my $query = qq|UPDATE employee SET name = ? WHERE login = ?|;
1456   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1457
1458   my $rc = $dbh->commit();
1459
1460   # save first currency in myconfig
1461   $currency               =~ s/:.*//;
1462   $form->{currency}       =  $currency;
1463
1464   $form->{businessnumber} =  $businessnumber;
1465
1466   $myconfig = new User($form->{login});
1467
1468   foreach my $item (keys %$form) {
1469     $myconfig->{$item} = $form->{$item};
1470   }
1471
1472   $myconfig->save_member;
1473
1474   my $auth = $main::auth;
1475
1476   $main::lxdebug->leave_sub();
1477
1478   return $rc;
1479 }
1480
1481 sub get_defaults {
1482   $main::lxdebug->enter_sub();
1483
1484   my $self     = shift;
1485   my %params   = @_;
1486
1487   my $myconfig = \%main::myconfig;
1488   my $form     = $main::form;
1489
1490   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1491
1492   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
1493
1494   $defaults->{weightunit} ||= 'kg';
1495
1496   $main::lxdebug->leave_sub();
1497
1498   return $defaults;
1499 }
1500
1501 sub defaultaccounts {
1502   $main::lxdebug->enter_sub();
1503
1504   my ($self, $myconfig, $form) = @_;
1505
1506   # connect to database
1507   my $dbh = $form->dbconnect($myconfig);
1508
1509   # get defaults from defaults table
1510   my $query = qq|SELECT * FROM defaults|;
1511   my $sth   = $dbh->prepare($query);
1512   $sth->execute || $form->dberror($query);
1513
1514   $form->{defaults}               = $sth->fetchrow_hashref("NAME_lc");
1515   $form->{defaults}{IC}           = $form->{defaults}{inventory_accno_id};
1516   $form->{defaults}{IC_income}    = $form->{defaults}{income_accno_id};
1517   $form->{defaults}{IC_expense}   = $form->{defaults}{expense_accno_id};
1518   $form->{defaults}{FX_gain}      = $form->{defaults}{fxgain_accno_id};
1519   $form->{defaults}{FX_loss}      = $form->{defaults}{fxloss_accno_id};
1520   $form->{defaults}{AR_paid}      = $form->{defaults}{ar_paid_accno_id};
1521
1522   $form->{defaults}{weightunit} ||= 'kg';
1523
1524   $sth->finish;
1525
1526   $query = qq|SELECT c.id, c.accno, c.description, c.link
1527               FROM chart c
1528               WHERE c.link LIKE '%IC%'
1529               ORDER BY c.accno|;
1530   $sth = $dbh->prepare($query);
1531   $sth->execute || $self->dberror($query);
1532
1533   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1534     foreach my $key (split(/:/, $ref->{link})) {
1535       if ($key =~ /IC/) {
1536         my $nkey = $key;
1537         if ($key =~ /cogs/) {
1538           $nkey = "IC_expense";
1539         }
1540         if ($key =~ /sale/) {
1541           $nkey = "IC_income";
1542         }
1543         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1544                                              id          => $ref->{id},
1545                                              description => $ref->{description}
1546         );
1547       }
1548     }
1549   }
1550   $sth->finish;
1551
1552   $query = qq|SELECT c.id, c.accno, c.description
1553               FROM chart c
1554               WHERE c.category = 'I'
1555               AND c.charttype = 'A'
1556               ORDER BY c.accno|;
1557   $sth = $dbh->prepare($query);
1558   $sth->execute || $self->dberror($query);
1559
1560   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1561     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1562                                              id          => $ref->{id},
1563                                              description => $ref->{description}
1564     );
1565   }
1566   $sth->finish;
1567
1568   $query = qq|SELECT c.id, c.accno, c.description
1569               FROM chart c
1570               WHERE c.category = 'E'
1571               AND c.charttype = 'A'
1572               ORDER BY c.accno|;
1573   $sth = $dbh->prepare($query);
1574   $sth->execute || $self->dberror($query);
1575
1576   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1577     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1578                                              id          => $ref->{id},
1579                                              description => $ref->{description}
1580     );
1581   }
1582   $sth->finish;
1583
1584   # now get the tax rates and numbers
1585   $query = qq|SELECT c.id, c.accno, c.description,
1586               t.rate * 100 AS rate, t.taxnumber
1587               FROM chart c, tax t
1588               WHERE c.id = t.chart_id|;
1589
1590   $sth = $dbh->prepare($query);
1591   $sth->execute || $form->dberror($query);
1592
1593   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1594     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1595     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1596     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1597       if $ref->{taxnumber};
1598     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1599   }
1600   # Abfrage für Standard Umlaufvermögenskonto
1601   $query =
1602     qq|SELECT id, accno, description, link | .
1603     qq|FROM chart | .
1604     qq|WHERE link LIKE ? |.
1605     qq|ORDER BY accno|;
1606   $sth = prepare_execute_query($form, $dbh, $query, '%AR%');
1607   $sth->execute || $form->dberror($query);#
1608   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1609     foreach my $item (split(/:/, $ref->{link})) {
1610       if ($item eq "AR_paid") {
1611         %{ $form->{IC}{AR_paid}{ $ref->{accno} } } = (
1612                                              id          => $ref->{id},
1613                                              description => $ref->{description}
1614           );
1615       }
1616     }
1617   }
1618
1619   $sth->finish;
1620   $dbh->disconnect;
1621
1622   $main::lxdebug->leave_sub();
1623 }
1624
1625 sub closedto {
1626   $main::lxdebug->enter_sub();
1627
1628   my ($self, $myconfig, $form) = @_;
1629
1630   my $dbh = $form->dbconnect($myconfig);
1631
1632   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1633   my $sth   = $dbh->prepare($query);
1634   $sth->execute || $form->dberror($query);
1635
1636   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1637
1638   $sth->finish;
1639
1640   $dbh->disconnect;
1641
1642   $main::lxdebug->leave_sub();
1643 }
1644
1645 sub closebooks {
1646   $main::lxdebug->enter_sub();
1647
1648   my ($self, $myconfig, $form) = @_;
1649
1650   my $dbh = $form->dbconnect($myconfig);
1651
1652   my ($query, @values);
1653
1654   if ($form->{revtrans}) {
1655     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1656
1657   } elsif ($form->{closedto}) {
1658     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1659     @values = (conv_date($form->{closedto}));
1660
1661   } else {
1662     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1663   }
1664
1665   # set close in defaults
1666   do_query($form, $dbh, $query, @values);
1667
1668   $dbh->disconnect;
1669
1670   $main::lxdebug->leave_sub();
1671 }
1672
1673 sub get_base_unit {
1674   my ($self, $units, $unit_name, $factor) = @_;
1675
1676   $factor = 1 unless ($factor);
1677
1678   my $unit = $units->{$unit_name};
1679
1680   if (!defined($unit) || !$unit->{"base_unit"} ||
1681       ($unit_name eq $unit->{"base_unit"})) {
1682     return ($unit_name, $factor);
1683   }
1684
1685   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1686 }
1687
1688 sub retrieve_units {
1689   $main::lxdebug->enter_sub();
1690
1691   my ($self, $myconfig, $form, $prefix) = @_;
1692
1693   my $dbh = $form->get_standard_dbh;
1694
1695   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1696
1697   my $sth = prepare_execute_query($form, $dbh, $query);
1698
1699   my $units = {};
1700   while (my $ref = $sth->fetchrow_hashref()) {
1701     $units->{$ref->{"name"}} = $ref;
1702   }
1703   $sth->finish();
1704
1705   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1706   $sth = $dbh->prepare($query_lang);
1707   $sth->execute() || $form->dberror($query_lang);
1708   my @languages;
1709   while (my $ref = $sth->fetchrow_hashref()) {
1710     push(@languages, $ref);
1711   }
1712   $sth->finish();
1713
1714   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1715     "FROM units_language ul " .
1716     "LEFT JOIN language l ON ul.language_id = l.id " .
1717     "WHERE ul.unit = ?";
1718   $sth = $dbh->prepare($query_lang);
1719
1720   foreach my $unit (values(%{$units})) {
1721     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1722
1723     $unit->{"LANGUAGES"} = {};
1724     foreach my $lang (@languages) {
1725       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1726     }
1727
1728     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1729     while (my $ref = $sth->fetchrow_hashref()) {
1730       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1731     }
1732   }
1733   $sth->finish;
1734
1735   $main::lxdebug->leave_sub();
1736
1737   return $units;
1738 }
1739
1740 sub retrieve_all_units {
1741   $main::lxdebug->enter_sub();
1742
1743   my $self = shift;
1744
1745   if (!$main::all_units) {
1746     $main::all_units = $self->retrieve_units(\%main::myconfig, $main::form);
1747   }
1748
1749   $main::lxdebug->leave_sub();
1750
1751   return $main::all_units;
1752 }
1753
1754
1755 sub translate_units {
1756   $main::lxdebug->enter_sub();
1757
1758   my ($self, $form, $template_code, $unit, $amount) = @_;
1759
1760   my $units = $self->retrieve_units(\%main::myconfig, $form);
1761
1762   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1763   my $new_unit = $unit;
1764   if ($h) {
1765     if (($amount != 1) && $h->{"localized_plural"}) {
1766       $new_unit = $h->{"localized_plural"};
1767     } elsif ($h->{"localized"}) {
1768       $new_unit = $h->{"localized"};
1769     }
1770   }
1771
1772   $main::lxdebug->leave_sub();
1773
1774   return $new_unit;
1775 }
1776
1777 sub units_in_use {
1778   $main::lxdebug->enter_sub();
1779
1780   my ($self, $myconfig, $form, $units) = @_;
1781
1782   my $dbh = $form->dbconnect($myconfig);
1783
1784   map({ $_->{"in_use"} = 0; } values(%{$units}));
1785
1786   foreach my $unit (values(%{$units})) {
1787     my $base_unit = $unit->{"original_base_unit"};
1788     while ($base_unit) {
1789       $units->{$base_unit}->{"in_use"} = 1;
1790       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1791       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1792       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1793     }
1794   }
1795
1796   foreach my $unit (values(%{$units})) {
1797     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1798
1799     foreach my $table (qw(parts invoice orderitems)) {
1800       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1801
1802       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1803         $query .= "= " . $dbh->quote($unit->{"name"});
1804       } else {
1805         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1806           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1807       }
1808
1809       my ($count) = $dbh->selectrow_array($query);
1810       $form->dberror($query) if ($dbh->err);
1811
1812       if ($count) {
1813         $unit->{"in_use"} = 1;
1814         last;
1815       }
1816     }
1817   }
1818
1819   $dbh->disconnect();
1820
1821   $main::lxdebug->leave_sub();
1822 }
1823
1824 sub convertible_units {
1825   $main::lxdebug->enter_sub();
1826
1827   my $self        = shift;
1828   my $units       = shift;
1829   my $filter_unit = shift;
1830   my $not_smaller = shift;
1831
1832   my $conv_units = [];
1833
1834   $filter_unit = $units->{$filter_unit};
1835
1836   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1837     my $unit = $units->{$name};
1838
1839     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1840         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1841       push @{$conv_units}, $unit;
1842     }
1843   }
1844
1845   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1846
1847   $main::lxdebug->leave_sub();
1848
1849   return \@sorted;
1850 }
1851
1852 # if $a is translatable to $b, return the factor between them.
1853 # else return 1
1854 sub convert_unit {
1855   $main::lxdebug->enter_sub(2);
1856   my ($this, $a, $b, $all_units) = @_;
1857
1858   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1859   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1860   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1861   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1862 }
1863
1864 sub unit_select_data {
1865   $main::lxdebug->enter_sub();
1866
1867   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1868
1869   my $select = [];
1870
1871   if ($empty_entry) {
1872     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1873   }
1874
1875   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1876     if (!$convertible_into ||
1877         ($units->{$convertible_into} &&
1878          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1879       push @{$select}, { "name"      => $unit,
1880                          "base_unit" => $units->{$unit}->{"base_unit"},
1881                          "factor"    => $units->{$unit}->{"factor"},
1882                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1883     }
1884   }
1885
1886   $main::lxdebug->leave_sub();
1887
1888   return $select;
1889 }
1890
1891 sub unit_select_html {
1892   $main::lxdebug->enter_sub();
1893
1894   my ($self, $units, $name, $selected, $convertible_into) = @_;
1895
1896   my $select = "<select name=${name}>";
1897
1898   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1899     if (!$convertible_into ||
1900         ($units->{$convertible_into} &&
1901          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1902       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1903     }
1904   }
1905   $select .= "</select>";
1906
1907   $main::lxdebug->leave_sub();
1908
1909   return $select;
1910 }
1911
1912 sub sum_with_unit {
1913   $main::lxdebug->enter_sub();
1914
1915   my $self  = shift;
1916
1917   my $units = $self->retrieve_all_units();
1918
1919   my $sum   = 0;
1920   my $base_unit;
1921
1922   while (2 <= scalar(@_)) {
1923     my $qty  = shift(@_);
1924     my $unit = $units->{shift(@_)};
1925
1926     croak "No unit defined with name $unit" if (!defined $unit);
1927
1928     if (!$base_unit) {
1929       $base_unit = $unit->{base_unit};
1930     } elsif ($base_unit ne $unit->{base_unit}) {
1931       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1932     }
1933
1934     $sum += $qty * $unit->{factor};
1935   }
1936
1937   $main::lxdebug->leave_sub();
1938
1939   return wantarray ? ($sum, $base_unit) : $sum;
1940 }
1941
1942 sub add_unit {
1943   $main::lxdebug->enter_sub();
1944
1945   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1946
1947   my $dbh = $form->dbconnect_noauto($myconfig);
1948
1949   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1950   my ($sortkey) = selectrow_query($form, $dbh, $query);
1951
1952   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1953     "VALUES (?, ?, ?, ?)";
1954   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1955
1956   if ($languages) {
1957     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1958     my $sth = $dbh->prepare($query);
1959     foreach my $lang (@{$languages}) {
1960       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1961       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1962     }
1963     $sth->finish();
1964   }
1965
1966   $dbh->commit();
1967   $dbh->disconnect();
1968
1969   $main::lxdebug->leave_sub();
1970 }
1971
1972 sub save_units {
1973   $main::lxdebug->enter_sub();
1974
1975   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1976
1977   my $dbh = $form->dbconnect_noauto($myconfig);
1978
1979   my ($base_unit, $unit, $sth, $query);
1980
1981   $query = "DELETE FROM units_language";
1982   $dbh->do($query) || $form->dberror($query);
1983
1984   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1985     $query = "DELETE FROM units WHERE name IN (";
1986     map({ $query .= "?," } @{$delete_units});
1987     substr($query, -1, 1) = ")";
1988     $dbh->do($query, undef, @{$delete_units}) ||
1989       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1990   }
1991
1992   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1993   $sth = $dbh->prepare($query);
1994
1995   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1996   my $sth_lang = $dbh->prepare($query_lang);
1997
1998   foreach $unit (values(%{$units})) {
1999     $unit->{"depth"} = 0;
2000     my $base_unit = $unit;
2001     while ($base_unit->{"base_unit"}) {
2002       $unit->{"depth"}++;
2003       $base_unit = $units->{$base_unit->{"base_unit"}};
2004     }
2005   }
2006
2007   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
2008     if ($unit->{"LANGUAGES"}) {
2009       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
2010         next unless ($lang->{"id"} && $lang->{"localized"});
2011         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
2012         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
2013       }
2014     }
2015
2016     next if ($unit->{"unchanged_unit"});
2017
2018     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
2019     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
2020   }
2021
2022   $sth->finish();
2023   $sth_lang->finish();
2024   $dbh->commit();
2025   $dbh->disconnect();
2026
2027   $main::lxdebug->leave_sub();
2028 }
2029
2030 sub taxes {
2031   $main::lxdebug->enter_sub();
2032
2033   my ($self, $myconfig, $form) = @_;
2034
2035   # connect to database
2036   my $dbh = $form->dbconnect($myconfig);
2037
2038   my $query = qq|SELECT
2039                    t.id,
2040                    t.taxkey,
2041                    t.taxdescription,
2042                    round(t.rate * 100, 2) AS rate,
2043                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
2044                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
2045                  FROM tax t
2046                  ORDER BY taxkey|;
2047
2048   my $sth = $dbh->prepare($query);
2049   $sth->execute || $form->dberror($query);
2050
2051   $form->{TAX} = [];
2052   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2053     push @{ $form->{TAX} }, $ref;
2054   }
2055
2056   $sth->finish;
2057   $dbh->disconnect;
2058
2059   $main::lxdebug->leave_sub();
2060 }
2061
2062 sub get_tax_accounts {
2063   $main::lxdebug->enter_sub();
2064
2065   my ($self, $myconfig, $form) = @_;
2066
2067   my $dbh = $form->dbconnect($myconfig);
2068
2069   # get Accounts from chart
2070   my $query = qq{ SELECT
2071                  id,
2072                  accno || ' - ' || description AS taxaccount
2073                FROM chart
2074                WHERE link LIKE '%_tax%'
2075                ORDER BY accno
2076              };
2077
2078   my $sth = $dbh->prepare($query);
2079   $sth->execute || $form->dberror($query);
2080
2081   $form->{ACCOUNTS} = [];
2082   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2083     push @{ $form->{ACCOUNTS} }, $ref;
2084   }
2085
2086   $sth->finish;
2087
2088   $dbh->disconnect;
2089
2090   $main::lxdebug->leave_sub();
2091 }
2092
2093 sub get_tax {
2094   $main::lxdebug->enter_sub();
2095
2096   my ($self, $myconfig, $form) = @_;
2097
2098   # connect to database
2099   my $dbh = $form->dbconnect($myconfig);
2100
2101   my $query = qq|SELECT
2102                    taxkey,
2103                    taxdescription,
2104                    round(rate * 100, 2) AS rate,
2105                    chart_id
2106                  FROM tax
2107                  WHERE id = ? |;
2108
2109   my $sth = $dbh->prepare($query);
2110   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2111
2112   my $ref = $sth->fetchrow_hashref("NAME_lc");
2113
2114   map { $form->{$_} = $ref->{$_} } keys %$ref;
2115
2116   $sth->finish;
2117
2118   # see if it is used by a taxkey
2119   $query = qq|SELECT count(*) FROM taxkeys
2120               WHERE tax_id = ? AND chart_id >0|;
2121
2122   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
2123
2124   $form->{orphaned} = !$form->{orphaned};
2125   $sth->finish;
2126
2127   if (!$form->{orphaned} ) {
2128     $query = qq|SELECT DISTINCT c.id, c.accno
2129                 FROM taxkeys tk
2130                 JOIN   tax t ON (t.id = tk.tax_id)
2131                 JOIN chart c ON (c.id = tk.chart_id)
2132                 WHERE tk.tax_id = ?|;
2133
2134     $sth = $dbh->prepare($query);
2135     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2136
2137     $form->{TAXINUSE} = [];
2138     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2139       push @{ $form->{TAXINUSE} }, $ref;
2140     }
2141
2142     $sth->finish;
2143   }
2144
2145   $dbh->disconnect;
2146
2147   $main::lxdebug->leave_sub();
2148 }
2149
2150 sub save_tax {
2151   $main::lxdebug->enter_sub();
2152
2153   my ($self, $myconfig, $form) = @_;
2154   my $query;
2155
2156   # connect to database
2157   my $dbh = $form->get_standard_dbh($myconfig);
2158
2159   $form->{rate} = $form->{rate} / 100;
2160
2161   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
2162   if ($form->{id} ne "") {
2163     $query = qq|UPDATE tax SET
2164                   taxkey         = ?,
2165                   taxdescription = ?,
2166                   rate           = ?,
2167                   chart_id       = ?,
2168                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
2169                 WHERE id = ?|;
2170     push(@values, $form->{id});
2171
2172   } else {
2173     #ok
2174     $query = qq|INSERT INTO tax (
2175                   taxkey,
2176                   taxdescription,
2177                   rate,
2178                   chart_id,
2179                   taxnumber
2180                 )
2181                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
2182   }
2183   do_query($form, $dbh, $query, @values);
2184
2185   $dbh->commit();
2186
2187   $main::lxdebug->leave_sub();
2188 }
2189
2190 sub delete_tax {
2191   $main::lxdebug->enter_sub();
2192
2193   my ($self, $myconfig, $form) = @_;
2194   my $query;
2195
2196   # connect to database
2197   my $dbh = $form->get_standard_dbh($myconfig);
2198
2199   $query = qq|DELETE FROM tax
2200               WHERE id = ?|;
2201   do_query($form, $dbh, $query, $form->{id});
2202
2203   $dbh->commit();
2204
2205   $main::lxdebug->leave_sub();
2206 }
2207
2208 sub save_price_factor {
2209   $main::lxdebug->enter_sub();
2210
2211   my ($self, $myconfig, $form) = @_;
2212
2213   # connect to database
2214   my $dbh = $form->get_standard_dbh($myconfig);
2215
2216   my $query;
2217   my @values = ($form->{description}, conv_i($form->{factor}));
2218
2219   if ($form->{id}) {
2220     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
2221     push @values, conv_i($form->{id});
2222
2223   } else {
2224     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
2225   }
2226
2227   do_query($form, $dbh, $query, @values);
2228
2229   $dbh->commit();
2230
2231   $main::lxdebug->leave_sub();
2232 }
2233
2234 sub get_all_price_factors {
2235   $main::lxdebug->enter_sub();
2236
2237   my ($self, $myconfig, $form) = @_;
2238
2239   # connect to database
2240   my $dbh = $form->get_standard_dbh($myconfig);
2241
2242   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
2243
2244   $main::lxdebug->leave_sub();
2245 }
2246
2247 sub get_price_factor {
2248   $main::lxdebug->enter_sub();
2249
2250   my ($self, $myconfig, $form) = @_;
2251
2252   # connect to database
2253   my $dbh = $form->get_standard_dbh($myconfig);
2254
2255   my $query = qq|SELECT description, factor,
2256                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
2257                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
2258                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
2259                  FROM price_factors WHERE id = ?|;
2260
2261   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
2262
2263   $main::lxdebug->leave_sub();
2264 }
2265
2266 sub delete_price_factor {
2267   $main::lxdebug->enter_sub();
2268
2269   my ($self, $myconfig, $form) = @_;
2270
2271   # connect to database
2272   my $dbh = $form->get_standard_dbh($myconfig);
2273
2274   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
2275   $dbh->commit();
2276
2277   $main::lxdebug->leave_sub();
2278 }
2279
2280 sub save_warehouse {
2281   $main::lxdebug->enter_sub();
2282
2283   my ($self, $myconfig, $form) = @_;
2284
2285   # connect to database
2286   my $dbh = $form->get_standard_dbh($myconfig);
2287
2288   my ($query, @values, $sth);
2289
2290   if (!$form->{id}) {
2291     $query        = qq|SELECT nextval('id')|;
2292     ($form->{id}) = selectrow_query($form, $dbh, $query);
2293
2294     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
2295     do_query($form, $dbh, $query, $form->{id});
2296   }
2297
2298   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
2299            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
2300
2301   if (0 < $form->{number_of_new_bins}) {
2302     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
2303     $sth   = prepare_query($form, $dbh, $query);
2304
2305     foreach my $i (1..$form->{number_of_new_bins}) {
2306       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
2307     }
2308
2309     $sth->finish();
2310   }
2311
2312   $dbh->commit();
2313
2314   $main::lxdebug->leave_sub();
2315 }
2316
2317 sub save_bins {
2318   $main::lxdebug->enter_sub();
2319
2320   my ($self, $myconfig, $form) = @_;
2321
2322   # connect to database
2323   my $dbh = $form->get_standard_dbh($myconfig);
2324
2325   my ($query, @values, $commit_necessary, $sth);
2326
2327   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
2328
2329   if (@values) {
2330     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
2331     do_query($form, $dbh, $query, @values);
2332
2333     $commit_necessary = 1;
2334   }
2335
2336   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
2337   $sth   = prepare_query($form, $dbh, $query);
2338
2339   foreach my $row (1..$form->{rowcount}) {
2340     next if ($form->{"delete_${row}"});
2341
2342     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
2343
2344     $commit_necessary = 1;
2345   }
2346
2347   $sth->finish();
2348
2349   $dbh->commit() if ($commit_necessary);
2350
2351   $main::lxdebug->leave_sub();
2352 }
2353
2354 sub delete_warehouse {
2355   $main::lxdebug->enter_sub();
2356
2357   my ($self, $myconfig, $form) = @_;
2358
2359   # connect to database
2360   my $dbh = $form->get_standard_dbh($myconfig);
2361
2362   my $id      = conv_i($form->{id});
2363   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|;
2364   my ($count) = selectrow_query($form, $dbh, $query, $id);
2365
2366   if ($count) {
2367     $main::lxdebug->leave_sub();
2368     return 0;
2369   }
2370
2371   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2372   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2373
2374   $dbh->commit();
2375
2376   $main::lxdebug->leave_sub();
2377
2378   return 1;
2379 }
2380
2381 sub get_all_warehouses {
2382   $main::lxdebug->enter_sub();
2383
2384   my ($self, $myconfig, $form) = @_;
2385
2386   # connect to database
2387   my $dbh = $form->get_standard_dbh($myconfig);
2388
2389   my $query = qq|SELECT w.id, w.description, w.invalid,
2390                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2391                  FROM warehouse w
2392                  ORDER BY w.sortkey|;
2393
2394   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2395
2396   $main::lxdebug->leave_sub();
2397 }
2398
2399 sub get_warehouse {
2400   $main::lxdebug->enter_sub();
2401
2402   my ($self, $myconfig, $form) = @_;
2403
2404   # connect to database
2405   my $dbh = $form->get_standard_dbh($myconfig);
2406
2407   my $id    = conv_i($form->{id});
2408   my $query = qq|SELECT w.description, w.invalid
2409                  FROM warehouse w
2410                  WHERE w.id = ?|;
2411
2412   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2413
2414   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2415
2416   $query = qq|SELECT b.*, EXISTS
2417                 (SELECT i.warehouse_id
2418                  FROM inventory i
2419                  WHERE i.bin_id = b.id
2420                  LIMIT 1)
2421                 AS in_use
2422               FROM bin b
2423               WHERE b.warehouse_id = ?|;
2424
2425   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2426
2427   $main::lxdebug->leave_sub();
2428 }
2429
2430 1;