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