dokumentation.pdf zur Klarheit umbenennen
[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     puhs(@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 = new User($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   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1513   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1514   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1515   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1516 }
1517
1518 sub unit_select_data {
1519   $main::lxdebug->enter_sub();
1520
1521   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1522
1523   my $select = [];
1524
1525   if ($empty_entry) {
1526     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1527   }
1528
1529   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1530     if (!$convertible_into ||
1531         ($units->{$convertible_into} &&
1532          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1533       push @{$select}, { "name"      => $unit,
1534                          "base_unit" => $units->{$unit}->{"base_unit"},
1535                          "factor"    => $units->{$unit}->{"factor"},
1536                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1537     }
1538   }
1539
1540   $main::lxdebug->leave_sub();
1541
1542   return $select;
1543 }
1544
1545 sub unit_select_html {
1546   $main::lxdebug->enter_sub();
1547
1548   my ($self, $units, $name, $selected, $convertible_into) = @_;
1549
1550   my $select = "<select name=${name}>";
1551
1552   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1553     if (!$convertible_into ||
1554         ($units->{$convertible_into} &&
1555          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1556       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1557     }
1558   }
1559   $select .= "</select>";
1560
1561   $main::lxdebug->leave_sub();
1562
1563   return $select;
1564 }
1565
1566 sub sum_with_unit {
1567   $main::lxdebug->enter_sub();
1568
1569   my $self  = shift;
1570
1571   my $units = $self->retrieve_all_units();
1572
1573   my $sum   = 0;
1574   my $base_unit;
1575
1576   while (2 <= scalar(@_)) {
1577     my $qty  = shift(@_);
1578     my $unit = $units->{shift(@_)};
1579
1580     croak "No unit defined with name $unit" if (!defined $unit);
1581
1582     if (!$base_unit) {
1583       $base_unit = $unit->{base_unit};
1584     } elsif ($base_unit ne $unit->{base_unit}) {
1585       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1586     }
1587
1588     $sum += $qty * $unit->{factor};
1589   }
1590
1591   $main::lxdebug->leave_sub();
1592
1593   return wantarray ? ($sum, $base_unit) : $sum;
1594 }
1595
1596 sub add_unit {
1597   $main::lxdebug->enter_sub();
1598
1599   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1600
1601   my $dbh = $form->dbconnect_noauto($myconfig);
1602
1603   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1604   my ($sortkey) = selectrow_query($form, $dbh, $query);
1605
1606   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1607     "VALUES (?, ?, ?, ?)";
1608   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1609
1610   if ($languages) {
1611     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1612     my $sth = $dbh->prepare($query);
1613     foreach my $lang (@{$languages}) {
1614       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1615       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1616     }
1617     $sth->finish();
1618   }
1619
1620   $dbh->commit();
1621   $dbh->disconnect();
1622
1623   $main::lxdebug->leave_sub();
1624 }
1625
1626 sub save_units {
1627   $main::lxdebug->enter_sub();
1628
1629   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1630
1631   my $dbh = $form->dbconnect_noauto($myconfig);
1632
1633   my ($base_unit, $unit, $sth, $query);
1634
1635   $query = "DELETE FROM units_language";
1636   $dbh->do($query) || $form->dberror($query);
1637
1638   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1639     $query = "DELETE FROM units WHERE name IN (";
1640     map({ $query .= "?," } @{$delete_units});
1641     substr($query, -1, 1) = ")";
1642     $dbh->do($query, undef, @{$delete_units}) ||
1643       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1644   }
1645
1646   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1647   $sth = $dbh->prepare($query);
1648
1649   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1650   my $sth_lang = $dbh->prepare($query_lang);
1651
1652   foreach $unit (values(%{$units})) {
1653     $unit->{"depth"} = 0;
1654     my $base_unit = $unit;
1655     while ($base_unit->{"base_unit"}) {
1656       $unit->{"depth"}++;
1657       $base_unit = $units->{$base_unit->{"base_unit"}};
1658     }
1659   }
1660
1661   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1662     if ($unit->{"LANGUAGES"}) {
1663       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1664         next unless ($lang->{"id"} && $lang->{"localized"});
1665         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1666         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1667       }
1668     }
1669
1670     next if ($unit->{"unchanged_unit"});
1671
1672     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1673     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1674   }
1675
1676   $sth->finish();
1677   $sth_lang->finish();
1678   $dbh->commit();
1679   $dbh->disconnect();
1680
1681   $main::lxdebug->leave_sub();
1682 }
1683
1684 sub taxes {
1685   $main::lxdebug->enter_sub();
1686
1687   my ($self, $myconfig, $form) = @_;
1688
1689   # connect to database
1690   my $dbh = $form->dbconnect($myconfig);
1691
1692   my $query = qq|SELECT
1693                    t.id,
1694                    t.taxkey,
1695                    t.taxdescription,
1696                    round(t.rate * 100, 2) AS rate,
1697                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1698                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
1699                  FROM tax t
1700                  ORDER BY taxkey|;
1701
1702   my $sth = $dbh->prepare($query);
1703   $sth->execute || $form->dberror($query);
1704
1705   $form->{TAX} = [];
1706   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1707     push @{ $form->{TAX} }, $ref;
1708   }
1709
1710   $sth->finish;
1711   $dbh->disconnect;
1712
1713   $main::lxdebug->leave_sub();
1714 }
1715
1716 sub get_tax_accounts {
1717   $main::lxdebug->enter_sub();
1718
1719   my ($self, $myconfig, $form) = @_;
1720
1721   my $dbh = $form->dbconnect($myconfig);
1722
1723   # get Accounts from chart
1724   my $query = qq{ SELECT
1725                  id,
1726                  accno || ' - ' || description AS taxaccount
1727                FROM chart
1728                WHERE link LIKE '%_tax%'
1729                ORDER BY accno
1730              };
1731
1732   my $sth = $dbh->prepare($query);
1733   $sth->execute || $form->dberror($query);
1734
1735   $form->{ACCOUNTS} = [];
1736   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1737     push @{ $form->{ACCOUNTS} }, $ref;
1738   }
1739
1740   $sth->finish;
1741
1742   $dbh->disconnect;
1743
1744   $main::lxdebug->leave_sub();
1745 }
1746
1747 sub get_tax {
1748   $main::lxdebug->enter_sub();
1749
1750   my ($self, $myconfig, $form) = @_;
1751
1752   # connect to database
1753   my $dbh = $form->dbconnect($myconfig);
1754
1755   my $query = qq|SELECT
1756                    taxkey,
1757                    taxdescription,
1758                    round(rate * 100, 2) AS rate,
1759                    chart_id
1760                  FROM tax
1761                  WHERE id = ? |;
1762
1763   my $sth = $dbh->prepare($query);
1764   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1765
1766   my $ref = $sth->fetchrow_hashref("NAME_lc");
1767
1768   map { $form->{$_} = $ref->{$_} } keys %$ref;
1769
1770   $sth->finish;
1771
1772   # see if it is used by a taxkey
1773   $query = qq|SELECT count(*) FROM taxkeys
1774               WHERE tax_id = ? AND chart_id >0|;
1775
1776   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1777
1778   $form->{orphaned} = !$form->{orphaned};
1779   $sth->finish;
1780
1781   if (!$form->{orphaned} ) {
1782     $query = qq|SELECT DISTINCT c.id, c.accno
1783                 FROM taxkeys tk
1784                 JOIN   tax t ON (t.id = tk.tax_id)
1785                 JOIN chart c ON (c.id = tk.chart_id)
1786                 WHERE tk.tax_id = ?|;
1787
1788     $sth = $dbh->prepare($query);
1789     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1790
1791     $form->{TAXINUSE} = [];
1792     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1793       push @{ $form->{TAXINUSE} }, $ref;
1794     }
1795
1796     $sth->finish;
1797   }
1798
1799   $dbh->disconnect;
1800
1801   $main::lxdebug->leave_sub();
1802 }
1803
1804 sub save_tax {
1805   $main::lxdebug->enter_sub();
1806
1807   my ($self, $myconfig, $form) = @_;
1808   my $query;
1809
1810   # connect to database
1811   my $dbh = $form->get_standard_dbh($myconfig);
1812
1813   $form->{rate} = $form->{rate} / 100;
1814
1815   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
1816   if ($form->{id} ne "") {
1817     $query = qq|UPDATE tax SET
1818                   taxkey         = ?,
1819                   taxdescription = ?,
1820                   rate           = ?,
1821                   chart_id       = ?,
1822                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
1823                 WHERE id = ?|;
1824     push(@values, $form->{id});
1825
1826   } else {
1827     #ok
1828     $query = qq|INSERT INTO tax (
1829                   taxkey,
1830                   taxdescription,
1831                   rate,
1832                   chart_id,
1833                   taxnumber
1834                 )
1835                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
1836   }
1837   do_query($form, $dbh, $query, @values);
1838
1839   $dbh->commit();
1840
1841   $main::lxdebug->leave_sub();
1842 }
1843
1844 sub delete_tax {
1845   $main::lxdebug->enter_sub();
1846
1847   my ($self, $myconfig, $form) = @_;
1848   my $query;
1849
1850   # connect to database
1851   my $dbh = $form->get_standard_dbh($myconfig);
1852
1853   $query = qq|DELETE FROM tax
1854               WHERE id = ?|;
1855   do_query($form, $dbh, $query, $form->{id});
1856
1857   $dbh->commit();
1858
1859   $main::lxdebug->leave_sub();
1860 }
1861
1862 sub save_price_factor {
1863   $main::lxdebug->enter_sub();
1864
1865   my ($self, $myconfig, $form) = @_;
1866
1867   # connect to database
1868   my $dbh = $form->get_standard_dbh($myconfig);
1869
1870   my $query;
1871   my @values = ($form->{description}, conv_i($form->{factor}));
1872
1873   if ($form->{id}) {
1874     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1875     push @values, conv_i($form->{id});
1876
1877   } else {
1878     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1879   }
1880
1881   do_query($form, $dbh, $query, @values);
1882
1883   $dbh->commit();
1884
1885   $main::lxdebug->leave_sub();
1886 }
1887
1888 sub get_all_price_factors {
1889   $main::lxdebug->enter_sub();
1890
1891   my ($self, $myconfig, $form) = @_;
1892
1893   # connect to database
1894   my $dbh = $form->get_standard_dbh($myconfig);
1895
1896   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1897
1898   $main::lxdebug->leave_sub();
1899 }
1900
1901 sub get_price_factor {
1902   $main::lxdebug->enter_sub();
1903
1904   my ($self, $myconfig, $form) = @_;
1905
1906   # connect to database
1907   my $dbh = $form->get_standard_dbh($myconfig);
1908
1909   my $query = qq|SELECT description, factor,
1910                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
1911                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
1912                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1913                  FROM price_factors WHERE id = ?|;
1914
1915   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1916
1917   $main::lxdebug->leave_sub();
1918 }
1919
1920 sub delete_price_factor {
1921   $main::lxdebug->enter_sub();
1922
1923   my ($self, $myconfig, $form) = @_;
1924
1925   # connect to database
1926   my $dbh = $form->get_standard_dbh($myconfig);
1927
1928   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1929   $dbh->commit();
1930
1931   $main::lxdebug->leave_sub();
1932 }
1933
1934 sub save_warehouse {
1935   $main::lxdebug->enter_sub();
1936
1937   my ($self, $myconfig, $form) = @_;
1938
1939   # connect to database
1940   my $dbh = $form->get_standard_dbh($myconfig);
1941
1942   my ($query, @values, $sth);
1943
1944   if (!$form->{id}) {
1945     $query        = qq|SELECT nextval('id')|;
1946     ($form->{id}) = selectrow_query($form, $dbh, $query);
1947
1948     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1949     do_query($form, $dbh, $query, $form->{id});
1950   }
1951
1952   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1953            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1954
1955   if (0 < $form->{number_of_new_bins}) {
1956     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1957     $sth   = prepare_query($form, $dbh, $query);
1958
1959     foreach my $i (1..$form->{number_of_new_bins}) {
1960       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
1961     }
1962
1963     $sth->finish();
1964   }
1965
1966   $dbh->commit();
1967
1968   $main::lxdebug->leave_sub();
1969 }
1970
1971 sub save_bins {
1972   $main::lxdebug->enter_sub();
1973
1974   my ($self, $myconfig, $form) = @_;
1975
1976   # connect to database
1977   my $dbh = $form->get_standard_dbh($myconfig);
1978
1979   my ($query, @values, $commit_necessary, $sth);
1980
1981   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1982
1983   if (@values) {
1984     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1985     do_query($form, $dbh, $query, @values);
1986
1987     $commit_necessary = 1;
1988   }
1989
1990   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1991   $sth   = prepare_query($form, $dbh, $query);
1992
1993   foreach my $row (1..$form->{rowcount}) {
1994     next if ($form->{"delete_${row}"});
1995
1996     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1997
1998     $commit_necessary = 1;
1999   }
2000
2001   $sth->finish();
2002
2003   $dbh->commit() if ($commit_necessary);
2004
2005   $main::lxdebug->leave_sub();
2006 }
2007
2008 sub delete_warehouse {
2009   $main::lxdebug->enter_sub();
2010
2011   my ($self, $myconfig, $form) = @_;
2012
2013   # connect to database
2014   my $dbh = $form->get_standard_dbh($myconfig);
2015
2016   my $id      = conv_i($form->{id});
2017   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|;
2018   my ($count) = selectrow_query($form, $dbh, $query, $id);
2019
2020   if ($count) {
2021     $main::lxdebug->leave_sub();
2022     return 0;
2023   }
2024
2025   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2026   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2027
2028   $dbh->commit();
2029
2030   $main::lxdebug->leave_sub();
2031
2032   return 1;
2033 }
2034
2035 sub get_all_warehouses {
2036   $main::lxdebug->enter_sub();
2037
2038   my ($self, $myconfig, $form) = @_;
2039
2040   # connect to database
2041   my $dbh = $form->get_standard_dbh($myconfig);
2042
2043   my $query = qq|SELECT w.id, w.description, w.invalid,
2044                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2045                  FROM warehouse w
2046                  ORDER BY w.sortkey|;
2047
2048   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2049
2050   $main::lxdebug->leave_sub();
2051 }
2052
2053 sub get_warehouse {
2054   $main::lxdebug->enter_sub();
2055
2056   my ($self, $myconfig, $form) = @_;
2057
2058   # connect to database
2059   my $dbh = $form->get_standard_dbh($myconfig);
2060
2061   my $id    = conv_i($form->{id});
2062   my $query = qq|SELECT w.description, w.invalid
2063                  FROM warehouse w
2064                  WHERE w.id = ?|;
2065
2066   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2067
2068   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2069
2070   $query = qq|SELECT b.*, EXISTS
2071                 (SELECT i.warehouse_id
2072                  FROM inventory i
2073                  WHERE i.bin_id = b.id
2074                  LIMIT 1)
2075                 AS in_use
2076               FROM bin b
2077               WHERE b.warehouse_id = ?|;
2078
2079   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2080
2081   $main::lxdebug->leave_sub();
2082 }
2083
2084 1;