Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[kivitendo-erp.git] / SL / AM.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Administration module
32 #    Chart of Accounts
33 #    template routines
34 #    preferences
35 #
36 #======================================================================
37
38 package AM;
39
40 use Carp;
41 use Data::Dumper;
42 use Encode;
43 use List::MoreUtils qw(any);
44 use SL::DBUtils;
45 use SL::DB::AuthUser;
46 use SL::DB::Default;
47 use SL::DB::Employee;
48
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);
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);
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     });
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;