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