Dialogbuchen: Weitere Drop-Down-Boxen werden bei jedem Aufbau aus der Datenbank ausge...
[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, salesman
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, b.salesman
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}, $form->{salesman} ? 't' : 'f');
563   # id is the old record
564   if ($form->{id}) {
565     $query = qq|UPDATE business SET
566                 description = ?,
567                 discount = ?,
568                 customernumberinit = ?,
569                 salesman = ?
570                 WHERE id = ?|;
571     push(@values, $form->{id});
572   } else {
573     $query = qq|INSERT INTO business
574                 (description, discount, customernumberinit, salesman)
575                 VALUES (?, ?, ?, ?)|;
576   }
577   do_query($form, $dbh, $query, @values);
578
579   $dbh->disconnect;
580
581   $main::lxdebug->leave_sub();
582 }
583
584 sub delete_business {
585   $main::lxdebug->enter_sub();
586
587   my ($self, $myconfig, $form) = @_;
588
589   # connect to database
590   my $dbh = $form->dbconnect($myconfig);
591
592   $query = qq|DELETE FROM business
593               WHERE id = ?|;
594   do_query($form, $dbh, $query, $form->{id});
595
596   $dbh->disconnect;
597
598   $main::lxdebug->leave_sub();
599 }
600
601
602 sub language {
603   $main::lxdebug->enter_sub();
604
605   my ($self, $myconfig, $form, $return_list) = @_;
606
607   # connect to database
608   my $dbh = $form->dbconnect($myconfig);
609
610   my $query =
611     "SELECT id, description, template_code, article_code, " .
612     "  output_numberformat, output_dateformat, output_longdates " .
613     "FROM language ORDER BY description";
614
615   $sth = $dbh->prepare($query);
616   $sth->execute || $form->dberror($query);
617
618   my $ary = [];
619
620   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
621     push(@{ $ary }, $ref);
622   }
623
624   $sth->finish;
625   $dbh->disconnect;
626
627   $main::lxdebug->leave_sub();
628
629   if ($return_list) {
630     return @{$ary};
631   } else {
632     $form->{ALL} = $ary;
633   }
634 }
635
636 sub get_language {
637   $main::lxdebug->enter_sub();
638
639   my ($self, $myconfig, $form) = @_;
640
641   # connect to database
642   my $dbh = $form->dbconnect($myconfig);
643
644   my $query =
645     "SELECT description, template_code, article_code, " .
646     "  output_numberformat, output_dateformat, output_longdates " .
647     "FROM language WHERE id = ?";
648   my $sth = $dbh->prepare($query);
649   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
650
651   my $ref = $sth->fetchrow_hashref(NAME_lc);
652
653   map { $form->{$_} = $ref->{$_} } keys %$ref;
654
655   $sth->finish;
656
657   $dbh->disconnect;
658
659   $main::lxdebug->leave_sub();
660 }
661
662 sub get_language_details {
663   $main::lxdebug->enter_sub();
664
665   my ($self, $myconfig, $form, $id) = @_;
666
667   # connect to database
668   my $dbh = $form->dbconnect($myconfig);
669
670   my $query =
671     "SELECT template_code, " .
672     "  output_numberformat, output_dateformat, output_longdates " .
673     "FROM language WHERE id = ?";
674   my @res = selectrow_query($form, $dbh, $query, $id);
675   $dbh->disconnect;
676
677   $main::lxdebug->leave_sub();
678
679   return @res;
680 }
681
682 sub save_language {
683   $main::lxdebug->enter_sub();
684
685   my ($self, $myconfig, $form) = @_;
686
687   # connect to database
688   my $dbh = $form->dbconnect($myconfig);
689   my (@values, $query);
690
691   map({ push(@values, $form->{$_}); }
692       qw(description template_code article_code
693          output_numberformat output_dateformat output_longdates));
694
695   # id is the old record
696   if ($form->{id}) {
697     $query =
698       "UPDATE language SET " .
699       "  description = ?, template_code = ?, article_code = ?, " .
700       "  output_numberformat = ?, output_dateformat = ?, " .
701       "  output_longdates = ? " .
702       "WHERE id = ?";
703     push(@values, $form->{id});
704   } else {
705     $query =
706       "INSERT INTO language (" .
707       "  description, template_code, article_code, " .
708       "  output_numberformat, output_dateformat, output_longdates" .
709       ") VALUES (?, ?, ?, ?, ?, ?)";
710   }
711   do_query($form, $dbh, $query, @values);
712
713   $dbh->disconnect;
714
715   $main::lxdebug->leave_sub();
716 }
717
718 sub delete_language {
719   $main::lxdebug->enter_sub();
720
721   my ($self, $myconfig, $form) = @_;
722
723   # connect to database
724   my $dbh = $form->dbconnect_noauto($myconfig);
725
726   foreach my $table (qw(translation_payment_terms units_language)) {
727     my $query = qq|DELETE FROM $table WHERE language_id = ?|;
728     do_query($form, $dbh, $query, $form->{"id"});
729   }
730
731   $query = "DELETE FROM language WHERE id = ?";
732   do_query($form, $dbh, $query, $form->{"id"});
733
734   $dbh->commit();
735   $dbh->disconnect;
736
737   $main::lxdebug->leave_sub();
738 }
739
740
741 sub buchungsgruppe {
742   $main::lxdebug->enter_sub();
743
744   my ($self, $myconfig, $form) = @_;
745
746   # connect to database
747   my $dbh = $form->dbconnect($myconfig);
748
749   my $query = qq|SELECT id, description,
750                  inventory_accno_id,
751                  (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
752                  income_accno_id_0,
753                  (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
754                  expense_accno_id_0,
755                  (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
756                  income_accno_id_1,
757                  (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
758                  expense_accno_id_1,
759                  (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
760                  income_accno_id_2,
761                  (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
762                  expense_accno_id_2,
763                  (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
764                  income_accno_id_3,
765                  (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
766                  expense_accno_id_3,
767                  (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
768                  FROM buchungsgruppen
769                  ORDER BY sortkey|;
770
771   $sth = $dbh->prepare($query);
772   $sth->execute || $form->dberror($query);
773
774   $form->{ALL} = [];
775   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
776     push @{ $form->{ALL} }, $ref;
777   }
778
779   $sth->finish;
780   $dbh->disconnect;
781
782   $main::lxdebug->leave_sub();
783 }
784
785 sub get_buchungsgruppe {
786   $main::lxdebug->enter_sub();
787
788   my ($self, $myconfig, $form) = @_;
789
790   # connect to database
791   my $dbh = $form->dbconnect($myconfig);
792
793   if ($form->{id}) {
794     my $query =
795       qq|SELECT description, inventory_accno_id,
796          (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
797          income_accno_id_0,
798          (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
799          expense_accno_id_0,
800          (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
801          income_accno_id_1,
802          (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
803          expense_accno_id_1,
804          (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
805          income_accno_id_2,
806          (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
807          expense_accno_id_2,
808          (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
809          income_accno_id_3,
810          (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
811          expense_accno_id_3,
812          (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
813          FROM buchungsgruppen
814          WHERE id = ?|;
815     my $sth = $dbh->prepare($query);
816     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
817
818     my $ref = $sth->fetchrow_hashref(NAME_lc);
819
820     map { $form->{$_} = $ref->{$_} } keys %$ref;
821
822     $sth->finish;
823
824     my $query =
825       qq|SELECT count(id) = 0 AS orphaned
826          FROM parts
827          WHERE buchungsgruppen_id = ?|;
828     ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
829   }
830
831   $query = "SELECT inventory_accno_id, income_accno_id, expense_accno_id ".
832     "FROM defaults";
833   ($form->{"std_inventory_accno_id"}, $form->{"std_income_accno_id"},
834    $form->{"std_expense_accno_id"}) = selectrow_query($form, $dbh, $query);
835
836   my $module = "IC";
837   $query = qq|SELECT c.accno, c.description, c.link, c.id,
838               d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
839               FROM chart c, defaults d
840               WHERE c.link LIKE '%$module%'
841               ORDER BY c.accno|;
842
843
844   my $sth = $dbh->prepare($query);
845   $sth->execute || $form->dberror($query);
846   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
847     foreach my $key (split(/:/, $ref->{link})) {
848       if (!$form->{"std_inventory_accno_id"} && ($key eq "IC")) {
849         $form->{"std_inventory_accno_id"} = $ref->{"id"};
850       }
851       if ($key =~ /$module/) {
852         if (   ($ref->{id} eq $ref->{inventory_accno_id})
853             || ($ref->{id} eq $ref->{income_accno_id})
854             || ($ref->{id} eq $ref->{expense_accno_id})) {
855           push @{ $form->{"${module}_links"}{$key} },
856             { accno       => $ref->{accno},
857               description => $ref->{description},
858               selected    => "selected",
859               id          => $ref->{id} };
860         } else {
861           push @{ $form->{"${module}_links"}{$key} },
862             { accno       => $ref->{accno},
863               description => $ref->{description},
864               selected    => "",
865               id          => $ref->{id} };
866         }
867       }
868     }
869   }
870   $sth->finish;
871
872
873   $dbh->disconnect;
874
875   $main::lxdebug->leave_sub();
876 }
877
878 sub save_buchungsgruppe {
879   $main::lxdebug->enter_sub();
880
881   my ($self, $myconfig, $form) = @_;
882
883   # connect to database
884   my $dbh = $form->dbconnect($myconfig);
885
886   my @values = ($form->{description}, $form->{inventory_accno_id},
887                 $form->{income_accno_id_0}, $form->{expense_accno_id_0},
888                 $form->{income_accno_id_1}, $form->{expense_accno_id_1},
889                 $form->{income_accno_id_2}, $form->{expense_accno_id_2},
890                 $form->{income_accno_id_3}, $form->{expense_accno_id_3});
891
892   my $query;
893
894   # id is the old record
895   if ($form->{id}) {
896     $query = qq|UPDATE buchungsgruppen SET
897                 description = ?, inventory_accno_id = ?,
898                 income_accno_id_0 = ?, expense_accno_id_0 = ?,
899                 income_accno_id_1 = ?, expense_accno_id_1 = ?,
900                 income_accno_id_2 = ?, expense_accno_id_2 = ?,
901                 income_accno_id_3 = ?, expense_accno_id_3 = ?
902                 WHERE id = ?|;
903     push(@values, $form->{id});
904   } else {
905     $query = qq|SELECT COALESCE(MAX(sortkey) + 1, 1) FROM buchungsgruppen|;
906     my ($sortkey) = $dbh->selectrow_array($query);
907     $form->dberror($query) if ($dbh->err);
908     push(@values, $sortkey);
909     $query = qq|INSERT INTO buchungsgruppen
910                 (description, inventory_accno_id,
911                 income_accno_id_0, expense_accno_id_0,
912                 income_accno_id_1, expense_accno_id_1,
913                 income_accno_id_2, expense_accno_id_2,
914                 income_accno_id_3, expense_accno_id_3,
915                 sortkey)
916                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
917   }
918   do_query($form, $dbh, $query, @values);
919
920   $dbh->disconnect;
921
922   $main::lxdebug->leave_sub();
923 }
924
925 sub delete_buchungsgruppe {
926   $main::lxdebug->enter_sub();
927
928   my ($self, $myconfig, $form) = @_;
929
930   # connect to database
931   my $dbh = $form->dbconnect($myconfig);
932
933   $query = qq|DELETE FROM buchungsgruppen WHERE id = ?|;
934   do_query($form, $dbh, $query, $form->{id});
935
936   $dbh->disconnect;
937
938   $main::lxdebug->leave_sub();
939 }
940
941 sub swap_sortkeys {
942   $main::lxdebug->enter_sub();
943
944   my ($self, $myconfig, $form, $table) = @_;
945
946   # connect to database
947   my $dbh = $form->dbconnect_noauto($myconfig);
948
949   my $query =
950     qq|SELECT
951        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey1,
952        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey2|;
953   my @values = ($form->{"id1"}, $form->{"id2"});
954   my @sortkeys = selectrow_query($form, $dbh, $query, @values);
955   $main::lxdebug->dump(0, "v", \@values);
956   $main::lxdebug->dump(0, "s", \@sortkeys);
957
958   $query = qq|UPDATE $table SET sortkey = ? WHERE id = ?|;
959   my $sth = $dbh->prepare($query);
960   $sth->execute($sortkeys[1], $form->{"id1"}) ||
961     $form->dberror($query . " ($sortkeys[1], $form->{id1})");
962   $sth->execute($sortkeys[0], $form->{"id2"}) ||
963     $form->dberror($query . " ($sortkeys[0], $form->{id2})");
964   $sth->finish();
965
966   $dbh->commit();
967   $dbh->disconnect;
968
969   $main::lxdebug->leave_sub();
970 }
971
972 sub printer {
973   $main::lxdebug->enter_sub();
974
975   my ($self, $myconfig, $form) = @_;
976
977   # connect to database
978   my $dbh = $form->dbconnect($myconfig);
979
980   my $query = qq|SELECT id, printer_description, template_code, printer_command
981                  FROM printers
982                  ORDER BY 2|;
983
984   $sth = $dbh->prepare($query);
985   $sth->execute || $form->dberror($query);
986
987   $form->{"ALL"} = [];
988   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
989     push @{ $form->{ALL} }, $ref;
990   }
991
992   $sth->finish;
993   $dbh->disconnect;
994
995   $main::lxdebug->leave_sub();
996 }
997
998 sub get_printer {
999   $main::lxdebug->enter_sub();
1000
1001   my ($self, $myconfig, $form) = @_;
1002
1003   # connect to database
1004   my $dbh = $form->dbconnect($myconfig);
1005
1006   my $query =
1007     qq|SELECT p.printer_description, p.template_code, p.printer_command
1008        FROM printers p
1009        WHERE p.id = ?|;
1010   my $sth = $dbh->prepare($query);
1011   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1012
1013   my $ref = $sth->fetchrow_hashref(NAME_lc);
1014
1015   map { $form->{$_} = $ref->{$_} } keys %$ref;
1016
1017   $sth->finish;
1018
1019   $dbh->disconnect;
1020
1021   $main::lxdebug->leave_sub();
1022 }
1023
1024 sub save_printer {
1025   $main::lxdebug->enter_sub();
1026
1027   my ($self, $myconfig, $form) = @_;
1028
1029   # connect to database
1030   my $dbh = $form->dbconnect($myconfig);
1031
1032   my @values = ($form->{printer_description},
1033                 $form->{template_code},
1034                 $form->{printer_command});
1035
1036   # id is the old record
1037   if ($form->{id}) {
1038     $query = qq|UPDATE printers SET
1039                 printer_description = ?, template_code = ?, printer_command = ?
1040                 WHERE id = ?|;
1041     push(@values, $form->{id});
1042   } else {
1043     $query = qq|INSERT INTO printers
1044                 (printer_description, template_code, printer_command)
1045                 VALUES (?, ?, ?)|;
1046   }
1047   do_query($form, $dbh, $query, @values);
1048
1049   $dbh->disconnect;
1050
1051   $main::lxdebug->leave_sub();
1052 }
1053
1054 sub delete_printer {
1055   $main::lxdebug->enter_sub();
1056
1057   my ($self, $myconfig, $form) = @_;
1058
1059   # connect to database
1060   my $dbh = $form->dbconnect($myconfig);
1061
1062   $query = qq|DELETE FROM printers
1063               WHERE id = ?|;
1064   do_query($form, $dbh, $query, $form->{id});
1065
1066   $dbh->disconnect;
1067
1068   $main::lxdebug->leave_sub();
1069 }
1070
1071 sub payment {
1072   $main::lxdebug->enter_sub();
1073
1074   my ($self, $myconfig, $form) = @_;
1075
1076   # connect to database
1077   my $dbh = $form->dbconnect($myconfig);
1078
1079   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
1080
1081   $sth = $dbh->prepare($query);
1082   $sth->execute || $form->dberror($query);
1083
1084   $form->{ALL} = [];
1085   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1086     push @{ $form->{ALL} }, $ref;
1087   }
1088
1089   $sth->finish;
1090   $dbh->disconnect;
1091
1092   $main::lxdebug->leave_sub();
1093 }
1094
1095 sub get_payment {
1096   $main::lxdebug->enter_sub();
1097
1098   my ($self, $myconfig, $form) = @_;
1099
1100   # connect to database
1101   my $dbh = $form->dbconnect($myconfig);
1102
1103   my $query = qq|SELECT * FROM payment_terms WHERE id = ?|;
1104   my $sth = $dbh->prepare($query);
1105   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1106
1107   my $ref = $sth->fetchrow_hashref(NAME_lc);
1108   map { $form->{$_} = $ref->{$_} } keys %$ref;
1109   $sth->finish();
1110
1111   $query =
1112     qq|SELECT t.language_id, t.description_long, l.description AS language | .
1113     qq|FROM translation_payment_terms t | .
1114     qq|LEFT JOIN language l ON t.language_id = l.id | .
1115     qq|WHERE t.payment_terms_id = ? | .
1116     qq|UNION | .
1117     qq|SELECT l.id AS language_id, NULL AS description_long, | .
1118     qq|  l.description AS language | .
1119     qq|FROM language l|;
1120   $sth = $dbh->prepare($query);
1121   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1122
1123   my %mapping;
1124   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1125     $mapping{ $ref->{"language_id"} } = $ref
1126       unless (defined($mapping{ $ref->{"language_id"} }));
1127   }
1128   $sth->finish;
1129
1130   $form->{"TRANSLATION"} = [sort({ $a->{"language"} cmp $b->{"language"} }
1131                                  values(%mapping))];
1132
1133   $dbh->disconnect;
1134
1135   $main::lxdebug->leave_sub();
1136 }
1137
1138 sub save_payment {
1139   $main::lxdebug->enter_sub();
1140
1141   my ($self, $myconfig, $form) = @_;
1142
1143   # connect to database
1144   my $dbh = $form->dbconnect_noauto($myconfig);
1145
1146   my $query;
1147
1148   if (!$form->{id}) {
1149     $query = qq|SELECT nextval('id'), COALESCE(MAX(sortkey) + 1, 1) | .
1150       qq|FROM payment_terms|;
1151     my $sortkey;
1152     ($form->{id}, $sortkey) = selectrow_query($form, $dbh, $query);
1153
1154     $query = qq|INSERT INTO payment_terms (id, sortkey) VALUES (?, ?)|;
1155     do_query($form, $dbh, $query, $form->{id}, $sortkey);
1156
1157   } else {
1158     $query =
1159       qq|DELETE FROM translation_payment_terms | .
1160       qq|WHERE payment_terms_id = ?|;
1161     do_query($form, $dbh, $query, $form->{"id"});
1162   }
1163
1164   $query = qq|UPDATE payment_terms SET
1165               description = ?, description_long = ?,
1166               ranking = ?,
1167               terms_netto = ?, terms_skonto = ?,
1168               percent_skonto = ?
1169               WHERE id = ?|;
1170   my @values = ($form->{description}, $form->{description_long},
1171                 $form->{ranking} * 1,
1172                 $form->{terms_netto} * 1, $form->{terms_skonto} * 1,
1173                 $form->{percent_skonto} * 1,
1174                 $form->{id});
1175   do_query($form, $dbh, $query, @values);
1176
1177   $query = qq|SELECT id FROM language|;
1178   my @language_ids;
1179   my $sth = $dbh->prepare($query);
1180   $sth->execute() || $form->dberror($query);
1181
1182   while (my ($id) = $sth->fetchrow_array()) {
1183     push(@language_ids, $id);
1184   }
1185   $sth->finish();
1186
1187   $query =
1188     qq|INSERT INTO translation_payment_terms | .
1189     qq|(language_id, payment_terms_id, description_long) | .
1190     qq|VALUES (?, ?, ?)|;
1191   $sth = $dbh->prepare($query);
1192
1193   foreach my $language_id (@language_ids) {
1194     do_statement($form, $sth, $query, $language_id, $form->{"id"},
1195                  $form->{"description_long_${language_id}"});
1196   }
1197   $sth->finish();
1198
1199   $dbh->commit();
1200   $dbh->disconnect;
1201
1202   $main::lxdebug->leave_sub();
1203 }
1204
1205 sub delete_payment {
1206   $main::lxdebug->enter_sub();
1207
1208   my ($self, $myconfig, $form) = @_;
1209
1210   # connect to database
1211   my $dbh = $form->dbconnect_noauto($myconfig);
1212
1213   my $query =
1214     qq|DELETE FROM translation_payment_terms WHERE payment_terms_id = ?|;
1215   do_query($form, $dbh, $query, $form->{"id"});
1216
1217   $query = qq|DELETE FROM payment_terms WHERE id = ?|;
1218   do_query($form, $dbh, $query, $form->{"id"});
1219
1220   $dbh->commit();
1221   $dbh->disconnect;
1222
1223   $main::lxdebug->leave_sub();
1224 }
1225
1226 sub load_template {
1227   $main::lxdebug->enter_sub();
1228
1229   my ($self, $form) = @_;
1230
1231   open(TEMPLATE, "$form->{file}") or $form->error("$form->{file} : $!");
1232
1233   while (<TEMPLATE>) {
1234     $form->{body} .= $_;
1235   }
1236
1237   close(TEMPLATE);
1238
1239   $main::lxdebug->leave_sub();
1240 }
1241
1242 sub save_template {
1243   $main::lxdebug->enter_sub();
1244
1245   my ($self, $form) = @_;
1246
1247   open(TEMPLATE, ">$form->{file}") or $form->error("$form->{file} : $!");
1248
1249   # strip
1250   $form->{body} =~ s/\r\n/\n/g;
1251   print TEMPLATE $form->{body};
1252
1253   close(TEMPLATE);
1254
1255   $main::lxdebug->leave_sub();
1256 }
1257
1258 sub save_preferences {
1259   $main::lxdebug->enter_sub();
1260
1261   my ($self, $myconfig, $form, $memberfile, $userspath, $webdav) = @_;
1262
1263   map { ($form->{$_}) = split(/--/, $form->{$_}) }
1264     qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno);
1265
1266   my @a;
1267   $form->{curr} =~ s/ //g;
1268   map { push(@a, uc pack "A3", $_) if $_ } split(/:/, $form->{curr});
1269   $form->{curr} = join ':', @a;
1270
1271   # connect to database
1272   my $dbh = $form->dbconnect_noauto($myconfig);
1273
1274   # these defaults are database wide
1275   # user specific variables are in myconfig
1276   # save defaults
1277   my $query =
1278     qq|UPDATE defaults SET | .
1279     qq|inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1280     qq|income_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1281     qq|expense_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1282     qq|fxgain_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1283     qq|fxloss_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1284     qq|invnumber = ?, | .
1285     qq|cnnumber  = ?, | .
1286     qq|sonumber = ?, | .
1287     qq|ponumber = ?, | .
1288     qq|sqnumber = ?, | .
1289     qq|rfqnumber = ?, | .
1290     qq|customernumber = ?, | .
1291     qq|vendornumber = ?, | .
1292     qq|articlenumber = ?, | .
1293     qq|servicenumber = ?, | .
1294     qq|yearend = ?, | .
1295     qq|curr = ?, | .
1296     qq|businessnumber = ?|;
1297   my @values = ($form->{inventory_accno}, $form->{income_accno},
1298                 $form->{expense_accno},
1299                 $form->{fxgain_accno}, $form->{fxloss_accno},
1300                 $form->{invnumber}, $form->{cnnumber},
1301                 $form->{sonumber}, $form->{ponumber},
1302                 $form->{sqnumber}, $form->{rfqnumber},
1303                 $form->{customernumber}, $form->{vendornumber},
1304                 $form->{articlenumber}, $form->{servicenumber},
1305                 $form->{yearend}, $form->{curr},
1306                 $form->{businessnumber});
1307   do_query($form, $dbh, $query, @values);
1308
1309   # update name
1310   $query = qq|UPDATE employee
1311               SET name = ?
1312               WHERE login = ?|;
1313   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1314
1315   my $rc = $dbh->commit;
1316   $dbh->disconnect;
1317
1318   # save first currency in myconfig
1319   $form->{currency} = substr($form->{curr}, 0, 3);
1320
1321   my $myconfig = new User "$memberfile", "$form->{login}";
1322
1323   foreach my $item (keys %$form) {
1324     $myconfig->{$item} = $form->{$item};
1325   }
1326
1327   $myconfig->save_member($memberfile, $userspath);
1328
1329   if ($webdav) {
1330     @webdavdirs =
1331       qw(angebote bestellungen rechnungen anfragen lieferantenbestellungen einkaufsrechnungen);
1332     foreach $directory (@webdavdirs) {
1333       $file = "webdav/" . $directory . "/webdav-user";
1334       if ($myconfig->{$directory}) {
1335         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1336         while (<HTACCESS>) {
1337           ($login, $password) = split(/:/, $_);
1338           if ($login ne $form->{login}) {
1339             $newfile .= $_;
1340           }
1341         }
1342         close(HTACCESS);
1343         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1344         $newfile .= $myconfig->{login} . ":" . $myconfig->{password} . "\n";
1345         print(HTACCESS $newfile);
1346         close(HTACCESS);
1347       } else {
1348         $form->{$directory} = 0;
1349         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1350         while (<HTACCESS>) {
1351           ($login, $password) = split(/:/, $_);
1352           if ($login ne $form->{login}) {
1353             $newfile .= $_;
1354           }
1355         }
1356         close(HTACCESS);
1357         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1358         print(HTACCESS $newfile);
1359         close(HTACCESS);
1360       }
1361     }
1362   }
1363
1364   $main::lxdebug->leave_sub();
1365
1366   return $rc;
1367 }
1368
1369 sub defaultaccounts {
1370   $main::lxdebug->enter_sub();
1371
1372   my ($self, $myconfig, $form) = @_;
1373
1374   # connect to database
1375   my $dbh = $form->dbconnect($myconfig);
1376
1377   # get defaults from defaults table
1378   my $query = qq|SELECT * FROM defaults|;
1379   my $sth   = $dbh->prepare($query);
1380   $sth->execute || $form->dberror($query);
1381
1382   $form->{defaults}             = $sth->fetchrow_hashref(NAME_lc);
1383   $form->{defaults}{IC}         = $form->{defaults}{inventory_accno_id};
1384   $form->{defaults}{IC_income}  = $form->{defaults}{income_accno_id};
1385   $form->{defaults}{IC_expense} = $form->{defaults}{expense_accno_id};
1386   $form->{defaults}{FX_gain}    = $form->{defaults}{fxgain_accno_id};
1387   $form->{defaults}{FX_loss}    = $form->{defaults}{fxloss_accno_id};
1388
1389   $sth->finish;
1390
1391   $query = qq|SELECT c.id, c.accno, c.description, c.link
1392               FROM chart c
1393               WHERE c.link LIKE '%IC%'
1394               ORDER BY c.accno|;
1395   $sth = $dbh->prepare($query);
1396   $sth->execute || $self->dberror($query);
1397
1398   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1399     foreach my $key (split(/:/, $ref->{link})) {
1400       if ($key =~ /IC/) {
1401         $nkey = $key;
1402         if ($key =~ /cogs/) {
1403           $nkey = "IC_expense";
1404         }
1405         if ($key =~ /sale/) {
1406           $nkey = "IC_income";
1407         }
1408         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1409                                              id          => $ref->{id},
1410                                              description => $ref->{description}
1411         );
1412       }
1413     }
1414   }
1415   $sth->finish;
1416
1417   $query = qq|SELECT c.id, c.accno, c.description
1418               FROM chart c
1419               WHERE c.category = 'I'
1420               AND c.charttype = 'A'
1421               ORDER BY c.accno|;
1422   $sth = $dbh->prepare($query);
1423   $sth->execute || $self->dberror($query);
1424
1425   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1426     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1427                                              id          => $ref->{id},
1428                                              description => $ref->{description}
1429     );
1430   }
1431   $sth->finish;
1432
1433   $query = qq|SELECT c.id, c.accno, c.description
1434               FROM chart c
1435               WHERE c.category = 'E'
1436               AND c.charttype = 'A'
1437               ORDER BY c.accno|;
1438   $sth = $dbh->prepare($query);
1439   $sth->execute || $self->dberror($query);
1440
1441   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1442     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1443                                              id          => $ref->{id},
1444                                              description => $ref->{description}
1445     );
1446   }
1447   $sth->finish;
1448
1449   # now get the tax rates and numbers
1450   $query = qq|SELECT c.id, c.accno, c.description,
1451               t.rate * 100 AS rate, t.taxnumber
1452               FROM chart c, tax t
1453               WHERE c.id = t.chart_id|;
1454
1455   $sth = $dbh->prepare($query);
1456   $sth->execute || $form->dberror($query);
1457
1458   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1459     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1460     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1461     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1462       if $ref->{taxnumber};
1463     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1464   }
1465
1466   $sth->finish;
1467   $dbh->disconnect;
1468
1469   $main::lxdebug->leave_sub();
1470 }
1471
1472 sub closedto {
1473   $main::lxdebug->enter_sub();
1474
1475   my ($self, $myconfig, $form) = @_;
1476
1477   my $dbh = $form->dbconnect($myconfig);
1478
1479   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1480   my $sth   = $dbh->prepare($query);
1481   $sth->execute || $form->dberror($query);
1482
1483   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1484
1485   $sth->finish;
1486
1487   $dbh->disconnect;
1488
1489   $main::lxdebug->leave_sub();
1490 }
1491
1492 sub closebooks {
1493   $main::lxdebug->enter_sub();
1494
1495   my ($self, $myconfig, $form) = @_;
1496
1497   my $dbh = $form->dbconnect($myconfig);
1498
1499   my ($query, @values);
1500
1501   if ($form->{revtrans}) {
1502     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1503
1504   } elsif ($form->{closedto}) {
1505     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1506     @values = (conv_date($form->{closedto}));
1507
1508   } else {
1509     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1510   }
1511
1512   # set close in defaults
1513   do_query($form, $dbh, $query, @values);
1514
1515   $dbh->disconnect;
1516
1517   $main::lxdebug->leave_sub();
1518 }
1519
1520 sub get_base_unit {
1521   my ($self, $units, $unit_name, $factor) = @_;
1522
1523   $factor = 1 unless ($factor);
1524
1525   my $unit = $units->{$unit_name};
1526
1527   if (!defined($unit) || !$unit->{"base_unit"} ||
1528       ($unit_name eq $unit->{"base_unit"})) {
1529     return ($unit_name, $factor);
1530   }
1531
1532   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1533 }
1534
1535 sub retrieve_units {
1536   $main::lxdebug->enter_sub();
1537
1538   my ($self, $myconfig, $form, $type, $prefix) = @_;
1539
1540   my $dbh = $form->dbconnect($myconfig);
1541
1542   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1543   my @values;
1544   if ($type) {
1545     $query .= " WHERE (type = ?)";
1546     @values = ($type);
1547   }
1548
1549   my $sth = $dbh->prepare($query);
1550   $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1551
1552   my $units = {};
1553   while (my $ref = $sth->fetchrow_hashref()) {
1554     $units->{$ref->{"name"}} = $ref;
1555   }
1556   $sth->finish();
1557
1558   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1559   $sth = $dbh->prepare($query_lang);
1560   $sth->execute() || $form->dberror($query_lang);
1561   my @languages;
1562   while ($ref = $sth->fetchrow_hashref()) {
1563     push(@languages, $ref);
1564   }
1565   $sth->finish();
1566
1567   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1568     "FROM units_language ul " .
1569     "LEFT JOIN language l ON ul.language_id = l.id " .
1570     "WHERE ul.unit = ?";
1571   $sth = $dbh->prepare($query_lang);
1572
1573   foreach my $unit (values(%{$units})) {
1574     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1575
1576     $unit->{"LANGUAGES"} = {};
1577     foreach my $lang (@languages) {
1578       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1579     }
1580
1581     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1582     while ($ref = $sth->fetchrow_hashref()) {
1583       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1584     }
1585   }
1586   $sth->finish();
1587
1588   $dbh->disconnect();
1589
1590   $main::lxdebug->leave_sub();
1591
1592   return $units;
1593 }
1594
1595 sub translate_units {
1596   $main::lxdebug->enter_sub();
1597
1598   my ($self, $form, $template_code, $unit, $amount) = @_;
1599
1600   my $units = $self->retrieve_units(\%main::myconfig, $form);
1601
1602   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1603   my $new_unit = $unit;
1604   if ($h) {
1605     if (($amount != 1) && $h->{"localized_plural"}) {
1606       $new_unit = $h->{"localized_plural"};
1607     } elsif ($h->{"localized"}) {
1608       $new_unit = $h->{"localized"};
1609     }
1610   }
1611
1612   $main::lxdebug->leave_sub();
1613
1614   return $new_unit;
1615 }
1616
1617 sub units_in_use {
1618   $main::lxdebug->enter_sub();
1619
1620   my ($self, $myconfig, $form, $units) = @_;
1621
1622   my $dbh = $form->dbconnect($myconfig);
1623
1624   map({ $_->{"in_use"} = 0; } values(%{$units}));
1625
1626   foreach my $unit (values(%{$units})) {
1627     my $base_unit = $unit->{"original_base_unit"};
1628     while ($base_unit) {
1629       $units->{$base_unit}->{"in_use"} = 1;
1630       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1631       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1632       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1633     }
1634   }
1635
1636   foreach my $unit (values(%{$units})) {
1637     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1638
1639     foreach my $table (qw(parts invoice orderitems)) {
1640       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1641
1642       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1643         $query .= "= " . $dbh->quote($unit->{"name"});
1644       } else {
1645         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1646           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1647       }
1648
1649       my ($count) = $dbh->selectrow_array($query);
1650       $form->dberror($query) if ($dbh->err);
1651
1652       if ($count) {
1653         $unit->{"in_use"} = 1;
1654         last;
1655       }
1656     }
1657   }
1658
1659   $dbh->disconnect();
1660
1661   $main::lxdebug->leave_sub();
1662 }
1663
1664 sub unit_select_data {
1665   $main::lxdebug->enter_sub();
1666
1667   my ($self, $units, $selected, $empty_entry) = @_;
1668
1669   my $select = [];
1670
1671   if ($empty_entry) {
1672     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1673   }
1674
1675   foreach my $unit (sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } keys(%{$units}))) {
1676     push(@{$select}, { "name" => $unit,
1677                        "base_unit" => $units->{$unit}->{"base_unit"},
1678                        "factor" => $units->{$unit}->{"factor"},
1679                        "selected" => ($unit eq $selected) ? "selected" : "" });
1680   }
1681
1682   $main::lxdebug->leave_sub();
1683
1684   return $select;
1685 }
1686
1687 sub unit_select_html {
1688   $main::lxdebug->enter_sub();
1689
1690   my ($self, $units, $name, $selected, $convertible_into) = @_;
1691
1692   my $select = "<select name=${name}>";
1693
1694   foreach my $unit (sort({ $a->{"sortkey"} <=> $b->{"sortkey"} } keys(%{$units}))) {
1695     if (!$convertible_into ||
1696         ($units->{$convertible_into} &&
1697          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1698       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1699     }
1700   }
1701   $select .= "</select>";
1702
1703   $main::lxdebug->leave_sub();
1704
1705   return $select;
1706 }
1707
1708 sub add_unit {
1709   $main::lxdebug->enter_sub();
1710
1711   my ($self, $myconfig, $form, $name, $base_unit, $factor, $type, $languages) = @_;
1712
1713   my $dbh = $form->dbconnect_noauto($myconfig);
1714
1715   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1716   my ($sortkey) = selectrow_query($form, $dbh, $query);
1717
1718   $query = "INSERT INTO units (name, base_unit, factor, type, sortkey) " .
1719     "VALUES (?, ?, ?, ?, ?)";
1720   do_query($form, $dbh, $query, $name, $base_unit, $factor, $type, $sortkey);
1721
1722   if ($languages) {
1723     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1724     my $sth = $dbh->prepare($query);
1725     foreach my $lang (@{$languages}) {
1726       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1727       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1728     }
1729     $sth->finish();
1730   }
1731
1732   $dbh->commit();
1733   $dbh->disconnect();
1734
1735   $main::lxdebug->leave_sub();
1736 }
1737
1738 sub save_units {
1739   $main::lxdebug->enter_sub();
1740
1741   my ($self, $myconfig, $form, $type, $units, $delete_units) = @_;
1742
1743   my $dbh = $form->dbconnect_noauto($myconfig);
1744
1745   my ($base_unit, $unit, $sth, $query);
1746
1747   $query = "DELETE FROM units_language";
1748   $dbh->do($query) || $form->dberror($query);
1749
1750   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1751     $query = "DELETE FROM units WHERE name IN (";
1752     map({ $query .= "?," } @{$delete_units});
1753     substr($query, -1, 1) = ")";
1754     $dbh->do($query, undef, @{$delete_units}) ||
1755       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1756   }
1757
1758   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1759   $sth = $dbh->prepare($query);
1760
1761   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1762   my $sth_lang = $dbh->prepare($query_lang);
1763
1764   foreach $unit (values(%{$units})) {
1765     $unit->{"depth"} = 0;
1766     my $base_unit = $unit;
1767     while ($base_unit->{"base_unit"}) {
1768       $unit->{"depth"}++;
1769       $base_unit = $units->{$base_unit->{"base_unit"}};
1770     }
1771   }
1772
1773   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1774     if ($unit->{"LANGUAGES"}) {
1775       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1776         next unless ($lang->{"id"} && $lang->{"localized"});
1777         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1778         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1779       }
1780     }
1781
1782     next if ($unit->{"unchanged_unit"});
1783
1784     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1785     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1786   }
1787
1788   $sth->finish();
1789   $sth_lang->finish();
1790   $dbh->commit();
1791   $dbh->disconnect();
1792
1793   $main::lxdebug->leave_sub();
1794 }
1795
1796 sub swap_units {
1797   $main::lxdebug->enter_sub();
1798
1799   my ($self, $myconfig, $form, $dir, $name_1, $unit_type) = @_;
1800
1801   my $dbh = $form->dbconnect_noauto($myconfig);
1802
1803   my $query;
1804
1805   $query = qq|SELECT sortkey FROM units WHERE name = ?|;
1806   my ($sortkey_1) = selectrow_query($form, $dbh, $query, $name_1);
1807
1808   $query =
1809     qq|SELECT sortkey FROM units | .
1810     qq|WHERE sortkey | . ($dir eq "down" ? ">" : "<") . qq| ? AND type = ? | .
1811     qq|ORDER BY sortkey | . ($dir eq "down" ? "ASC" : "DESC") . qq| LIMIT 1|;
1812   my ($sortkey_2) = selectrow_query($form, $dbh, $query, $sortkey_1, $unit_type);
1813
1814   if (defined($sortkey_1)) {
1815     $query = qq|SELECT name FROM units WHERE sortkey = ${sortkey_2}|;
1816     my ($name_2) = selectrow_query($form, $dbh, $query);
1817
1818     if (defined($name_2)) {
1819       $query = qq|UPDATE units SET sortkey = ? WHERE name = ?|;
1820       my $sth = $dbh->prepare($query);
1821
1822       do_statement($form, $sth, $query, $sortkey_1, $name_2);
1823       do_statement($form, $sth, $query, $sortkey_2, $name_1);
1824     }
1825   }
1826
1827   $dbh->commit();
1828   $dbh->disconnect();
1829
1830   $main::lxdebug->leave_sub();
1831 }
1832
1833 1;