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