fec1b038c66ee3fd3febd9d32e78a58eb09e1ccd
[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 sub load_template {
1224   $main::lxdebug->enter_sub();
1225
1226   my ($self, $form) = @_;
1227
1228   open(TEMPLATE, "$form->{file}") or $form->error("$form->{file} : $!");
1229
1230   while (<TEMPLATE>) {
1231     $form->{body} .= $_;
1232   }
1233
1234   close(TEMPLATE);
1235
1236   $main::lxdebug->leave_sub();
1237 }
1238
1239 sub save_template {
1240   $main::lxdebug->enter_sub();
1241
1242   my ($self, $form) = @_;
1243
1244   open(TEMPLATE, ">$form->{file}") or $form->error("$form->{file} : $!");
1245
1246   # strip
1247   $form->{body} =~ s/\r\n/\n/g;
1248   print TEMPLATE $form->{body};
1249
1250   close(TEMPLATE);
1251
1252   $main::lxdebug->leave_sub();
1253 }
1254
1255 sub save_preferences {
1256   $main::lxdebug->enter_sub();
1257
1258   my ($self, $myconfig, $form, $memberfile, $userspath, $webdav) = @_;
1259
1260   map { ($form->{$_}) = split(/--/, $form->{$_}) }
1261     qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno);
1262
1263   my @a;
1264   $form->{curr} =~ s/ //g;
1265   map { push(@a, uc pack "A3", $_) if $_ } split(/:/, $form->{curr});
1266   $form->{curr} = join ':', @a;
1267
1268   # connect to database
1269   my $dbh = $form->dbconnect_noauto($myconfig);
1270
1271   # these defaults are database wide
1272   # user specific variables are in myconfig
1273   # save defaults
1274   my $query =
1275     qq|UPDATE defaults SET | .
1276     qq|inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1277     qq|income_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1278     qq|expense_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1279     qq|fxgain_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1280     qq|fxloss_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?), | .
1281     qq|invnumber = ?, | .
1282     qq|cnnumber  = ?, | .
1283     qq|sonumber = ?, | .
1284     qq|ponumber = ?, | .
1285     qq|sqnumber = ?, | .
1286     qq|rfqnumber = ?, | .
1287     qq|customernumber = ?, | .
1288     qq|vendornumber = ?, | .
1289     qq|articlenumber = ?, | .
1290     qq|servicenumber = ?, | .
1291     qq|yearend = ?, | .
1292     qq|curr = ?, | .
1293     qq|businessnumber = ?|;
1294   my @values = ($form->{inventory_accno}, $form->{income_accno},
1295                 $form->{expense_accno},
1296                 $form->{fxgain_accno}, $form->{fxloss_accno},
1297                 $form->{invnumber}, $form->{cnnumber},
1298                 $form->{sonumber}, $form->{ponumber},
1299                 $form->{sqnumber}, $form->{rfqnumber},
1300                 $form->{customernumber}, $form->{vendornumber},
1301                 $form->{articlenumber}, $form->{servicenumber},
1302                 $form->{yearend}, $form->{curr},
1303                 $form->{businessnumber});
1304   do_query($form, $dbh, $query, @values);
1305
1306   # update name
1307   $query = qq|UPDATE employee
1308               SET name = ?
1309               WHERE login = ?|;
1310   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1311
1312   my $rc = $dbh->commit;
1313   $dbh->disconnect;
1314
1315   # save first currency in myconfig
1316   $form->{currency} = substr($form->{curr}, 0, 3);
1317
1318   my $myconfig = new User "$memberfile", "$form->{login}";
1319
1320   foreach my $item (keys %$form) {
1321     $myconfig->{$item} = $form->{$item};
1322   }
1323
1324   $myconfig->save_member($memberfile, $userspath);
1325
1326   if ($webdav) {
1327     @webdavdirs =
1328       qw(angebote bestellungen rechnungen anfragen lieferantenbestellungen einkaufsrechnungen);
1329     foreach $directory (@webdavdirs) {
1330       $file = "webdav/" . $directory . "/webdav-user";
1331       if ($myconfig->{$directory}) {
1332         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1333         while (<HTACCESS>) {
1334           ($login, $password) = split(/:/, $_);
1335           if ($login ne $form->{login}) {
1336             $newfile .= $_;
1337           }
1338         }
1339         close(HTACCESS);
1340         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1341         $newfile .= $myconfig->{login} . ":" . $myconfig->{password} . "\n";
1342         print(HTACCESS $newfile);
1343         close(HTACCESS);
1344       } else {
1345         $form->{$directory} = 0;
1346         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1347         while (<HTACCESS>) {
1348           ($login, $password) = split(/:/, $_);
1349           if ($login ne $form->{login}) {
1350             $newfile .= $_;
1351           }
1352         }
1353         close(HTACCESS);
1354         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1355         print(HTACCESS $newfile);
1356         close(HTACCESS);
1357       }
1358     }
1359   }
1360
1361   $main::lxdebug->leave_sub();
1362
1363   return $rc;
1364 }
1365
1366 sub defaultaccounts {
1367   $main::lxdebug->enter_sub();
1368
1369   my ($self, $myconfig, $form) = @_;
1370
1371   # connect to database
1372   my $dbh = $form->dbconnect($myconfig);
1373
1374   # get defaults from defaults table
1375   my $query = qq|SELECT * FROM defaults|;
1376   my $sth   = $dbh->prepare($query);
1377   $sth->execute || $form->dberror($query);
1378
1379   $form->{defaults}             = $sth->fetchrow_hashref(NAME_lc);
1380   $form->{defaults}{IC}         = $form->{defaults}{inventory_accno_id};
1381   $form->{defaults}{IC_income}  = $form->{defaults}{income_accno_id};
1382   $form->{defaults}{IC_expense} = $form->{defaults}{expense_accno_id};
1383   $form->{defaults}{FX_gain}    = $form->{defaults}{fxgain_accno_id};
1384   $form->{defaults}{FX_loss}    = $form->{defaults}{fxloss_accno_id};
1385
1386   $sth->finish;
1387
1388   $query = qq|SELECT c.id, c.accno, c.description, c.link
1389               FROM chart c
1390               WHERE c.link LIKE '%IC%'
1391               ORDER BY c.accno|;
1392   $sth = $dbh->prepare($query);
1393   $sth->execute || $self->dberror($query);
1394
1395   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1396     foreach my $key (split(/:/, $ref->{link})) {
1397       if ($key =~ /IC/) {
1398         $nkey = $key;
1399         if ($key =~ /cogs/) {
1400           $nkey = "IC_expense";
1401         }
1402         if ($key =~ /sale/) {
1403           $nkey = "IC_income";
1404         }
1405         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1406                                              id          => $ref->{id},
1407                                              description => $ref->{description}
1408         );
1409       }
1410     }
1411   }
1412   $sth->finish;
1413
1414   $query = qq|SELECT c.id, c.accno, c.description
1415               FROM chart c
1416               WHERE c.category = 'I'
1417               AND c.charttype = 'A'
1418               ORDER BY c.accno|;
1419   $sth = $dbh->prepare($query);
1420   $sth->execute || $self->dberror($query);
1421
1422   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1423     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1424                                              id          => $ref->{id},
1425                                              description => $ref->{description}
1426     );
1427   }
1428   $sth->finish;
1429
1430   $query = qq|SELECT c.id, c.accno, c.description
1431               FROM chart c
1432               WHERE c.category = 'E'
1433               AND c.charttype = 'A'
1434               ORDER BY c.accno|;
1435   $sth = $dbh->prepare($query);
1436   $sth->execute || $self->dberror($query);
1437
1438   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1439     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1440                                              id          => $ref->{id},
1441                                              description => $ref->{description}
1442     );
1443   }
1444   $sth->finish;
1445
1446   # now get the tax rates and numbers
1447   $query = qq|SELECT c.id, c.accno, c.description,
1448               t.rate * 100 AS rate, t.taxnumber
1449               FROM chart c, tax t
1450               WHERE c.id = t.chart_id|;
1451
1452   $sth = $dbh->prepare($query);
1453   $sth->execute || $form->dberror($query);
1454
1455   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1456     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1457     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1458     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1459       if $ref->{taxnumber};
1460     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1461   }
1462
1463   $sth->finish;
1464   $dbh->disconnect;
1465
1466   $main::lxdebug->leave_sub();
1467 }
1468
1469 sub closedto {
1470   $main::lxdebug->enter_sub();
1471
1472   my ($self, $myconfig, $form) = @_;
1473
1474   my $dbh = $form->dbconnect($myconfig);
1475
1476   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1477   my $sth   = $dbh->prepare($query);
1478   $sth->execute || $form->dberror($query);
1479
1480   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1481
1482   $sth->finish;
1483
1484   $dbh->disconnect;
1485
1486   $main::lxdebug->leave_sub();
1487 }
1488
1489 sub closebooks {
1490   $main::lxdebug->enter_sub();
1491
1492   my ($self, $myconfig, $form) = @_;
1493
1494   my $dbh = $form->dbconnect($myconfig);
1495
1496   my ($query, @values);
1497
1498   if ($form->{revtrans}) {
1499     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1500
1501   } elsif ($form->{closedto}) {
1502     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1503     @values = (conv_date($form->{closedto}));
1504
1505   } else {
1506     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1507   }
1508
1509   # set close in defaults
1510   do_query($form, $dbh, $query, @values);
1511
1512   $dbh->disconnect;
1513
1514   $main::lxdebug->leave_sub();
1515 }
1516
1517 sub get_base_unit {
1518   my ($self, $units, $unit_name, $factor) = @_;
1519
1520   $factor = 1 unless ($factor);
1521
1522   my $unit = $units->{$unit_name};
1523
1524   if (!defined($unit) || !$unit->{"base_unit"} ||
1525       ($unit_name eq $unit->{"base_unit"})) {
1526     return ($unit_name, $factor);
1527   }
1528
1529   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1530 }
1531
1532 sub retrieve_units {
1533   $main::lxdebug->enter_sub();
1534
1535   my ($self, $myconfig, $form, $type, $prefix) = @_;
1536
1537   my $dbh = $form->dbconnect($myconfig);
1538
1539   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1540   my @values;
1541   if ($type) {
1542     $query .= " WHERE (type = ?)";
1543     @values = ($type);
1544   }
1545
1546   my $sth = $dbh->prepare($query);
1547   $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1548
1549   my $units = {};
1550   while (my $ref = $sth->fetchrow_hashref()) {
1551     $units->{$ref->{"name"}} = $ref;
1552   }
1553   $sth->finish();
1554
1555   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1556   $sth = $dbh->prepare($query_lang);
1557   $sth->execute() || $form->dberror($query_lang);
1558   my @languages;
1559   while ($ref = $sth->fetchrow_hashref()) {
1560     push(@languages, $ref);
1561   }
1562   $sth->finish();
1563
1564   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1565     "FROM units_language ul " .
1566     "LEFT JOIN language l ON ul.language_id = l.id " .
1567     "WHERE ul.unit = ?";
1568   $sth = $dbh->prepare($query_lang);
1569
1570   foreach my $unit (values(%{$units})) {
1571     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1572
1573     $unit->{"LANGUAGES"} = {};
1574     foreach my $lang (@languages) {
1575       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1576     }
1577
1578     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1579     while ($ref = $sth->fetchrow_hashref()) {
1580       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1581     }
1582   }
1583   $sth->finish();
1584
1585   $dbh->disconnect();
1586
1587   $main::lxdebug->leave_sub();
1588
1589   return $units;
1590 }
1591
1592 sub translate_units {
1593   $main::lxdebug->enter_sub();
1594
1595   my ($self, $form, $template_code, $unit, $amount) = @_;
1596
1597   my $units = $self->retrieve_units(\%main::myconfig, $form);
1598
1599   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1600   my $new_unit = $unit;
1601   if ($h) {
1602     if (($amount != 1) && $h->{"localized_plural"}) {
1603       $new_unit = $h->{"localized_plural"};
1604     } elsif ($h->{"localized"}) {
1605       $new_unit = $h->{"localized"};
1606     }
1607   }
1608
1609   $main::lxdebug->leave_sub();
1610
1611   return $new_unit;
1612 }
1613
1614 sub units_in_use {
1615   $main::lxdebug->enter_sub();
1616
1617   my ($self, $myconfig, $form, $units) = @_;
1618
1619   my $dbh = $form->dbconnect($myconfig);
1620
1621   map({ $_->{"in_use"} = 0; } values(%{$units}));
1622
1623   foreach my $unit (values(%{$units})) {
1624     my $base_unit = $unit->{"original_base_unit"};
1625     while ($base_unit) {
1626       $units->{$base_unit}->{"in_use"} = 1;
1627       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1628       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1629       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1630     }
1631   }
1632
1633   foreach my $unit (values(%{$units})) {
1634     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1635
1636     foreach my $table (qw(parts invoice orderitems)) {
1637       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1638
1639       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1640         $query .= "= " . $dbh->quote($unit->{"name"});
1641       } else {
1642         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1643           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1644       }
1645
1646       my ($count) = $dbh->selectrow_array($query);
1647       $form->dberror($query) if ($dbh->err);
1648
1649       if ($count) {
1650         $unit->{"in_use"} = 1;
1651         last;
1652       }
1653     }
1654   }
1655
1656   $dbh->disconnect();
1657
1658   $main::lxdebug->leave_sub();
1659 }
1660
1661 sub unit_select_data {
1662   $main::lxdebug->enter_sub();
1663
1664   my ($self, $units, $selected, $empty_entry) = @_;
1665
1666   my $select = [];
1667
1668   if ($empty_entry) {
1669     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1670   }
1671
1672   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1673     push(@{$select}, { "name" => $unit,
1674                        "base_unit" => $units->{$unit}->{"base_unit"},
1675                        "factor" => $units->{$unit}->{"factor"},
1676                        "selected" => ($unit eq $selected) ? "selected" : "" });
1677   }
1678
1679   $main::lxdebug->leave_sub();
1680
1681   return $select;
1682 }
1683
1684 sub unit_select_html {
1685   $main::lxdebug->enter_sub();
1686
1687   my ($self, $units, $name, $selected, $convertible_into) = @_;
1688
1689   my $select = "<select name=${name}>";
1690
1691   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1692     if (!$convertible_into ||
1693         ($units->{$convertible_into} &&
1694          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1695       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1696     }
1697   }
1698   $select .= "</select>";
1699
1700   $main::lxdebug->leave_sub();
1701
1702   return $select;
1703 }
1704
1705 sub add_unit {
1706   $main::lxdebug->enter_sub();
1707
1708   my ($self, $myconfig, $form, $name, $base_unit, $factor, $type, $languages) = @_;
1709
1710   my $dbh = $form->dbconnect_noauto($myconfig);
1711
1712   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1713   my ($sortkey) = selectrow_query($form, $dbh, $query);
1714
1715   $query = "INSERT INTO units (name, base_unit, factor, type, sortkey) " .
1716     "VALUES (?, ?, ?, ?, ?)";
1717   do_query($form, $dbh, $query, $name, $base_unit, $factor, $type, $sortkey);
1718
1719   if ($languages) {
1720     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1721     my $sth = $dbh->prepare($query);
1722     foreach my $lang (@{$languages}) {
1723       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1724       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1725     }
1726     $sth->finish();
1727   }
1728
1729   $dbh->commit();
1730   $dbh->disconnect();
1731
1732   $main::lxdebug->leave_sub();
1733 }
1734
1735 sub save_units {
1736   $main::lxdebug->enter_sub();
1737
1738   my ($self, $myconfig, $form, $type, $units, $delete_units) = @_;
1739
1740   my $dbh = $form->dbconnect_noauto($myconfig);
1741
1742   my ($base_unit, $unit, $sth, $query);
1743
1744   $query = "DELETE FROM units_language";
1745   $dbh->do($query) || $form->dberror($query);
1746
1747   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1748     $query = "DELETE FROM units WHERE name IN (";
1749     map({ $query .= "?," } @{$delete_units});
1750     substr($query, -1, 1) = ")";
1751     $dbh->do($query, undef, @{$delete_units}) ||
1752       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1753   }
1754
1755   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1756   $sth = $dbh->prepare($query);
1757
1758   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1759   my $sth_lang = $dbh->prepare($query_lang);
1760
1761   foreach $unit (values(%{$units})) {
1762     $unit->{"depth"} = 0;
1763     my $base_unit = $unit;
1764     while ($base_unit->{"base_unit"}) {
1765       $unit->{"depth"}++;
1766       $base_unit = $units->{$base_unit->{"base_unit"}};
1767     }
1768   }
1769
1770   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1771     if ($unit->{"LANGUAGES"}) {
1772       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1773         next unless ($lang->{"id"} && $lang->{"localized"});
1774         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1775         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1776       }
1777     }
1778
1779     next if ($unit->{"unchanged_unit"});
1780
1781     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1782     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1783   }
1784
1785   $sth->finish();
1786   $sth_lang->finish();
1787   $dbh->commit();
1788   $dbh->disconnect();
1789
1790   $main::lxdebug->leave_sub();
1791 }
1792
1793 sub swap_units {
1794   $main::lxdebug->enter_sub();
1795
1796   my ($self, $myconfig, $form, $dir, $name_1, $unit_type) = @_;
1797
1798   my $dbh = $form->dbconnect_noauto($myconfig);
1799
1800   my $query;
1801
1802   $query = qq|SELECT sortkey FROM units WHERE name = ?|;
1803   my ($sortkey_1) = selectrow_query($form, $dbh, $query, $name_1);
1804
1805   $query =
1806     qq|SELECT sortkey FROM units | .
1807     qq|WHERE sortkey | . ($dir eq "down" ? ">" : "<") . qq| ? AND type = ? | .
1808     qq|ORDER BY sortkey | . ($dir eq "down" ? "ASC" : "DESC") . qq| LIMIT 1|;
1809   my ($sortkey_2) = selectrow_query($form, $dbh, $query, $sortkey_1, $unit_type);
1810
1811   if (defined($sortkey_1)) {
1812     $query = qq|SELECT name FROM units WHERE sortkey = ${sortkey_2}|;
1813     my ($name_2) = selectrow_query($form, $dbh, $query);
1814
1815     if (defined($name_2)) {
1816       $query = qq|UPDATE units SET sortkey = ? WHERE name = ?|;
1817       my $sth = $dbh->prepare($query);
1818
1819       do_statement($form, $sth, $query, $sortkey_1, $name_2);
1820       do_statement($form, $sth, $query, $sortkey_2, $name_1);
1821     }
1822   }
1823
1824   $dbh->commit();
1825   $dbh->disconnect();
1826
1827   $main::lxdebug->leave_sub();
1828 }
1829
1830 1;