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