Alle 2-arg open in 3-arg open verwandelt.
[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     $filename =~ s|.*/||;
969     $display_filename = $filename;
970     $filename = "$myconfig->{templates}/$filename";
971   }
972
973   $main::lxdebug->leave_sub();
974
975   return ($filename, $display_filename);
976 }
977
978
979 sub load_template {
980   $main::lxdebug->enter_sub();
981
982   my ($self, $filename) = @_;
983
984   my ($content, $lines) = ("", 0);
985
986   local *TEMPLATE;
987
988   if (open(TEMPLATE, $filename)) {
989     while (<TEMPLATE>) {
990       $content .= $_;
991       $lines++;
992     }
993     close(TEMPLATE);
994   }
995
996   $content = Encode::decode('utf-8-strict', $content) if $::locale->is_utf8;
997
998   $main::lxdebug->leave_sub();
999
1000   return ($content, $lines);
1001 }
1002
1003 sub save_template {
1004   $main::lxdebug->enter_sub();
1005
1006   my ($self, $filename, $content) = @_;
1007
1008   local *TEMPLATE;
1009
1010   my $error = "";
1011
1012   if (open(TEMPLATE, ">", $filename)) {
1013     $content = Encode::encode('utf-8-strict', $content) if $::locale->is_utf8;
1014     $content =~ s/\r\n/\n/g;
1015     print(TEMPLATE $content);
1016     close(TEMPLATE);
1017   } else {
1018     $error = $!;
1019   }
1020
1021   $main::lxdebug->leave_sub();
1022
1023   return $error;
1024 }
1025
1026 sub save_defaults {
1027   $main::lxdebug->enter_sub();
1028
1029   my $self     = shift;
1030   my %params   = @_;
1031
1032   my $myconfig = \%main::myconfig;
1033   my $form     = $main::form;
1034
1035   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1036
1037   my %accnos;
1038   map { ($accnos{$_}) = split(m/--/, $form->{$_}) } qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno ar_paid_accno);
1039
1040   $form->{curr}  =~ s/ //g;
1041   my @currencies =  grep { $_ ne '' } split m/:/, $form->{curr};
1042   my $currency   =  join ':', @currencies;
1043
1044   # these defaults are database wide
1045
1046   my $query =
1047     qq|UPDATE defaults SET
1048         inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?),
1049         income_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1050         expense_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1051         fxgain_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1052         fxloss_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1053         ar_paid_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1054         invnumber          = ?,
1055         cnnumber           = ?,
1056         sonumber           = ?,
1057         ponumber           = ?,
1058         sqnumber           = ?,
1059         rfqnumber          = ?,
1060         customernumber     = ?,
1061         vendornumber       = ?,
1062         articlenumber      = ?,
1063         servicenumber      = ?,
1064         sdonumber          = ?,
1065         pdonumber          = ?,
1066         curr               = ?,
1067         businessnumber     = ?,
1068         weightunit         = ?,
1069         language_id        = ?|;
1070   my @values = ($accnos{inventory_accno}, $accnos{income_accno}, $accnos{expense_accno},
1071                 $accnos{fxgain_accno},    $accnos{fxloss_accno}, $accnos{ar_paid_accno},
1072                 $form->{invnumber},       $form->{cnnumber},
1073                 $form->{sonumber},        $form->{ponumber},
1074                 $form->{sqnumber},        $form->{rfqnumber},
1075                 $form->{customernumber},  $form->{vendornumber},
1076                 $form->{articlenumber},   $form->{servicenumber},
1077                 $form->{sdonumber},       $form->{pdonumber},
1078                 $currency,
1079                 $form->{businessnumber},  $form->{weightunit},
1080                 conv_i($form->{language_id}));
1081   do_query($form, $dbh, $query, @values);
1082
1083   $dbh->commit();
1084
1085   $main::lxdebug->leave_sub();
1086 }
1087
1088
1089 sub save_preferences {
1090   $main::lxdebug->enter_sub();
1091
1092   my ($self, $myconfig, $form) = @_;
1093
1094   my $dbh = $form->get_standard_dbh($myconfig);
1095
1096   my ($currency, $businessnumber) = selectrow_query($form, $dbh, qq|SELECT curr, businessnumber FROM defaults|);
1097
1098   # update name
1099   my $query = qq|UPDATE employee SET name = ? WHERE login = ?|;
1100   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1101
1102   my $rc = $dbh->commit();
1103
1104   # save first currency in myconfig
1105   $currency               =~ s/:.*//;
1106   $form->{currency}       =  $currency;
1107
1108   $form->{businessnumber} =  $businessnumber;
1109
1110   $myconfig = new User($form->{login});
1111
1112   foreach my $item (keys %$form) {
1113     $myconfig->{$item} = $form->{$item};
1114   }
1115
1116   $myconfig->save_member;
1117
1118   my $auth = $main::auth;
1119
1120   $main::lxdebug->leave_sub();
1121
1122   return $rc;
1123 }
1124
1125 sub get_defaults {
1126   $main::lxdebug->enter_sub();
1127
1128   my $self     = shift;
1129   my %params   = @_;
1130
1131   my $myconfig = \%main::myconfig;
1132   my $form     = $main::form;
1133
1134   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1135
1136   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
1137
1138   $defaults->{weightunit} ||= 'kg';
1139
1140   $main::lxdebug->leave_sub();
1141
1142   return $defaults;
1143 }
1144
1145 sub defaultaccounts {
1146   $main::lxdebug->enter_sub();
1147
1148   my ($self, $myconfig, $form) = @_;
1149
1150   # connect to database
1151   my $dbh = $form->dbconnect($myconfig);
1152
1153   # get defaults from defaults table
1154   my $query = qq|SELECT * FROM defaults|;
1155   my $sth   = $dbh->prepare($query);
1156   $sth->execute || $form->dberror($query);
1157
1158   $form->{defaults}               = $sth->fetchrow_hashref("NAME_lc");
1159   $form->{defaults}{IC}           = $form->{defaults}{inventory_accno_id};
1160   $form->{defaults}{IC_income}    = $form->{defaults}{income_accno_id};
1161   $form->{defaults}{IC_expense}   = $form->{defaults}{expense_accno_id};
1162   $form->{defaults}{FX_gain}      = $form->{defaults}{fxgain_accno_id};
1163   $form->{defaults}{FX_loss}      = $form->{defaults}{fxloss_accno_id};
1164   $form->{defaults}{AR_paid}      = $form->{defaults}{ar_paid_accno_id};
1165
1166   $form->{defaults}{weightunit} ||= 'kg';
1167
1168   $sth->finish;
1169
1170   $query = qq|SELECT c.id, c.accno, c.description, c.link
1171               FROM chart c
1172               WHERE c.link LIKE '%IC%'
1173               ORDER BY c.accno|;
1174   $sth = $dbh->prepare($query);
1175   $sth->execute || $self->dberror($query);
1176
1177   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1178     foreach my $key (split(/:/, $ref->{link})) {
1179       if ($key =~ /IC/) {
1180         my $nkey = $key;
1181         if ($key =~ /cogs/) {
1182           $nkey = "IC_expense";
1183         }
1184         if ($key =~ /sale/) {
1185           $nkey = "IC_income";
1186         }
1187         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1188                                              id          => $ref->{id},
1189                                              description => $ref->{description}
1190         );
1191       }
1192     }
1193   }
1194   $sth->finish;
1195
1196   $query = qq|SELECT c.id, c.accno, c.description
1197               FROM chart c
1198               WHERE c.category = 'I'
1199               AND c.charttype = 'A'
1200               ORDER BY c.accno|;
1201   $sth = $dbh->prepare($query);
1202   $sth->execute || $self->dberror($query);
1203
1204   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1205     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1206                                              id          => $ref->{id},
1207                                              description => $ref->{description}
1208     );
1209   }
1210   $sth->finish;
1211
1212   $query = qq|SELECT c.id, c.accno, c.description
1213               FROM chart c
1214               WHERE c.category = 'E'
1215               AND c.charttype = 'A'
1216               ORDER BY c.accno|;
1217   $sth = $dbh->prepare($query);
1218   $sth->execute || $self->dberror($query);
1219
1220   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1221     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1222                                              id          => $ref->{id},
1223                                              description => $ref->{description}
1224     );
1225   }
1226   $sth->finish;
1227
1228   # now get the tax rates and numbers
1229   $query = qq|SELECT c.id, c.accno, c.description,
1230               t.rate * 100 AS rate, t.taxnumber
1231               FROM chart c, tax t
1232               WHERE c.id = t.chart_id|;
1233
1234   $sth = $dbh->prepare($query);
1235   $sth->execute || $form->dberror($query);
1236
1237   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1238     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1239     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1240     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1241       if $ref->{taxnumber};
1242     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1243   }
1244   # Abfrage für Standard Umlaufvermögenskonto
1245   $query =
1246     qq|SELECT id, accno, description, link | .
1247     qq|FROM chart | .
1248     qq|WHERE link LIKE ? |.
1249     qq|ORDER BY accno|;
1250   $sth = prepare_execute_query($form, $dbh, $query, '%AR%');
1251   $sth->execute || $form->dberror($query);#
1252   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1253     foreach my $item (split(/:/, $ref->{link})) {
1254       if ($item eq "AR_paid") {
1255         %{ $form->{IC}{AR_paid}{ $ref->{accno} } } = (
1256                                              id          => $ref->{id},
1257                                              description => $ref->{description}
1258           );
1259       }
1260     }
1261   }
1262
1263   $sth->finish;
1264   $dbh->disconnect;
1265
1266   $main::lxdebug->leave_sub();
1267 }
1268
1269 sub closedto {
1270   $main::lxdebug->enter_sub();
1271
1272   my ($self, $myconfig, $form) = @_;
1273
1274   my $dbh = $form->dbconnect($myconfig);
1275
1276   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1277   my $sth   = $dbh->prepare($query);
1278   $sth->execute || $form->dberror($query);
1279
1280   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1281
1282   $sth->finish;
1283
1284   $dbh->disconnect;
1285
1286   $main::lxdebug->leave_sub();
1287 }
1288
1289 sub closebooks {
1290   $main::lxdebug->enter_sub();
1291
1292   my ($self, $myconfig, $form) = @_;
1293
1294   my $dbh = $form->dbconnect($myconfig);
1295
1296   my ($query, @values);
1297
1298   if ($form->{revtrans}) {
1299     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1300
1301   } elsif ($form->{closedto}) {
1302     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1303     @values = (conv_date($form->{closedto}));
1304
1305   } else {
1306     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1307   }
1308
1309   # set close in defaults
1310   do_query($form, $dbh, $query, @values);
1311
1312   $dbh->disconnect;
1313
1314   $main::lxdebug->leave_sub();
1315 }
1316
1317 sub get_base_unit {
1318   my ($self, $units, $unit_name, $factor) = @_;
1319
1320   $factor = 1 unless ($factor);
1321
1322   my $unit = $units->{$unit_name};
1323
1324   if (!defined($unit) || !$unit->{"base_unit"} ||
1325       ($unit_name eq $unit->{"base_unit"})) {
1326     return ($unit_name, $factor);
1327   }
1328
1329   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1330 }
1331
1332 sub retrieve_units {
1333   $main::lxdebug->enter_sub();
1334
1335   my ($self, $myconfig, $form, $prefix) = @_;
1336
1337   my $dbh = $form->get_standard_dbh;
1338
1339   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1340
1341   my $sth = prepare_execute_query($form, $dbh, $query);
1342
1343   my $units = {};
1344   while (my $ref = $sth->fetchrow_hashref()) {
1345     $units->{$ref->{"name"}} = $ref;
1346   }
1347   $sth->finish();
1348
1349   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1350   $sth = $dbh->prepare($query_lang);
1351   $sth->execute() || $form->dberror($query_lang);
1352   my @languages;
1353   while (my $ref = $sth->fetchrow_hashref()) {
1354     push(@languages, $ref);
1355   }
1356   $sth->finish();
1357
1358   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1359     "FROM units_language ul " .
1360     "LEFT JOIN language l ON ul.language_id = l.id " .
1361     "WHERE ul.unit = ?";
1362   $sth = $dbh->prepare($query_lang);
1363
1364   foreach my $unit (values(%{$units})) {
1365     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1366
1367     $unit->{"LANGUAGES"} = {};
1368     foreach my $lang (@languages) {
1369       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1370     }
1371
1372     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1373     while (my $ref = $sth->fetchrow_hashref()) {
1374       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1375     }
1376   }
1377   $sth->finish;
1378
1379   $main::lxdebug->leave_sub();
1380
1381   return $units;
1382 }
1383
1384 sub retrieve_all_units {
1385   $main::lxdebug->enter_sub();
1386
1387   my $self = shift;
1388
1389   if (!$main::all_units) {
1390     $main::all_units = $self->retrieve_units(\%main::myconfig, $main::form);
1391   }
1392
1393   $main::lxdebug->leave_sub();
1394
1395   return $main::all_units;
1396 }
1397
1398
1399 sub translate_units {
1400   $main::lxdebug->enter_sub();
1401
1402   my ($self, $form, $template_code, $unit, $amount) = @_;
1403
1404   my $units = $self->retrieve_units(\%main::myconfig, $form);
1405
1406   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1407   my $new_unit = $unit;
1408   if ($h) {
1409     if (($amount != 1) && $h->{"localized_plural"}) {
1410       $new_unit = $h->{"localized_plural"};
1411     } elsif ($h->{"localized"}) {
1412       $new_unit = $h->{"localized"};
1413     }
1414   }
1415
1416   $main::lxdebug->leave_sub();
1417
1418   return $new_unit;
1419 }
1420
1421 sub units_in_use {
1422   $main::lxdebug->enter_sub();
1423
1424   my ($self, $myconfig, $form, $units) = @_;
1425
1426   my $dbh = $form->dbconnect($myconfig);
1427
1428   map({ $_->{"in_use"} = 0; } values(%{$units}));
1429
1430   foreach my $unit (values(%{$units})) {
1431     my $base_unit = $unit->{"original_base_unit"};
1432     while ($base_unit) {
1433       $units->{$base_unit}->{"in_use"} = 1;
1434       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1435       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1436       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1437     }
1438   }
1439
1440   foreach my $unit (values(%{$units})) {
1441     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1442
1443     foreach my $table (qw(parts invoice orderitems)) {
1444       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1445
1446       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1447         $query .= "= " . $dbh->quote($unit->{"name"});
1448       } else {
1449         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1450           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1451       }
1452
1453       my ($count) = $dbh->selectrow_array($query);
1454       $form->dberror($query) if ($dbh->err);
1455
1456       if ($count) {
1457         $unit->{"in_use"} = 1;
1458         last;
1459       }
1460     }
1461   }
1462
1463   $dbh->disconnect();
1464
1465   $main::lxdebug->leave_sub();
1466 }
1467
1468 sub convertible_units {
1469   $main::lxdebug->enter_sub();
1470
1471   my $self        = shift;
1472   my $units       = shift;
1473   my $filter_unit = shift;
1474   my $not_smaller = shift;
1475
1476   my $conv_units = [];
1477
1478   $filter_unit = $units->{$filter_unit};
1479
1480   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1481     my $unit = $units->{$name};
1482
1483     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1484         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1485       push @{$conv_units}, $unit;
1486     }
1487   }
1488
1489   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1490
1491   $main::lxdebug->leave_sub();
1492
1493   return \@sorted;
1494 }
1495
1496 # if $a is translatable to $b, return the factor between them.
1497 # else return 1
1498 sub convert_unit {
1499   $main::lxdebug->enter_sub(2);
1500   my ($this, $a, $b, $all_units) = @_;
1501
1502   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1503   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1504   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1505   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1506 }
1507
1508 sub unit_select_data {
1509   $main::lxdebug->enter_sub();
1510
1511   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1512
1513   my $select = [];
1514
1515   if ($empty_entry) {
1516     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1517   }
1518
1519   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1520     if (!$convertible_into ||
1521         ($units->{$convertible_into} &&
1522          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1523       push @{$select}, { "name"      => $unit,
1524                          "base_unit" => $units->{$unit}->{"base_unit"},
1525                          "factor"    => $units->{$unit}->{"factor"},
1526                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1527     }
1528   }
1529
1530   $main::lxdebug->leave_sub();
1531
1532   return $select;
1533 }
1534
1535 sub unit_select_html {
1536   $main::lxdebug->enter_sub();
1537
1538   my ($self, $units, $name, $selected, $convertible_into) = @_;
1539
1540   my $select = "<select name=${name}>";
1541
1542   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1543     if (!$convertible_into ||
1544         ($units->{$convertible_into} &&
1545          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1546       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1547     }
1548   }
1549   $select .= "</select>";
1550
1551   $main::lxdebug->leave_sub();
1552
1553   return $select;
1554 }
1555
1556 sub sum_with_unit {
1557   $main::lxdebug->enter_sub();
1558
1559   my $self  = shift;
1560
1561   my $units = $self->retrieve_all_units();
1562
1563   my $sum   = 0;
1564   my $base_unit;
1565
1566   while (2 <= scalar(@_)) {
1567     my $qty  = shift(@_);
1568     my $unit = $units->{shift(@_)};
1569
1570     croak "No unit defined with name $unit" if (!defined $unit);
1571
1572     if (!$base_unit) {
1573       $base_unit = $unit->{base_unit};
1574     } elsif ($base_unit ne $unit->{base_unit}) {
1575       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1576     }
1577
1578     $sum += $qty * $unit->{factor};
1579   }
1580
1581   $main::lxdebug->leave_sub();
1582
1583   return wantarray ? ($sum, $base_unit) : $sum;
1584 }
1585
1586 sub add_unit {
1587   $main::lxdebug->enter_sub();
1588
1589   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1590
1591   my $dbh = $form->dbconnect_noauto($myconfig);
1592
1593   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1594   my ($sortkey) = selectrow_query($form, $dbh, $query);
1595
1596   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1597     "VALUES (?, ?, ?, ?)";
1598   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1599
1600   if ($languages) {
1601     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1602     my $sth = $dbh->prepare($query);
1603     foreach my $lang (@{$languages}) {
1604       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1605       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1606     }
1607     $sth->finish();
1608   }
1609
1610   $dbh->commit();
1611   $dbh->disconnect();
1612
1613   $main::lxdebug->leave_sub();
1614 }
1615
1616 sub save_units {
1617   $main::lxdebug->enter_sub();
1618
1619   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1620
1621   my $dbh = $form->dbconnect_noauto($myconfig);
1622
1623   my ($base_unit, $unit, $sth, $query);
1624
1625   $query = "DELETE FROM units_language";
1626   $dbh->do($query) || $form->dberror($query);
1627
1628   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1629     $query = "DELETE FROM units WHERE name IN (";
1630     map({ $query .= "?," } @{$delete_units});
1631     substr($query, -1, 1) = ")";
1632     $dbh->do($query, undef, @{$delete_units}) ||
1633       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1634   }
1635
1636   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1637   $sth = $dbh->prepare($query);
1638
1639   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1640   my $sth_lang = $dbh->prepare($query_lang);
1641
1642   foreach $unit (values(%{$units})) {
1643     $unit->{"depth"} = 0;
1644     my $base_unit = $unit;
1645     while ($base_unit->{"base_unit"}) {
1646       $unit->{"depth"}++;
1647       $base_unit = $units->{$base_unit->{"base_unit"}};
1648     }
1649   }
1650
1651   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1652     if ($unit->{"LANGUAGES"}) {
1653       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1654         next unless ($lang->{"id"} && $lang->{"localized"});
1655         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1656         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1657       }
1658     }
1659
1660     next if ($unit->{"unchanged_unit"});
1661
1662     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1663     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1664   }
1665
1666   $sth->finish();
1667   $sth_lang->finish();
1668   $dbh->commit();
1669   $dbh->disconnect();
1670
1671   $main::lxdebug->leave_sub();
1672 }
1673
1674 sub taxes {
1675   $main::lxdebug->enter_sub();
1676
1677   my ($self, $myconfig, $form) = @_;
1678
1679   # connect to database
1680   my $dbh = $form->dbconnect($myconfig);
1681
1682   my $query = qq|SELECT
1683                    t.id,
1684                    t.taxkey,
1685                    t.taxdescription,
1686                    round(t.rate * 100, 2) AS rate,
1687                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1688                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
1689                  FROM tax t
1690                  ORDER BY taxkey|;
1691
1692   my $sth = $dbh->prepare($query);
1693   $sth->execute || $form->dberror($query);
1694
1695   $form->{TAX} = [];
1696   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1697     push @{ $form->{TAX} }, $ref;
1698   }
1699
1700   $sth->finish;
1701   $dbh->disconnect;
1702
1703   $main::lxdebug->leave_sub();
1704 }
1705
1706 sub get_tax_accounts {
1707   $main::lxdebug->enter_sub();
1708
1709   my ($self, $myconfig, $form) = @_;
1710
1711   my $dbh = $form->dbconnect($myconfig);
1712
1713   # get Accounts from chart
1714   my $query = qq{ SELECT
1715                  id,
1716                  accno || ' - ' || description AS taxaccount
1717                FROM chart
1718                WHERE link LIKE '%_tax%'
1719                ORDER BY accno
1720              };
1721
1722   my $sth = $dbh->prepare($query);
1723   $sth->execute || $form->dberror($query);
1724
1725   $form->{ACCOUNTS} = [];
1726   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1727     push @{ $form->{ACCOUNTS} }, $ref;
1728   }
1729
1730   $sth->finish;
1731
1732   $dbh->disconnect;
1733
1734   $main::lxdebug->leave_sub();
1735 }
1736
1737 sub get_tax {
1738   $main::lxdebug->enter_sub();
1739
1740   my ($self, $myconfig, $form) = @_;
1741
1742   # connect to database
1743   my $dbh = $form->dbconnect($myconfig);
1744
1745   my $query = qq|SELECT
1746                    taxkey,
1747                    taxdescription,
1748                    round(rate * 100, 2) AS rate,
1749                    chart_id
1750                  FROM tax
1751                  WHERE id = ? |;
1752
1753   my $sth = $dbh->prepare($query);
1754   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1755
1756   my $ref = $sth->fetchrow_hashref("NAME_lc");
1757
1758   map { $form->{$_} = $ref->{$_} } keys %$ref;
1759
1760   $sth->finish;
1761
1762   # see if it is used by a taxkey
1763   $query = qq|SELECT count(*) FROM taxkeys
1764               WHERE tax_id = ? AND chart_id >0|;
1765
1766   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1767
1768   $form->{orphaned} = !$form->{orphaned};
1769   $sth->finish;
1770
1771   if (!$form->{orphaned} ) {
1772     $query = qq|SELECT DISTINCT c.id, c.accno
1773                 FROM taxkeys tk
1774                 JOIN   tax t ON (t.id = tk.tax_id)
1775                 JOIN chart c ON (c.id = tk.chart_id)
1776                 WHERE tk.tax_id = ?|;
1777
1778     $sth = $dbh->prepare($query);
1779     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1780
1781     $form->{TAXINUSE} = [];
1782     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1783       push @{ $form->{TAXINUSE} }, $ref;
1784     }
1785
1786     $sth->finish;
1787   }
1788
1789   $dbh->disconnect;
1790
1791   $main::lxdebug->leave_sub();
1792 }
1793
1794 sub save_tax {
1795   $main::lxdebug->enter_sub();
1796
1797   my ($self, $myconfig, $form) = @_;
1798   my $query;
1799
1800   # connect to database
1801   my $dbh = $form->get_standard_dbh($myconfig);
1802
1803   $form->{rate} = $form->{rate} / 100;
1804
1805   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
1806   if ($form->{id} ne "") {
1807     $query = qq|UPDATE tax SET
1808                   taxkey         = ?,
1809                   taxdescription = ?,
1810                   rate           = ?,
1811                   chart_id       = ?,
1812                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
1813                 WHERE id = ?|;
1814     push(@values, $form->{id});
1815
1816   } else {
1817     #ok
1818     $query = qq|INSERT INTO tax (
1819                   taxkey,
1820                   taxdescription,
1821                   rate,
1822                   chart_id,
1823                   taxnumber
1824                 )
1825                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
1826   }
1827   do_query($form, $dbh, $query, @values);
1828
1829   $dbh->commit();
1830
1831   $main::lxdebug->leave_sub();
1832 }
1833
1834 sub delete_tax {
1835   $main::lxdebug->enter_sub();
1836
1837   my ($self, $myconfig, $form) = @_;
1838   my $query;
1839
1840   # connect to database
1841   my $dbh = $form->get_standard_dbh($myconfig);
1842
1843   $query = qq|DELETE FROM tax
1844               WHERE id = ?|;
1845   do_query($form, $dbh, $query, $form->{id});
1846
1847   $dbh->commit();
1848
1849   $main::lxdebug->leave_sub();
1850 }
1851
1852 sub save_price_factor {
1853   $main::lxdebug->enter_sub();
1854
1855   my ($self, $myconfig, $form) = @_;
1856
1857   # connect to database
1858   my $dbh = $form->get_standard_dbh($myconfig);
1859
1860   my $query;
1861   my @values = ($form->{description}, conv_i($form->{factor}));
1862
1863   if ($form->{id}) {
1864     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1865     push @values, conv_i($form->{id});
1866
1867   } else {
1868     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1869   }
1870
1871   do_query($form, $dbh, $query, @values);
1872
1873   $dbh->commit();
1874
1875   $main::lxdebug->leave_sub();
1876 }
1877
1878 sub get_all_price_factors {
1879   $main::lxdebug->enter_sub();
1880
1881   my ($self, $myconfig, $form) = @_;
1882
1883   # connect to database
1884   my $dbh = $form->get_standard_dbh($myconfig);
1885
1886   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1887
1888   $main::lxdebug->leave_sub();
1889 }
1890
1891 sub get_price_factor {
1892   $main::lxdebug->enter_sub();
1893
1894   my ($self, $myconfig, $form) = @_;
1895
1896   # connect to database
1897   my $dbh = $form->get_standard_dbh($myconfig);
1898
1899   my $query = qq|SELECT description, factor,
1900                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
1901                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
1902                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1903                  FROM price_factors WHERE id = ?|;
1904
1905   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1906
1907   $main::lxdebug->leave_sub();
1908 }
1909
1910 sub delete_price_factor {
1911   $main::lxdebug->enter_sub();
1912
1913   my ($self, $myconfig, $form) = @_;
1914
1915   # connect to database
1916   my $dbh = $form->get_standard_dbh($myconfig);
1917
1918   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1919   $dbh->commit();
1920
1921   $main::lxdebug->leave_sub();
1922 }
1923
1924 sub save_warehouse {
1925   $main::lxdebug->enter_sub();
1926
1927   my ($self, $myconfig, $form) = @_;
1928
1929   # connect to database
1930   my $dbh = $form->get_standard_dbh($myconfig);
1931
1932   my ($query, @values, $sth);
1933
1934   if (!$form->{id}) {
1935     $query        = qq|SELECT nextval('id')|;
1936     ($form->{id}) = selectrow_query($form, $dbh, $query);
1937
1938     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1939     do_query($form, $dbh, $query, $form->{id});
1940   }
1941
1942   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1943            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1944
1945   if (0 < $form->{number_of_new_bins}) {
1946     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1947     $sth   = prepare_query($form, $dbh, $query);
1948
1949     foreach my $i (1..$form->{number_of_new_bins}) {
1950       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
1951     }
1952
1953     $sth->finish();
1954   }
1955
1956   $dbh->commit();
1957
1958   $main::lxdebug->leave_sub();
1959 }
1960
1961 sub save_bins {
1962   $main::lxdebug->enter_sub();
1963
1964   my ($self, $myconfig, $form) = @_;
1965
1966   # connect to database
1967   my $dbh = $form->get_standard_dbh($myconfig);
1968
1969   my ($query, @values, $commit_necessary, $sth);
1970
1971   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1972
1973   if (@values) {
1974     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1975     do_query($form, $dbh, $query, @values);
1976
1977     $commit_necessary = 1;
1978   }
1979
1980   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1981   $sth   = prepare_query($form, $dbh, $query);
1982
1983   foreach my $row (1..$form->{rowcount}) {
1984     next if ($form->{"delete_${row}"});
1985
1986     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1987
1988     $commit_necessary = 1;
1989   }
1990
1991   $sth->finish();
1992
1993   $dbh->commit() if ($commit_necessary);
1994
1995   $main::lxdebug->leave_sub();
1996 }
1997
1998 sub delete_warehouse {
1999   $main::lxdebug->enter_sub();
2000
2001   my ($self, $myconfig, $form) = @_;
2002
2003   # connect to database
2004   my $dbh = $form->get_standard_dbh($myconfig);
2005
2006   my $id      = conv_i($form->{id});
2007   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|;
2008   my ($count) = selectrow_query($form, $dbh, $query, $id);
2009
2010   if ($count) {
2011     $main::lxdebug->leave_sub();
2012     return 0;
2013   }
2014
2015   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2016   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2017
2018   $dbh->commit();
2019
2020   $main::lxdebug->leave_sub();
2021
2022   return 1;
2023 }
2024
2025 sub get_all_warehouses {
2026   $main::lxdebug->enter_sub();
2027
2028   my ($self, $myconfig, $form) = @_;
2029
2030   # connect to database
2031   my $dbh = $form->get_standard_dbh($myconfig);
2032
2033   my $query = qq|SELECT w.id, w.description, w.invalid,
2034                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2035                  FROM warehouse w
2036                  ORDER BY w.sortkey|;
2037
2038   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2039
2040   $main::lxdebug->leave_sub();
2041 }
2042
2043 sub get_warehouse {
2044   $main::lxdebug->enter_sub();
2045
2046   my ($self, $myconfig, $form) = @_;
2047
2048   # connect to database
2049   my $dbh = $form->get_standard_dbh($myconfig);
2050
2051   my $id    = conv_i($form->{id});
2052   my $query = qq|SELECT w.description, w.invalid
2053                  FROM warehouse w
2054                  WHERE w.id = ?|;
2055
2056   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2057
2058   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2059
2060   $query = qq|SELECT b.*, EXISTS
2061                 (SELECT i.warehouse_id
2062                  FROM inventory i
2063                  WHERE i.bin_id = b.id
2064                  LIMIT 1)
2065                 AS in_use
2066               FROM bin b
2067               WHERE b.warehouse_id = ?|;
2068
2069   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2070
2071   $main::lxdebug->leave_sub();
2072 }
2073
2074 1;