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