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