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