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