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