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