8696cba0da19d48bde3c8627b2c0d37cfa91b3c6
[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 =
51     qq!SELECT c.accno, c.description, c.charttype, c.gifi_accno, c.category,! .
52     qq!  c.link, c.pos_bilanz, c.pos_eur, c.new_chart_id, c.valid_from, ! .
53     qq!  c.pos_bwa, ! .
54     qq!  tk.taxkey_id, tk.pos_ustva, tk.tax_id, ! .
55     qq!  tk.tax_id || '--' || tk.taxkey_id AS tax, tk.startdate ! .
56     qq!FROM chart c ! .
57     qq!LEFT JOIN taxkeys tk ! .
58     qq!ON (c.id=tk.chart_id AND tk.id = ! .
59     qq!  (SELECT id FROM taxkeys ! .
60     qq!   WHERE taxkeys.chart_id = c.id AND startdate <= current_date ! .
61     qq!   ORDER BY startdate DESC LIMIT 1)) ! .
62     qq!WHERE c.id = ?!;
63
64   my $sth = $dbh->prepare($query);
65   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
66
67   my $ref = $sth->fetchrow_hashref(NAME_lc);
68
69   foreach my $key (keys %$ref) {
70     $form->{"$key"} = $ref->{"$key"};
71   }
72
73   $sth->finish;
74
75   # get default accounts
76   $query = qq|SELECT inventory_accno_id, income_accno_id, expense_accno_id
77               FROM defaults|;
78   $sth = $dbh->prepare($query);
79   $sth->execute || $form->dberror($query);
80
81   $ref = $sth->fetchrow_hashref(NAME_lc);
82
83   map { $form->{$_} = $ref->{$_} } keys %ref;
84
85   $sth->finish;
86
87   # get taxkeys and description
88   $query = qq§SELECT id, taxkey,id||'--'||taxkey AS tax, taxdescription
89               FROM tax ORDER BY taxkey§;
90   $sth = $dbh->prepare($query);
91   $sth->execute || $form->dberror($query);
92
93   $form->{TAXKEY} = [];
94
95   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
96     push @{ $form->{TAXKEY} }, $ref;
97   }
98
99   $sth->finish;
100   if ($form->{id}) {
101     # get new accounts
102     $query = qq|SELECT id, accno,description
103                 FROM chart WHERE link = ?|;
104     $sth = $dbh->prepare($query);
105     $sth->execute($form->{link}) || $form->dberror($query . " ($form->{link})");
106
107     $form->{NEWACCOUNT} = [];
108     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
109       push @{ $form->{NEWACCOUNT} }, $ref;
110     }
111
112     $sth->finish;
113   }
114   # check if we have any transactions
115   $query = qq|SELECT a.trans_id FROM acc_trans a
116               WHERE a.chart_id = ?|;
117   $sth = $dbh->prepare($query);
118   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
119
120   ($form->{orphaned}) = $sth->fetchrow_array;
121   $form->{orphaned} = !$form->{orphaned};
122   $sth->finish;
123
124   # check if new account is active
125   $form->{new_chart_valid} = 0;
126   if ($form->{new_chart_id}) {
127     $query = qq|SELECT current_date-valid_from FROM chart
128                 WHERE id = ?|;
129     my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
130     if ($count >=0) {
131       $form->{new_chart_valid} = 1;
132     }
133     $sth->finish;
134   }
135
136   $dbh->disconnect;
137
138   $main::lxdebug->leave_sub();
139 }
140
141 sub save_account {
142   $main::lxdebug->enter_sub();
143
144   my ($self, $myconfig, $form) = @_;
145
146   # connect to database, turn off AutoCommit
147   my $dbh = $form->dbconnect_noauto($myconfig);
148
149   # sanity check, can't have AR with AR_...
150   if ($form->{AR} || $form->{AP} || $form->{IC}) {
151     map { delete $form->{$_} }
152       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);
153   }
154
155   $form->{link} = "";
156   foreach my $item ($form->{AR},            $form->{AR_amount},
157                     $form->{AR_tax},        $form->{AR_paid},
158                     $form->{AP},            $form->{AP_amount},
159                     $form->{AP_tax},        $form->{AP_paid},
160                     $form->{IC},            $form->{IC_sale},
161                     $form->{IC_cogs},       $form->{IC_taxpart},
162                     $form->{IC_income},     $form->{IC_expense},
163                     $form->{IC_taxservice}, $form->{CT_tax}
164     ) {
165     $form->{link} .= "${item}:" if ($item);
166   }
167   chop $form->{link};
168
169   # strip blanks from accno
170   map { $form->{$_} =~ s/ //g; } qw(accno);
171
172   my ($query, $sth);
173
174   if ($form->{id} eq "NULL") {
175     $form->{id} = "";
176   }
177
178   my @values;
179
180   my ($tax_id, $taxkey) = split(/--/, $form->{tax});
181   my $startdate = $form->{startdate} ? $form->{startdate} : "1970-01-01";
182
183   if ($form->{id}) {
184     $query = qq|UPDATE chart SET
185                 accno = ?, description = ?, charttype = ?,
186                 gifi_accno = ?, category = ?, link = ?,
187                 taxkey_id = ?,
188                 pos_ustva = ?, pos_bwa   = ?, pos_bilanz = ?,
189                 pos_eur = ?, new_chart_id = ?, valid_from = ?
190                 WHERE id = ?|;
191     @values = ($form->{accno}, $form->{description}, $form->{charttype},
192                $form->{gifi_accno}, $form->{category}, $form->{link},
193                conv_i($taxkey),
194                conv_i($form->{pos_ustva}), conv_i($form->{pos_bwa}),
195                conv_i($form->{pos_bilanz}), conv_i($form->{pos_eur}),
196                conv_i($form->{new_chart_id}),
197                conv_date($form->{valid_from}),
198                $form->{id});
199
200   } elsif ($form->{id} && !$form->{new_chart_valid}) {
201     $query = qq|UPDATE chart SET new_chart_id = ?, valid_from = ?
202                 WHERE id = ?|;
203     @values = (conv_i($form->{new_chart_id}), conv_date($form->{valid_from}),
204                $form->{id});
205   } else {
206     $query = qq|INSERT INTO chart
207                 (accno, description, charttype,
208                  gifi_accno, category, link,
209                  taxkey_id,
210                  pos_ustva, pos_bwa, pos_bilanz, pos_eur,
211                  new_chart_id, valid_from)
212                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
213     @values = ($form->{accno}, $form->{description}, $form->{charttype},
214                $form->{gifi_accno}, $form->{category}, $form->{link},
215                conv_i($taxkey),
216                conv_i($form->{pos_ustva}), conv_i($form->{pos_bwa}),
217                conv_i($form->{pos_bilanz}), conv_i($form->{pos_eur}),
218                conv_i($form->{new_chart_id}),
219                conv_date($form->{valid_from}));
220
221   }
222   do_query($form, $dbh, $query, @values);
223
224   #Save Taxes
225   if (!$form->{id}) {
226     $query =
227       qq|INSERT INTO taxkeys | .
228       qq|(chart_id, tax_id, taxkey_id, pos_ustva, startdate) | .
229       qq|VALUES ((SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?)|;
230     do_query($form, $dbh, $query,
231              $form->{accno}, conv_i($tax_id), conv_i($taxkey),
232              conv_i($form->{pos_ustva}), conv_date($startdate));
233
234   } else {
235     $query = qq|DELETE FROM taxkeys WHERE chart_id = ? AND tax_id = ?|;
236     do_query($form, $dbh, $query, $form->{id}, conv_i($tax_id));
237
238     $query =
239       qq|INSERT INTO taxkeys | .
240       qq|(chart_id, tax_id, taxkey_id, pos_ustva, startdate) | .
241       qq|VALUES (?, ?, ?, ?, ?)|;
242     do_query($form, $dbh, $query,
243              $form->{id}, conv_i($tax_id), conv_i($taxkey),
244              conv_i($form->{pos_ustva}), conv_date($startdate));
245   }
246
247   # commit
248   my $rc = $dbh->commit;
249   $dbh->disconnect;
250
251   $main::lxdebug->leave_sub();
252
253   return $rc;
254 }
255
256 sub delete_account {
257   $main::lxdebug->enter_sub();
258
259   my ($self, $myconfig, $form) = @_;
260
261   # connect to database, turn off AutoCommit
262   my $dbh = $form->dbconnect_noauto($myconfig);
263
264   my $query = qq|SELECT count(*) FROM acc_trans a
265                  WHERE a.chart_id = ?|;
266   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
267
268   if ($count) {
269     $dbh->disconnect;
270     $main::lxdebug->leave_sub();
271     return;
272   }
273
274   # set inventory_accno_id, income_accno_id, expense_accno_id to defaults
275   foreach my $type (qw(inventory income expense)) {
276     $query =
277       qq|UPDATE parts | .
278       qq|SET ${type}_accno_id = (SELECT ${type}_accno_id FROM defaults) | .
279       qq|WHERE ${type}_accno_id = ?|;
280     do_query($form, $dbh, $query, $form->{id});
281   }
282
283   foreach my $table (qw(partstax customertax vendortax tax)) {
284     $query = qq|DELETE FROM $table
285                 WHERE chart_id = ?|;
286     do_query($form, $dbh, $query, $form->{id});
287   }
288
289   # delete chart of account record
290   $query = qq|DELETE FROM chart
291               WHERE id = ?|;
292   do_query($form, $dbh, $query, $form->{id});
293
294   # commit and redirect
295   my $rc = $dbh->commit;
296   $dbh->disconnect;
297
298   $main::lxdebug->leave_sub();
299
300   return $rc;
301 }
302
303 sub departments {
304   $main::lxdebug->enter_sub();
305
306   my ($self, $myconfig, $form) = @_;
307
308   # connect to database
309   my $dbh = $form->dbconnect($myconfig);
310
311   my $query = qq|SELECT d.id, d.description, d.role
312                  FROM department d
313                  ORDER BY 2|;
314
315   $sth = $dbh->prepare($query);
316   $sth->execute || $form->dberror($query);
317
318   $form->{ALL} = [];
319   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
320     push @{ $form->{ALL} }, $ref;
321   }
322
323   $sth->finish;
324   $dbh->disconnect;
325
326   $main::lxdebug->leave_sub();
327 }
328
329 sub get_department {
330   $main::lxdebug->enter_sub();
331
332   my ($self, $myconfig, $form) = @_;
333
334   # connect to database
335   my $dbh = $form->dbconnect($myconfig);
336
337   my $query = qq|SELECT d.description, d.role
338                  FROM department d
339                  WHERE d.id = ?|;
340   my $sth = $dbh->prepare($query);
341   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
342
343   my $ref = $sth->fetchrow_hashref(NAME_lc);
344
345   map { $form->{$_} = $ref->{$_} } keys %$ref;
346
347   $sth->finish;
348
349   # see if it is in use
350   $query = qq|SELECT count(*) FROM dpt_trans d
351               WHERE d.department_id = ?|;
352   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
353
354   $form->{orphaned} = !$form->{orphaned};
355   $sth->finish;
356
357   $dbh->disconnect;
358
359   $main::lxdebug->leave_sub();
360 }
361
362 sub save_department {
363   $main::lxdebug->enter_sub();
364
365   my ($self, $myconfig, $form) = @_;
366
367   # connect to database
368   my $dbh = $form->dbconnect($myconfig);
369
370   my @values = ($form->{description}, $form->{role});
371   if ($form->{id}) {
372     $query = qq|UPDATE department SET
373                 description = ?, role = ?
374                 WHERE id = ?|;
375     push(@values, $form->{id});
376   } else {
377     $query = qq|INSERT INTO department
378                 (description, role)
379                 VALUES (?, ?)|;
380   }
381   do_query($form, $dbh, $query, @values);
382
383   $dbh->disconnect;
384
385   $main::lxdebug->leave_sub();
386 }
387
388 sub delete_department {
389   $main::lxdebug->enter_sub();
390
391   my ($self, $myconfig, $form) = @_;
392
393   # connect to database
394   my $dbh = $form->dbconnect($myconfig);
395
396   $query = qq|DELETE FROM department
397               WHERE id = ?|;
398   do_query($form, $dbh, $query, $form->{id});
399
400   $dbh->disconnect;
401
402   $main::lxdebug->leave_sub();
403 }
404
405 sub lead {
406   $main::lxdebug->enter_sub();
407
408   my ($self, $myconfig, $form) = @_;
409
410   # connect to database
411   my $dbh = $form->dbconnect($myconfig);
412
413   my $query = qq|SELECT id, lead
414                  FROM leads
415                  ORDER BY 2|;
416
417   $sth = $dbh->prepare($query);
418   $sth->execute || $form->dberror($query);
419
420   $form->{ALL};
421   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
422     push @{ $form->{ALL} }, $ref;
423   }
424
425   $sth->finish;
426   $dbh->disconnect;
427
428   $main::lxdebug->leave_sub();
429 }
430
431 sub get_lead {
432   $main::lxdebug->enter_sub();
433
434   my ($self, $myconfig, $form) = @_;
435
436   # connect to database
437   my $dbh = $form->dbconnect($myconfig);
438
439   my $query =
440     qq|SELECT l.id, l.lead | .
441     qq|FROM leads l | .
442     qq|WHERE l.id = ?|;
443   my $sth = $dbh->prepare($query);
444   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
445
446   my $ref = $sth->fetchrow_hashref(NAME_lc);
447
448   map { $form->{$_} = $ref->{$_} } keys %$ref;
449
450   $sth->finish;
451
452   $dbh->disconnect;
453
454   $main::lxdebug->leave_sub();
455 }
456
457 sub save_lead {
458   $main::lxdebug->enter_sub();
459
460   my ($self, $myconfig, $form) = @_;
461
462   # connect to database
463   my $dbh = $form->dbconnect($myconfig);
464
465   my @values = ($form->{description});
466   # id is the old record
467   if ($form->{id}) {
468     $query = qq|UPDATE leads SET
469                 lead = ?
470                 WHERE id = ?|;
471     puhs(@values, $form->{id});
472   } else {
473     $query = qq|INSERT INTO leads
474                 (lead)
475                 VALUES (?)|;
476   }
477   do_query($form, $dbh, $query, @values);
478
479   $dbh->disconnect;
480
481   $main::lxdebug->leave_sub();
482 }
483
484 sub delete_lead {
485   $main::lxdebug->enter_sub();
486
487   my ($self, $myconfig, $form) = @_;
488
489   # connect to database
490   my $dbh = $form->dbconnect($myconfig);
491
492   $query = qq|DELETE FROM leads
493               WHERE id = ?|;
494   do_query($form, $dbh, $query, $form->{id});
495
496   $dbh->disconnect;
497
498   $main::lxdebug->leave_sub();
499 }
500
501 sub business {
502   $main::lxdebug->enter_sub();
503
504   my ($self, $myconfig, $form) = @_;
505
506   # connect to database
507   my $dbh = $form->dbconnect($myconfig);
508
509   my $query = qq|SELECT id, description, discount, customernumberinit
510                  FROM business
511                  ORDER BY 2|;
512
513   $sth = $dbh->prepare($query);
514   $sth->execute || $form->dberror($query);
515
516   $form->{ALL};
517   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
518     push @{ $form->{ALL} }, $ref;
519   }
520
521   $sth->finish;
522   $dbh->disconnect;
523
524   $main::lxdebug->leave_sub();
525 }
526
527 sub get_business {
528   $main::lxdebug->enter_sub();
529
530   my ($self, $myconfig, $form) = @_;
531
532   # connect to database
533   my $dbh = $form->dbconnect($myconfig);
534
535   my $query =
536     qq|SELECT b.description, b.discount, b.customernumberinit
537        FROM business b
538        WHERE b.id = ?|;
539   my $sth = $dbh->prepare($query);
540   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
541
542   my $ref = $sth->fetchrow_hashref(NAME_lc);
543
544   map { $form->{$_} = $ref->{$_} } keys %$ref;
545
546   $sth->finish;
547
548   $dbh->disconnect;
549
550   $main::lxdebug->leave_sub();
551 }
552
553 sub save_business {
554   $main::lxdebug->enter_sub();
555
556   my ($self, $myconfig, $form) = @_;
557
558   # connect to database
559   my $dbh = $form->dbconnect($myconfig);
560
561   my @values = ($form->{description}, $form->{discount},
562                 $form->{customernumberinit});
563   # id is the old record
564   if ($form->{id}) {
565     $query = qq|UPDATE business SET
566                 description = ?,
567                 discount = ?,
568                 customernumberinit = ?
569                 WHERE id = ?|;
570     push(@values, $form->{id});
571   } else {
572     $query = qq|INSERT INTO business
573                 (description, discount, customernumberinit)
574                 VALUES (?, ?, ?)|;
575   }
576   do_query($form, $dbh, $query, @values);
577
578   $dbh->disconnect;
579
580   $main::lxdebug->leave_sub();
581 }
582
583 sub delete_business {
584   $main::lxdebug->enter_sub();
585
586   my ($self, $myconfig, $form) = @_;
587
588   # connect to database
589   my $dbh = $form->dbconnect($myconfig);
590
591   $query = qq|DELETE FROM business
592               WHERE id = ?|;
593   do_query($form, $dbh, $query, $form->{id});
594
595   $dbh->disconnect;
596
597   $main::lxdebug->leave_sub();
598 }
599
600
601 sub language {
602   $main::lxdebug->enter_sub();
603
604   my ($self, $myconfig, $form, $return_list) = @_;
605
606   # connect to database
607   my $dbh = $form->dbconnect($myconfig);
608
609   my $query =
610     "SELECT id, description, template_code, article_code, " .
611     "  output_numberformat, output_dateformat, output_longdates " .
612     "FROM language ORDER BY description";
613
614   $sth = $dbh->prepare($query);
615   $sth->execute || $form->dberror($query);
616
617   my $ary = [];
618
619   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
620     push(@{ $ary }, $ref);
621   }
622
623   $sth->finish;
624   $dbh->disconnect;
625
626   $main::lxdebug->leave_sub();
627
628   if ($return_list) {
629     return @{$ary};
630   } else {
631     $form->{ALL} = $ary;
632   }
633 }
634
635 sub get_language {
636   $main::lxdebug->enter_sub();
637
638   my ($self, $myconfig, $form) = @_;
639
640   # connect to database
641   my $dbh = $form->dbconnect($myconfig);
642
643   my $query =
644     "SELECT description, template_code, article_code, " .
645     "  output_numberformat, output_dateformat, output_longdates " .
646     "FROM language WHERE id = ?";
647   my $sth = $dbh->prepare($query);
648   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
649
650   my $ref = $sth->fetchrow_hashref(NAME_lc);
651
652   map { $form->{$_} = $ref->{$_} } keys %$ref;
653
654   $sth->finish;
655
656   $dbh->disconnect;
657
658   $main::lxdebug->leave_sub();
659 }
660
661 sub get_language_details {
662   $main::lxdebug->enter_sub();
663
664   my ($self, $myconfig, $form, $id) = @_;
665
666   # connect to database
667   my $dbh = $form->dbconnect($myconfig);
668
669   my $query =
670     "SELECT template_code, " .
671     "  output_numberformat, output_dateformat, output_longdates " .
672     "FROM language WHERE id = ?";
673   my @res = selectrow_query($form, $dbh, $query, $id);
674   $dbh->disconnect;
675
676   $main::lxdebug->leave_sub();
677
678   return @res;
679 }
680
681 sub save_language {
682   $main::lxdebug->enter_sub();
683
684   my ($self, $myconfig, $form) = @_;
685
686   # connect to database
687   my $dbh = $form->dbconnect($myconfig);
688   my (@values, $query);
689
690   map({ push(@values, $form->{$_}); }
691       qw(description template_code article_code
692          output_numberformat output_dateformat output_longdates));
693
694   # id is the old record
695   if ($form->{id}) {
696     $query =
697       "UPDATE language SET " .
698       "  description = ?, template_code = ?, article_code = ?, " .
699       "  output_numberformat = ?, output_dateformat = ?, " .
700       "  output_longdates = ? " .
701       "WHERE id = ?";
702     push(@values, $form->{id});
703   } else {
704     $query =
705       "INSERT INTO language (" .
706       "  description, template_code, article_code, " .
707       "  output_numberformat, output_dateformat, output_longdates" .
708       ") VALUES (?, ?, ?, ?, ?, ?)";
709   }
710   do_query($form, $dbh, $query, @values);
711
712   $dbh->disconnect;
713
714   $main::lxdebug->leave_sub();
715 }
716
717 sub delete_language {
718   $main::lxdebug->enter_sub();
719
720   my ($self, $myconfig, $form) = @_;
721
722   # connect to database
723   my $dbh = $form->dbconnect_noauto($myconfig);
724
725   foreach my $table (qw(translation_payment_terms units_language)) {
726     my $query = qq|DELETE FROM $table WHERE language_id = ?|;
727     do_query($form, $dbh, $query, $form->{"id"});
728   }
729
730   $query = "DELETE FROM language WHERE id = ?";
731   do_query($form, $dbh, $query, $form->{"id"});
732
733   $dbh->commit();
734   $dbh->disconnect;
735
736   $main::lxdebug->leave_sub();
737 }
738
739
740 sub buchungsgruppe {
741   $main::lxdebug->enter_sub();
742
743   my ($self, $myconfig, $form) = @_;
744
745   # connect to database
746   my $dbh = $form->dbconnect($myconfig);
747
748   my $query = qq|SELECT id, description,
749                  inventory_accno_id,
750                  (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
751                  income_accno_id_0,
752                  (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
753                  expense_accno_id_0,
754                  (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
755                  income_accno_id_1,
756                  (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
757                  expense_accno_id_1,
758                  (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
759                  income_accno_id_2,
760                  (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
761                  expense_accno_id_2,
762                  (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
763                  income_accno_id_3,
764                  (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
765                  expense_accno_id_3,
766                  (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
767                  FROM buchungsgruppen
768                  ORDER BY sortkey|;
769
770   $sth = $dbh->prepare($query);
771   $sth->execute || $form->dberror($query);
772
773   $form->{ALL} = [];
774   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
775     push @{ $form->{ALL} }, $ref;
776   }
777
778   $sth->finish;
779   $dbh->disconnect;
780
781   $main::lxdebug->leave_sub();
782 }
783
784 sub get_buchungsgruppe {
785   $main::lxdebug->enter_sub();
786
787   my ($self, $myconfig, $form) = @_;
788
789   # connect to database
790   my $dbh = $form->dbconnect($myconfig);
791
792   if ($form->{id}) {
793     my $query =
794       qq|SELECT description, inventory_accno_id,
795          (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
796          income_accno_id_0,
797          (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
798          expense_accno_id_0,
799          (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
800          income_accno_id_1,
801          (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
802          expense_accno_id_1,
803          (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
804          income_accno_id_2,
805          (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
806          expense_accno_id_2,
807          (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
808          income_accno_id_3,
809          (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
810          expense_accno_id_3,
811          (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
812          FROM buchungsgruppen
813          WHERE id = ?|;
814     my $sth = $dbh->prepare($query);
815     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
816
817     my $ref = $sth->fetchrow_hashref(NAME_lc);
818
819     map { $form->{$_} = $ref->{$_} } keys %$ref;
820
821     $sth->finish;
822
823     my $query =
824       qq|SELECT count(id) = 0 AS orphaned
825          FROM parts
826          WHERE buchungsgruppen_id = ?|;
827     ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
828   }
829
830   $query = "SELECT inventory_accno_id, income_accno_id, expense_accno_id ".
831     "FROM defaults";
832   ($form->{"std_inventory_accno_id"}, $form->{"std_income_accno_id"},
833    $form->{"std_expense_accno_id"}) = selectrow_query($form, $dbh, $query);
834
835   my $module = "IC";
836   $query = qq|SELECT c.accno, c.description, c.link, c.id,
837               d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
838               FROM chart c, defaults d
839               WHERE c.link LIKE '%$module%'
840               ORDER BY c.accno|;
841
842
843   my $sth = $dbh->prepare($query);
844   $sth->execute || $form->dberror($query);
845   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
846     foreach my $key (split(/:/, $ref->{link})) {
847       if (!$form->{"std_inventory_accno_id"} && ($key eq "IC")) {
848         $form->{"std_inventory_accno_id"} = $ref->{"id"};
849       }
850       if ($key =~ /$module/) {
851         if (   ($ref->{id} eq $ref->{inventory_accno_id})
852             || ($ref->{id} eq $ref->{income_accno_id})
853             || ($ref->{id} eq $ref->{expense_accno_id})) {
854           push @{ $form->{"${module}_links"}{$key} },
855             { accno       => $ref->{accno},
856               description => $ref->{description},
857               selected    => "selected",
858               id          => $ref->{id} };
859         } else {
860           push @{ $form->{"${module}_links"}{$key} },
861             { accno       => $ref->{accno},
862               description => $ref->{description},
863               selected    => "",
864               id          => $ref->{id} };
865         }
866       }
867     }
868   }
869   $sth->finish;
870
871
872   $dbh->disconnect;
873
874   $main::lxdebug->leave_sub();
875 }
876
877 sub save_buchungsgruppe {
878   $main::lxdebug->enter_sub();
879
880   my ($self, $myconfig, $form) = @_;
881
882   # connect to database
883   my $dbh = $form->dbconnect($myconfig);
884
885   my @values = ($form->{description}, $form->{inventory_accno_id},
886                 $form->{income_accno_id_0}, $form->{expense_accno_id_0},
887                 $form->{income_accno_id_1}, $form->{expense_accno_id_1},
888                 $form->{income_accno_id_2}, $form->{expense_accno_id_2},
889                 $form->{income_accno_id_3}, $form->{expense_accno_id_3});
890
891   my $query;
892
893   # id is the old record
894   if ($form->{id}) {
895     $query = qq|UPDATE buchungsgruppen SET
896                 description = ?, inventory_accno_id = ?,
897                 income_accno_id_0 = ?, expense_accno_id_0 = ?,
898                 income_accno_id_1 = ?, expense_accno_id_1 = ?,
899                 income_accno_id_2 = ?, expense_accno_id_2 = ?,
900                 income_accno_id_3 = ?, expense_accno_id_3 = ?
901                 WHERE id = ?|;
902     push(@values, $form->{id});
903   } else {
904     $query = qq|SELECT COALESCE(MAX(sortkey) + 1, 1) FROM buchungsgruppen|;
905     my ($sortkey) = $dbh->selectrow_array($query);
906     $form->dberror($query) if ($dbh->err);
907     push(@values, $sortkey);
908     $query = qq|INSERT INTO buchungsgruppen
909                 (description, inventory_accno_id,
910                 income_accno_id_0, expense_accno_id_0,
911                 income_accno_id_1, expense_accno_id_1,
912                 income_accno_id_2, expense_accno_id_2,
913                 income_accno_id_3, expense_accno_id_3,
914                 sortkey)
915                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
916   }
917   do_query($form, $dbh, $query, @values);
918
919   $dbh->disconnect;
920
921   $main::lxdebug->leave_sub();
922 }
923
924 sub delete_buchungsgruppe {
925   $main::lxdebug->enter_sub();
926
927   my ($self, $myconfig, $form) = @_;
928
929   # connect to database
930   my $dbh = $form->dbconnect($myconfig);
931
932   $query = qq|DELETE FROM buchungsgruppen WHERE id = ?|;
933   do_query($form, $dbh, $query, $form->{id});
934
935   $dbh->disconnect;
936
937   $main::lxdebug->leave_sub();
938 }
939
940 sub swap_sortkeys {
941   $main::lxdebug->enter_sub();
942
943   my ($self, $myconfig, $form, $table) = @_;
944
945   # connect to database
946   my $dbh = $form->dbconnect_noauto($myconfig);
947
948   my $query =
949     qq|SELECT
950        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey1,
951        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey2|;
952   my @values = ($form->{"id1"}, $form->{"id2"});
953   my @sortkeys = selectrow_query($form, $dbh, $query, @values);
954   $main::lxdebug->dump(0, "v", \@values);
955   $main::lxdebug->dump(0, "s", \@sortkeys);
956
957   $query = qq|UPDATE $table SET sortkey = ? WHERE id = ?|;
958   my $sth = $dbh->prepare($query);
959   $sth->execute($sortkeys[1], $form->{"id1"}) ||
960     $form->dberror($query . " ($sortkeys[1], $form->{id1})");
961   $sth->execute($sortkeys[0], $form->{"id2"}) ||
962     $form->dberror($query . " ($sortkeys[0], $form->{id2})");
963   $sth->finish();
964
965   $dbh->commit();
966   $dbh->disconnect;
967
968   $main::lxdebug->leave_sub();
969 }
970
971 sub printer {
972   $main::lxdebug->enter_sub();
973
974   my ($self, $myconfig, $form) = @_;
975
976   # connect to database
977   my $dbh = $form->dbconnect($myconfig);
978
979   my $query = qq|SELECT id, printer_description, template_code, printer_command
980                  FROM printers
981                  ORDER BY 2|;
982
983   $sth = $dbh->prepare($query);
984   $sth->execute || $form->dberror($query);
985
986   $form->{"ALL"} = [];
987   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
988     push @{ $form->{ALL} }, $ref;
989   }
990
991   $sth->finish;
992   $dbh->disconnect;
993
994   $main::lxdebug->leave_sub();
995 }
996
997 sub get_printer {
998   $main::lxdebug->enter_sub();
999
1000   my ($self, $myconfig, $form) = @_;
1001
1002   # connect to database
1003   my $dbh = $form->dbconnect($myconfig);
1004
1005   my $query =
1006     qq|SELECT p.printer_description, p.template_code, p.printer_command
1007        FROM printers p
1008        WHERE p.id = ?|;
1009   my $sth = $dbh->prepare($query);
1010   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1011
1012   my $ref = $sth->fetchrow_hashref(NAME_lc);
1013
1014   map { $form->{$_} = $ref->{$_} } keys %$ref;
1015
1016   $sth->finish;
1017
1018   $dbh->disconnect;
1019
1020   $main::lxdebug->leave_sub();
1021 }
1022
1023 sub save_printer {
1024   $main::lxdebug->enter_sub();
1025
1026   my ($self, $myconfig, $form) = @_;
1027
1028   # connect to database
1029   my $dbh = $form->dbconnect($myconfig);
1030
1031   my @values = ($form->{printer_description},
1032                 $form->{template_code},
1033                 $form->{printer_command});
1034
1035   # id is the old record
1036   if ($form->{id}) {
1037     $query = qq|UPDATE printers SET
1038                 printer_description = ?, template_code = ?, printer_command = ?
1039                 WHERE id = ?|;
1040     push(@values, $form->{id});
1041   } else {
1042     $query = qq|INSERT INTO printers
1043                 (printer_description, template_code, printer_command)
1044                 VALUES (?, ?, ?)|;
1045   }
1046   do_query($form, $dbh, $query, @values);
1047
1048   $dbh->disconnect;
1049
1050   $main::lxdebug->leave_sub();
1051 }
1052
1053 sub delete_printer {
1054   $main::lxdebug->enter_sub();
1055
1056   my ($self, $myconfig, $form) = @_;
1057
1058   # connect to database
1059   my $dbh = $form->dbconnect($myconfig);
1060
1061   $query = qq|DELETE FROM printers
1062               WHERE id = ?|;
1063   do_query($form, $dbh, $query, $form->{id});
1064
1065   $dbh->disconnect;
1066
1067   $main::lxdebug->leave_sub();
1068 }
1069
1070 sub payment {
1071   $main::lxdebug->enter_sub();
1072
1073   my ($self, $myconfig, $form) = @_;
1074
1075   # connect to database
1076   my $dbh = $form->dbconnect($myconfig);
1077
1078   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
1079
1080   $sth = $dbh->prepare($query);
1081   $sth->execute || $form->dberror($query);
1082
1083   $form->{ALL} = [];
1084   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1085     push @{ $form->{ALL} }, $ref;
1086   }
1087
1088   $sth->finish;
1089   $dbh->disconnect;
1090
1091   $main::lxdebug->leave_sub();
1092 }
1093
1094 sub get_payment {
1095   $main::lxdebug->enter_sub();
1096
1097   my ($self, $myconfig, $form) = @_;
1098
1099   # connect to database
1100   my $dbh = $form->dbconnect($myconfig);
1101
1102   my $query = qq|SELECT * FROM payment_terms WHERE id = ?|;
1103   my $sth = $dbh->prepare($query);
1104   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1105
1106   my $ref = $sth->fetchrow_hashref(NAME_lc);
1107   map { $form->{$_} = $ref->{$_} } keys %$ref;
1108   $sth->finish();
1109
1110   $query =
1111     qq|SELECT t.language_id, t.description_long, l.description AS language | .
1112     qq|FROM translation_payment_terms t | .
1113     qq|LEFT JOIN language l ON t.language_id = l.id | .
1114     qq|WHERE t.payment_terms_id = ? | .
1115     qq|UNION | .
1116     qq|SELECT l.id AS language_id, NULL AS description_long, | .
1117     qq|  l.description AS language | .
1118     qq|FROM language l|;
1119   $sth = $dbh->prepare($query);
1120   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1121
1122   my %mapping;
1123   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1124     $mapping{ $ref->{"language_id"} } = $ref
1125       unless (defined($mapping{ $ref->{"language_id"} }));
1126   }
1127   $sth->finish;
1128
1129   $form->{"TRANSLATION"} = [sort({ $a->{"language"} cmp $b->{"language"} }
1130                                  values(%mapping))];
1131
1132   $dbh->disconnect;
1133
1134   $main::lxdebug->leave_sub();
1135 }
1136
1137 sub save_payment {
1138   $main::lxdebug->enter_sub();
1139
1140   my ($self, $myconfig, $form) = @_;
1141
1142   # connect to database
1143   my $dbh = $form->dbconnect_noauto($myconfig);
1144
1145   my $query;
1146
1147   if (!$form->{id}) {
1148     $query = qq|SELECT nextval('id'), COALESCE(MAX(sortkey) + 1, 1) | .
1149       qq|FROM payment_terms|;
1150     my $sortkey;
1151     ($form->{id}, $sortkey) = selectrow_query($form, $dbh, $query);
1152
1153     $query = qq|INSERT INTO payment_terms (id, sortkey) VALUES (?, ?)|;
1154     do_query($form, $dbh, $query, $form->{id}, $sortkey);
1155
1156   } else {
1157     $query =
1158       qq|DELETE FROM translation_payment_terms | .
1159       qq|WHERE payment_terms_id = ?|;
1160     do_query($form, $dbh, $query, $form->{"id"});
1161   }
1162
1163   $query = qq|UPDATE payment_terms SET
1164               description = ?, description_long = ?,
1165               ranking = ?,
1166               terms_netto = ?, terms_skonto = ?,
1167               percent_skonto = ?
1168               WHERE id = ?|;
1169   my @values = ($form->{description}, $form->{description_long},
1170                 $form->{ranking} * 1,
1171                 $form->{terms_netto} * 1, $form->{terms_skonto} * 1,
1172                 $form->{percent_skonto} * 1,
1173                 $form->{id});
1174   do_query($form, $dbh, $query, @values);
1175
1176   $query = qq|SELECT id FROM language|;
1177   my @language_ids;
1178   my $sth = $dbh->prepare($query);
1179   $sth->execute() || $form->dberror($query);
1180
1181   while (my ($id) = $sth->fetchrow_array()) {
1182     push(@language_ids, $id);
1183   }
1184   $sth->finish();
1185
1186   $query =
1187     qq|INSERT INTO translation_payment_terms | .
1188     qq|(language_id, payment_terms_id, description_long) | .
1189     qq|VALUES (?, ?, ?)|;
1190   $sth = $dbh->prepare($query);
1191
1192   foreach my $language_id (@language_ids) {
1193     do_statement($form, $sth, $query, $language_id, $form->{"id"},
1194                  $form->{"description_long_${language_id}"});
1195   }
1196   $sth->finish();
1197
1198   $dbh->commit();
1199   $dbh->disconnect;
1200
1201   $main::lxdebug->leave_sub();
1202 }
1203
1204 sub delete_payment {
1205   $main::lxdebug->enter_sub();
1206
1207   my ($self, $myconfig, $form) = @_;
1208
1209   # connect to database
1210   my $dbh = $form->dbconnect_noauto($myconfig);
1211
1212   my $query =
1213     qq|DELETE FROM translation_payment_terms WHERE payment_terms_id = ?|;
1214   do_query($form, $dbh, $query, $form->{"id"});
1215
1216   $query = qq|DELETE FROM payment_terms WHERE id = ?|;
1217   do_query($form, $dbh, $query, $form->{"id"});
1218
1219   $dbh->commit();
1220   $dbh->disconnect;
1221
1222   $main::lxdebug->leave_sub();
1223 }
1224
1225 sub load_template {
1226   $main::lxdebug->enter_sub();
1227
1228   my ($self, $form) = @_;
1229
1230   open(TEMPLATE, "$form->{file}") or $form->error("$form->{file} : $!");
1231
1232   while (<TEMPLATE>) {
1233     $form->{body} .= $_;
1234   }
1235
1236   close(TEMPLATE);
1237
1238   $main::lxdebug->leave_sub();
1239 }
1240
1241 sub save_template {
1242   $main::lxdebug->enter_sub();
1243
1244   my ($self, $form) = @_;
1245
1246   open(TEMPLATE, ">$form->{file}") or $form->error("$form->{file} : $!");
1247
1248   # strip
1249   $form->{body} =~ s/\r\n/\n/g;
1250   print TEMPLATE $form->{body};
1251
1252   close(TEMPLATE);
1253
1254   $main::lxdebug->leave_sub();
1255 }
1256
1257 sub save_preferences {
1258   $main::lxdebug->enter_sub();
1259
1260   my ($self, $myconfig, $form, $memberfile, $userspath, $webdav) = @_;
1261
1262   map { ($form->{$_}) = split(/--/, $form->{$_}) }
1263     qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno);
1264
1265   my @a;
1266   $form->{curr} =~ s/ //g;
1267   map { push(@a, uc pack "A3", $_) if $_ } split(/:/, $form->{curr});
1268   $form->{curr} = join ':', @a;
1269
1270   # connect to database
1271   my $dbh = $form->dbconnect_noauto($myconfig);
1272
1273   # these defaults are database wide
1274   # user specific variables are in myconfig
1275   # save defaults
1276   my $query =
1277     qq|UPDATE defaults SET | .
1278     qq|inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1279     qq|income_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1280     qq|expense_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1281     qq|fxgain_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1282     qq|fxloss_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1283     qq|invnumber = ?, | .
1284     qq|cnnumber  = ?, | .
1285     qq|sonumber = ?, | .
1286     qq|ponumber = ?, | .
1287     qq|sqnumber = ?, | .
1288     qq|rfqnumber = ?, | .
1289     qq|customernumber = ?, | .
1290     qq|vendornumber = ?, | .
1291     qq|articlenumber = ?, | .
1292     qq|servicenumber = ?, | .
1293     qq|yearend = ?, | .
1294     qq|curr = ?, | .
1295     qq|businessnumber = ?|;
1296   my @values = ($form->{inventory_accno}, $form->{income_accno},
1297                 $form->{expense_accno},
1298                 $form->{fxgain_accno}, $form->{fxloss_accno},
1299                 $form->{invnumber}, $form->{cnnumber},
1300                 $form->{sonumber}, $form->{ponumber},
1301                 $form->{sqnumber}, $form->{rfqnumber},
1302                 $form->{customernumber}, $form->{vendornumber},
1303                 $form->{articlenumber}, $form->{servicenumber},
1304                 $form->{yearend}, $form->{curr},
1305                 $form->{businessnumber});
1306   do_query($form, $dbh, $query, @values);
1307
1308   # update name
1309   $query = qq|UPDATE employee
1310               SET name = ?
1311               WHERE login = ?|;
1312   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1313
1314   my $rc = $dbh->commit;
1315   $dbh->disconnect;
1316
1317   # save first currency in myconfig
1318   $form->{currency} = substr($form->{curr}, 0, 3);
1319
1320   my $myconfig = new User "$memberfile", "$form->{login}";
1321
1322   foreach my $item (keys %$form) {
1323     $myconfig->{$item} = $form->{$item};
1324   }
1325
1326   $myconfig->save_member($memberfile, $userspath);
1327
1328   if ($webdav) {
1329     @webdavdirs =
1330       qw(angebote bestellungen rechnungen anfragen lieferantenbestellungen einkaufsrechnungen);
1331     foreach $directory (@webdavdirs) {
1332       $file = "webdav/" . $directory . "/webdav-user";
1333       if ($myconfig->{$directory}) {
1334         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1335         while (<HTACCESS>) {
1336           ($login, $password) = split(/:/, $_);
1337           if ($login ne $form->{login}) {
1338             $newfile .= $_;
1339           }
1340         }
1341         close(HTACCESS);
1342         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1343         $newfile .= $myconfig->{login} . ":" . $myconfig->{password} . "\n";
1344         print(HTACCESS $newfile);
1345         close(HTACCESS);
1346       } else {
1347         $form->{$directory} = 0;
1348         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1349         while (<HTACCESS>) {
1350           ($login, $password) = split(/:/, $_);
1351           if ($login ne $form->{login}) {
1352             $newfile .= $_;
1353           }
1354         }
1355         close(HTACCESS);
1356         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1357         print(HTACCESS $newfile);
1358         close(HTACCESS);
1359       }
1360     }
1361   }
1362
1363   $main::lxdebug->leave_sub();
1364
1365   return $rc;
1366 }
1367
1368 sub defaultaccounts {
1369   $main::lxdebug->enter_sub();
1370
1371   my ($self, $myconfig, $form) = @_;
1372
1373   # connect to database
1374   my $dbh = $form->dbconnect($myconfig);
1375
1376   # get defaults from defaults table
1377   my $query = qq|SELECT * FROM defaults|;
1378   my $sth   = $dbh->prepare($query);
1379   $sth->execute || $form->dberror($query);
1380
1381   $form->{defaults}             = $sth->fetchrow_hashref(NAME_lc);
1382   $form->{defaults}{IC}         = $form->{defaults}{inventory_accno_id};
1383   $form->{defaults}{IC_income}  = $form->{defaults}{income_accno_id};
1384   $form->{defaults}{IC_expense} = $form->{defaults}{expense_accno_id};
1385   $form->{defaults}{FX_gain}    = $form->{defaults}{fxgain_accno_id};
1386   $form->{defaults}{FX_loss}    = $form->{defaults}{fxloss_accno_id};
1387
1388   $sth->finish;
1389
1390   $query = qq|SELECT c.id, c.accno, c.description, c.link
1391               FROM chart c
1392               WHERE c.link LIKE '%IC%'
1393               ORDER BY c.accno|;
1394   $sth = $dbh->prepare($query);
1395   $sth->execute || $self->dberror($query);
1396
1397   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1398     foreach my $key (split(/:/, $ref->{link})) {
1399       if ($key =~ /IC/) {
1400         $nkey = $key;
1401         if ($key =~ /cogs/) {
1402           $nkey = "IC_expense";
1403         }
1404         if ($key =~ /sale/) {
1405           $nkey = "IC_income";
1406         }
1407         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1408                                              id          => $ref->{id},
1409                                              description => $ref->{description}
1410         );
1411       }
1412     }
1413   }
1414   $sth->finish;
1415
1416   $query = qq|SELECT c.id, c.accno, c.description
1417               FROM chart c
1418               WHERE c.category = 'I'
1419               AND c.charttype = 'A'
1420               ORDER BY c.accno|;
1421   $sth = $dbh->prepare($query);
1422   $sth->execute || $self->dberror($query);
1423
1424   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1425     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1426                                              id          => $ref->{id},
1427                                              description => $ref->{description}
1428     );
1429   }
1430   $sth->finish;
1431
1432   $query = qq|SELECT c.id, c.accno, c.description
1433               FROM chart c
1434               WHERE c.category = 'E'
1435               AND c.charttype = 'A'
1436               ORDER BY c.accno|;
1437   $sth = $dbh->prepare($query);
1438   $sth->execute || $self->dberror($query);
1439
1440   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1441     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1442                                              id          => $ref->{id},
1443                                              description => $ref->{description}
1444     );
1445   }
1446   $sth->finish;
1447
1448   # now get the tax rates and numbers
1449   $query = qq|SELECT c.id, c.accno, c.description,
1450               t.rate * 100 AS rate, t.taxnumber
1451               FROM chart c, tax t
1452               WHERE c.id = t.chart_id|;
1453
1454   $sth = $dbh->prepare($query);
1455   $sth->execute || $form->dberror($query);
1456
1457   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1458     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1459     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1460     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1461       if $ref->{taxnumber};
1462     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1463   }
1464
1465   $sth->finish;
1466   $dbh->disconnect;
1467
1468   $main::lxdebug->leave_sub();
1469 }
1470
1471 sub closedto {
1472   $main::lxdebug->enter_sub();
1473
1474   my ($self, $myconfig, $form) = @_;
1475
1476   my $dbh = $form->dbconnect($myconfig);
1477
1478   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1479   my $sth   = $dbh->prepare($query);
1480   $sth->execute || $form->dberror($query);
1481
1482   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1483
1484   $sth->finish;
1485
1486   $dbh->disconnect;
1487
1488   $main::lxdebug->leave_sub();
1489 }
1490
1491 sub closebooks {
1492   $main::lxdebug->enter_sub();
1493
1494   my ($self, $myconfig, $form) = @_;
1495
1496   my $dbh = $form->dbconnect($myconfig);
1497
1498   my ($query, @values);
1499
1500   if ($form->{revtrans}) {
1501     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1502
1503   } elsif ($form->{closedto}) {
1504     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1505     @values = (conv_date($form->{closedto}));
1506
1507   } else {
1508     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1509   }
1510
1511   # set close in defaults
1512   do_query($form, $dbh, $query, @values);
1513
1514   $dbh->disconnect;
1515
1516   $main::lxdebug->leave_sub();
1517 }
1518
1519 sub get_base_unit {
1520   my ($self, $units, $unit_name, $factor) = @_;
1521
1522   $factor = 1 unless ($factor);
1523
1524   my $unit = $units->{$unit_name};
1525
1526   if (!defined($unit) || !$unit->{"base_unit"} ||
1527       ($unit_name eq $unit->{"base_unit"})) {
1528     return ($unit_name, $factor);
1529   }
1530
1531   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1532 }
1533
1534 sub retrieve_units {
1535   $main::lxdebug->enter_sub();
1536
1537   my ($self, $myconfig, $form, $type, $prefix) = @_;
1538
1539   my $dbh = $form->dbconnect($myconfig);
1540
1541   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1542   my @values;
1543   if ($type) {
1544     $query .= " WHERE (type = ?)";
1545     @values = ($type);
1546   }
1547
1548   my $sth = $dbh->prepare($query);
1549   $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1550
1551   my $units = {};
1552   while (my $ref = $sth->fetchrow_hashref()) {
1553     $units->{$ref->{"name"}} = $ref;
1554   }
1555   $sth->finish();
1556
1557   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1558   $sth = $dbh->prepare($query_lang);
1559   $sth->execute() || $form->dberror($query_lang);
1560   my @languages;
1561   while ($ref = $sth->fetchrow_hashref()) {
1562     push(@languages, $ref);
1563   }
1564   $sth->finish();
1565
1566   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1567     "FROM units_language ul " .
1568     "LEFT JOIN language l ON ul.language_id = l.id " .
1569     "WHERE ul.unit = ?";
1570   $sth = $dbh->prepare($query_lang);
1571
1572   foreach my $unit (values(%{$units})) {
1573     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1574
1575     $unit->{"LANGUAGES"} = {};
1576     foreach my $lang (@languages) {
1577       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1578     }
1579
1580     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1581     while ($ref = $sth->fetchrow_hashref()) {
1582       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1583     }
1584   }
1585   $sth->finish();
1586
1587   $dbh->disconnect();
1588
1589   $main::lxdebug->leave_sub();
1590
1591   return $units;
1592 }
1593
1594 sub translate_units {
1595   $main::lxdebug->enter_sub();
1596
1597   my ($self, $form, $template_code, $unit, $amount) = @_;
1598
1599   my $units = $self->retrieve_units(\%main::myconfig, $form);
1600
1601   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1602   my $new_unit = $unit;
1603   if ($h) {
1604     if (($amount != 1) && $h->{"localized_plural"}) {
1605       $new_unit = $h->{"localized_plural"};
1606     } elsif ($h->{"localized"}) {
1607       $new_unit = $h->{"localized"};
1608     }
1609   }
1610
1611   $main::lxdebug->leave_sub();
1612
1613   return $new_unit;
1614 }
1615
1616 sub units_in_use {
1617   $main::lxdebug->enter_sub();
1618
1619   my ($self, $myconfig, $form, $units) = @_;
1620
1621   my $dbh = $form->dbconnect($myconfig);
1622
1623   map({ $_->{"in_use"} = 0; } values(%{$units}));
1624
1625   foreach my $unit (values(%{$units})) {
1626     my $base_unit = $unit->{"original_base_unit"};
1627     while ($base_unit) {
1628       $units->{$base_unit}->{"in_use"} = 1;
1629       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1630       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1631       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1632     }
1633   }
1634
1635   foreach my $unit (values(%{$units})) {
1636     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1637
1638     foreach my $table (qw(parts invoice orderitems)) {
1639       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1640
1641       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1642         $query .= "= " . $dbh->quote($unit->{"name"});
1643       } else {
1644         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1645           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1646       }
1647
1648       my ($count) = $dbh->selectrow_array($query);
1649       $form->dberror($query) if ($dbh->err);
1650
1651       if ($count) {
1652         $unit->{"in_use"} = 1;
1653         last;
1654       }
1655     }
1656   }
1657
1658   $dbh->disconnect();
1659
1660   $main::lxdebug->leave_sub();
1661 }
1662
1663 sub unit_select_data {
1664   $main::lxdebug->enter_sub();
1665
1666   my ($self, $units, $selected, $empty_entry) = @_;
1667
1668   my $select = [];
1669
1670   if ($empty_entry) {
1671     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1672   }
1673
1674   foreach my $unit (sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } keys(%{$units}))) {
1675     push(@{$select}, { "name" => $unit,
1676                        "base_unit" => $units->{$unit}->{"base_unit"},
1677                        "factor" => $units->{$unit}->{"factor"},
1678                        "selected" => ($unit eq $selected) ? "selected" : "" });
1679   }
1680
1681   $main::lxdebug->leave_sub();
1682
1683   return $select;
1684 }
1685
1686 sub unit_select_html {
1687   $main::lxdebug->enter_sub();
1688
1689   my ($self, $units, $name, $selected, $convertible_into) = @_;
1690
1691   my $select = "<select name=${name}>";
1692
1693   foreach my $unit (sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } keys(%{$units}))) {
1694     if (!$convertible_into ||
1695         ($units->{$convertible_into} &&
1696          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1697       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1698     }
1699   }
1700   $select .= "</select>";
1701
1702   $main::lxdebug->leave_sub();
1703
1704   return $select;
1705 }
1706
1707 sub add_unit {
1708   $main::lxdebug->enter_sub();
1709
1710   my ($self, $myconfig, $form, $name, $base_unit, $factor, $type, $languages) = @_;
1711
1712   my $dbh = $form->dbconnect_noauto($myconfig);
1713
1714   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1715   my ($sortkey) = selectrow_query($form, $dbh, $query);
1716
1717   $query = "INSERT INTO units (name, base_unit, factor, type, sortkey) " .
1718     "VALUES (?, ?, ?, ?, ?)";
1719   do_query($form, $dbh, $query, $name, $base_unit, $factor, $type, $sortkey);
1720
1721   if ($languages) {
1722     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1723     my $sth = $dbh->prepare($query);
1724     foreach my $lang (@{$languages}) {
1725       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1726       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1727     }
1728     $sth->finish();
1729   }
1730
1731   $dbh->commit();
1732   $dbh->disconnect();
1733
1734   $main::lxdebug->leave_sub();
1735 }
1736
1737 sub save_units {
1738   $main::lxdebug->enter_sub();
1739
1740   my ($self, $myconfig, $form, $type, $units, $delete_units) = @_;
1741
1742   my $dbh = $form->dbconnect_noauto($myconfig);
1743
1744   my ($base_unit, $unit, $sth, $query);
1745
1746   $query = "DELETE FROM units_language";
1747   $dbh->do($query) || $form->dberror($query);
1748
1749   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1750     $query = "DELETE FROM units WHERE name IN (";
1751     map({ $query .= "?," } @{$delete_units});
1752     substr($query, -1, 1) = ")";
1753     $dbh->do($query, undef, @{$delete_units}) ||
1754       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1755   }
1756
1757   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1758   $sth = $dbh->prepare($query);
1759
1760   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1761   my $sth_lang = $dbh->prepare($query_lang);
1762
1763   foreach $unit (values(%{$units})) {
1764     $unit->{"depth"} = 0;
1765     my $base_unit = $unit;
1766     while ($base_unit->{"base_unit"}) {
1767       $unit->{"depth"}++;
1768       $base_unit = $units->{$base_unit->{"base_unit"}};
1769     }
1770   }
1771
1772   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1773     if ($unit->{"LANGUAGES"}) {
1774       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1775         next unless ($lang->{"id"} && $lang->{"localized"});
1776         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1777         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1778       }
1779     }
1780
1781     next if ($unit->{"unchanged_unit"});
1782
1783     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1784     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1785   }
1786
1787   $sth->finish();
1788   $sth_lang->finish();
1789   $dbh->commit();
1790   $dbh->disconnect();
1791
1792   $main::lxdebug->leave_sub();
1793 }
1794
1795 sub swap_units {
1796   $main::lxdebug->enter_sub();
1797
1798   my ($self, $myconfig, $form, $dir, $name_1, $unit_type) = @_;
1799
1800   my $dbh = $form->dbconnect_noauto($myconfig);
1801
1802   my $query;
1803
1804   $query = qq|SELECT sortkey FROM units WHERE name = ?|;
1805   my ($sortkey_1) = selectrow_query($form, $dbh, $query, $name_1);
1806
1807   $query =
1808     qq|SELECT sortkey FROM units | .
1809     qq|WHERE sortkey | . ($dir eq "down" ? ">" : "<") . qq| ? AND type = ? | .
1810     qq|ORDER BY sortkey | . ($dir eq "down" ? "ASC" : "DESC") . qq| LIMIT 1|;
1811   my ($sortkey_2) = selectrow_query($form, $dbh, $query, $sortkey_1, $unit_type);
1812
1813   if (defined($sortkey_1)) {
1814     $query = qq|SELECT name FROM units WHERE sortkey = ${sortkey_2}|;
1815     my ($name_2) = selectrow_query($form, $dbh, $query);
1816
1817     if (defined($name_2)) {
1818       $query = qq|UPDATE units SET sortkey = ? WHERE name = ?|;
1819       my $sth = $dbh->prepare($query);
1820
1821       do_statement($form, $sth, $query, $sortkey_1, $name_2);
1822       do_statement($form, $sth, $query, $sortkey_2, $name_1);
1823     }
1824   }
1825
1826   $dbh->commit();
1827   $dbh->disconnect();
1828
1829   $main::lxdebug->leave_sub();
1830 }
1831
1832 1;