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