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