a17286711b953e7ccfe51bd0ff9c0e3c82244184
[kivitendo-erp.git] / 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   });
502
503   $main::lxdebug->leave_sub();
504 }
505
506 sub language {
507   $main::lxdebug->enter_sub();
508
509   my ($self, $myconfig, $form, $return_list) = @_;
510
511   my $dbh = SL::DB->client->dbh;
512
513   my $query =
514     "SELECT id, description, template_code, article_code, " .
515     "  output_numberformat, output_dateformat, output_longdates " .
516     "FROM language ORDER BY description";
517
518   my $sth = $dbh->prepare($query);
519   $sth->execute || $form->dberror($query);
520
521   my $ary = [];
522
523   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
524     push(@{ $ary }, $ref);
525   }
526
527   $sth->finish;
528
529   $main::lxdebug->leave_sub();
530
531   if ($return_list) {
532     return @{$ary};
533   } else {
534     $form->{ALL} = $ary;
535   }
536 }
537
538 sub get_language {
539   $main::lxdebug->enter_sub();
540
541   my ($self, $myconfig, $form) = @_;
542
543   my $dbh = SL::DB->client->dbh;
544
545   my $query =
546     "SELECT description, template_code, article_code, " .
547     "  output_numberformat, output_dateformat, output_longdates " .
548     "FROM language WHERE id = ?";
549   my $sth = $dbh->prepare($query);
550   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
551
552   my $ref = $sth->fetchrow_hashref("NAME_lc");
553
554   map { $form->{$_} = $ref->{$_} } keys %$ref;
555
556   $sth->finish;
557
558   $main::lxdebug->leave_sub();
559 }
560
561 sub get_language_details {
562   $main::lxdebug->enter_sub();
563
564   my ($self, $myconfig, $form, $id) = @_;
565
566   my $dbh = SL::DB->client->dbh;
567
568   my $query =
569     "SELECT template_code, " .
570     "  output_numberformat, output_dateformat, output_longdates " .
571     "FROM language WHERE id = ?";
572   my @res = selectrow_query($form, $dbh, $query, $id);
573
574   $main::lxdebug->leave_sub();
575
576   return @res;
577 }
578
579 sub save_language {
580   $main::lxdebug->enter_sub();
581
582   my ($self, $myconfig, $form) = @_;
583
584   SL::DB->client->with_transaction(sub {
585     my $dbh = SL::DB->client->dbh;
586     my (@values, $query);
587
588     map({ push(@values, $form->{$_}); }
589         qw(description template_code article_code
590            output_numberformat output_dateformat output_longdates));
591
592     # id is the old record
593     if ($form->{id}) {
594       $query =
595         "UPDATE language SET " .
596         "  description = ?, template_code = ?, article_code = ?, " .
597         "  output_numberformat = ?, output_dateformat = ?, " .
598         "  output_longdates = ? " .
599         "WHERE id = ?";
600       push(@values, $form->{id});
601     } else {
602       $query =
603         "INSERT INTO language (" .
604         "  description, template_code, article_code, " .
605         "  output_numberformat, output_dateformat, output_longdates" .
606         ") VALUES (?, ?, ?, ?, ?, ?)";
607     }
608     do_query($form, $dbh, $query, @values);
609   });
610
611   $main::lxdebug->leave_sub();
612 }
613
614 sub delete_language {
615   $main::lxdebug->enter_sub();
616
617   my ($self, $myconfig, $form) = @_;
618   my $query;
619
620   SL::DB->client->with_transaction(sub {
621     my $dbh = SL::DB->client->dbh;
622
623     foreach my $table (qw(generic_translations units_language)) {
624       $query = qq|DELETE FROM $table WHERE language_id = ?|;
625       do_query($form, $dbh, $query, $form->{"id"});
626     }
627
628     $query = "DELETE FROM language WHERE id = ?";
629     do_query($form, $dbh, $query, $form->{"id"});
630   });
631
632   $main::lxdebug->leave_sub();
633 }
634
635 sub prepare_template_filename {
636   $main::lxdebug->enter_sub();
637
638   my ($self, $myconfig, $form) = @_;
639
640   my ($filename, $display_filename);
641
642   if ($form->{type} eq "stylesheet") {
643     $filename = "css/$myconfig->{stylesheet}";
644     $display_filename = $myconfig->{stylesheet};
645
646   } else {
647     $filename = $form->{formname};
648
649     if ($form->{language}) {
650       my ($id, $template_code) = split(/--/, $form->{language});
651       $filename .= "_${template_code}";
652     }
653
654     if ($form->{printer}) {
655       my ($id, $template_code) = split(/--/, $form->{printer});
656       $filename .= "_${template_code}";
657     }
658
659     $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
660     if ($form->{"formname"} =~ m|\.\.| || $form->{"formname"} =~ m|^/|) {
661       $filename =~ s|.*/||;
662     }
663     $display_filename = $filename;
664     $filename = SL::DB::Default->get->templates . "/$filename";
665   }
666
667   $main::lxdebug->leave_sub();
668
669   return ($filename, $display_filename);
670 }
671
672
673 sub load_template {
674   $main::lxdebug->enter_sub();
675
676   my ($self, $filename) = @_;
677
678   my ($content, $lines) = ("", 0);
679
680   local *TEMPLATE;
681
682   if (open(TEMPLATE, $filename)) {
683     while (<TEMPLATE>) {
684       $content .= $_;
685       $lines++;
686     }
687     close(TEMPLATE);
688   }
689
690   $content = Encode::decode('utf-8-strict', $content);
691
692   $main::lxdebug->leave_sub();
693
694   return ($content, $lines);
695 }
696
697 sub save_template {
698   $main::lxdebug->enter_sub();
699
700   my ($self, $filename, $content) = @_;
701
702   local *TEMPLATE;
703
704   my $error = "";
705
706   if (open(TEMPLATE, ">", $filename)) {
707     $content = Encode::encode('utf-8-strict', $content);
708     $content =~ s/\r\n/\n/g;
709     print(TEMPLATE $content);
710     close(TEMPLATE);
711   } else {
712     $error = $!;
713   }
714
715   $main::lxdebug->leave_sub();
716
717   return $error;
718 }
719
720 sub save_preferences {
721   $main::lxdebug->enter_sub();
722
723   my ($self, $form) = @_;
724
725   my $employee = SL::DB::Manager::Employee->find_by(login => $::myconfig{login});
726   $employee->update_attributes(name => $form->{name});
727
728   my $user = SL::DB::Manager::AuthUser->find_by(login => $::myconfig{login});
729   $user->update_attributes(
730     config_values => {
731       %{ $user->config_values },
732       map { ($_ => $form->{$_}) } SL::DB::AuthUser::CONFIG_VARS(),
733     });
734
735   $main::lxdebug->leave_sub();
736
737   return 1;
738 }
739
740 sub get_defaults {
741   $main::lxdebug->enter_sub();
742
743   my $self     = shift;
744   my %params   = @_;
745
746   my $myconfig = \%main::myconfig;
747   my $form     = $main::form;
748
749   my $dbh      = $params{dbh} || SL::DB->client->dbh;
750
751   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
752
753   $defaults->{weightunit} ||= 'kg';
754
755   $main::lxdebug->leave_sub();
756
757   return $defaults;
758 }
759
760 sub closedto {
761   $main::lxdebug->enter_sub();
762
763   my ($self, $myconfig, $form) = @_;
764
765   my $dbh = SL::DB->client->dbh;
766
767   my $query = qq|SELECT closedto, max_future_booking_interval, revtrans FROM defaults|;
768   my $sth   = $dbh->prepare($query);
769   $sth->execute || $form->dberror($query);
770
771   ($form->{closedto}, $form->{max_future_booking_interval}, $form->{revtrans}) = $sth->fetchrow_array;
772
773   $sth->finish;
774
775   $main::lxdebug->leave_sub();
776 }
777
778 sub closebooks {
779   $main::lxdebug->enter_sub();
780
781   my ($self, $myconfig, $form) = @_;
782
783   SL::DB->client->with_transaction(sub {
784     my $dbh = SL::DB->client->dbh;
785
786     my ($query, @values);
787
788     # is currently NEVER trueish (no more hidden revtrans in $form)
789     # if ($form->{revtrans}) {
790     #   $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
791     # -> therefore you can only set this to false (which is already the default)
792     # and this flag is currently only checked in gl.pl. TOOD Can probably be removed
793
794       $query = qq|UPDATE defaults SET closedto = ?, max_future_booking_interval = ?, revtrans = '0'|;
795       @values = (conv_date($form->{closedto}), conv_i($form->{max_future_booking_interval}));
796
797     # set close in defaults
798     do_query($form, $dbh, $query, @values);
799   });
800
801   $main::lxdebug->leave_sub();
802 }
803
804 sub get_base_unit {
805   my ($self, $units, $unit_name, $factor) = @_;
806
807   $factor = 1 unless ($factor);
808
809   my $unit = $units->{$unit_name};
810
811   if (!defined($unit) || !$unit->{"base_unit"} ||
812       ($unit_name eq $unit->{"base_unit"})) {
813     return ($unit_name, $factor);
814   }
815
816   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
817 }
818
819 sub retrieve_units {
820   $main::lxdebug->enter_sub();
821
822   my ($self, $myconfig, $form, $prefix) = @_;
823   $prefix ||= '';
824
825   my $dbh = SL::DB->client->dbh;
826
827   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
828
829   my $sth = prepare_execute_query($form, $dbh, $query);
830
831   my $units = {};
832   while (my $ref = $sth->fetchrow_hashref()) {
833     $units->{$ref->{"name"}} = $ref;
834   }
835   $sth->finish();
836
837   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
838   $sth = $dbh->prepare($query_lang);
839   $sth->execute() || $form->dberror($query_lang);
840   my @languages;
841   while (my $ref = $sth->fetchrow_hashref()) {
842     push(@languages, $ref);
843   }
844   $sth->finish();
845
846   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
847     "FROM units_language ul " .
848     "LEFT JOIN language l ON ul.language_id = l.id " .
849     "WHERE ul.unit = ?";
850   $sth = $dbh->prepare($query_lang);
851
852   foreach my $unit (values(%{$units})) {
853     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
854
855     $unit->{"LANGUAGES"} = {};
856     foreach my $lang (@languages) {
857       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
858     }
859
860     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
861     while (my $ref = $sth->fetchrow_hashref()) {
862       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
863     }
864   }
865   $sth->finish;
866
867   $main::lxdebug->leave_sub();
868
869   return $units;
870 }
871
872 sub retrieve_all_units {
873   $main::lxdebug->enter_sub();
874
875   my $self = shift;
876
877   if (!$::request->{cache}{all_units}) {
878     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
879   }
880
881   $main::lxdebug->leave_sub();
882
883   return $::request->{cache}{all_units};
884 }
885
886
887 sub translate_units {
888   $main::lxdebug->enter_sub();
889
890   my ($self, $form, $template_code, $unit, $amount) = @_;
891
892   my $units = $self->retrieve_units(\%main::myconfig, $form);
893
894   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
895   my $new_unit = $unit;
896   if ($h) {
897     if (($amount != 1) && $h->{"localized_plural"}) {
898       $new_unit = $h->{"localized_plural"};
899     } elsif ($h->{"localized"}) {
900       $new_unit = $h->{"localized"};
901     }
902   }
903
904   $main::lxdebug->leave_sub();
905
906   return $new_unit;
907 }
908
909 sub units_in_use {
910   $main::lxdebug->enter_sub();
911
912   my ($self, $myconfig, $form, $units) = @_;
913
914   my $dbh = SL::DB->client->dbh;
915
916   map({ $_->{"in_use"} = 0; } values(%{$units}));
917
918   foreach my $unit (values(%{$units})) {
919     my $base_unit = $unit->{"original_base_unit"};
920     while ($base_unit) {
921       $units->{$base_unit}->{"in_use"} = 1;
922       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
923       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
924       $base_unit = $units->{$base_unit}->{"original_base_unit"};
925     }
926   }
927
928   foreach my $unit (values(%{$units})) {
929     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
930
931     foreach my $table (qw(parts invoice orderitems)) {
932       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
933
934       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
935         $query .= "= " . $dbh->quote($unit->{"name"});
936       } else {
937         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
938           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
939       }
940
941       my ($count) = $dbh->selectrow_array($query);
942       $form->dberror($query) if ($dbh->err);
943
944       if ($count) {
945         $unit->{"in_use"} = 1;
946         last;
947       }
948     }
949   }
950
951   $main::lxdebug->leave_sub();
952 }
953
954 sub convertible_units {
955   $main::lxdebug->enter_sub();
956
957   my $self        = shift;
958   my $units       = shift;
959   my $filter_unit = shift;
960   my $not_smaller = shift;
961
962   my $conv_units = [];
963
964   $filter_unit = $units->{$filter_unit};
965
966   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
967     my $unit = $units->{$name};
968
969     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
970         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
971       push @{$conv_units}, $unit;
972     }
973   }
974
975   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
976
977   $main::lxdebug->leave_sub();
978
979   return \@sorted;
980 }
981
982 # if $a is translatable to $b, return the factor between them.
983 # else return 1
984 sub convert_unit {
985   $main::lxdebug->enter_sub(2);
986   my ($this, $a, $b, $all_units) = @_;
987
988   if (!$all_units) {
989     $all_units = $this->retrieve_all_units;
990   }
991
992   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
993   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
994   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
995   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
996 }
997
998 sub unit_select_data {
999   $main::lxdebug->enter_sub();
1000
1001   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1002
1003   my $select = [];
1004
1005   if ($empty_entry) {
1006     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1007   }
1008
1009   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1010     if (!$convertible_into ||
1011         ($units->{$convertible_into} &&
1012          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1013       push @{$select}, { "name"      => $unit,
1014                          "base_unit" => $units->{$unit}->{"base_unit"},
1015                          "factor"    => $units->{$unit}->{"factor"},
1016                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1017     }
1018   }
1019
1020   $main::lxdebug->leave_sub();
1021
1022   return $select;
1023 }
1024
1025 sub unit_select_html {
1026   $main::lxdebug->enter_sub();
1027
1028   my ($self, $units, $name, $selected, $convertible_into) = @_;
1029
1030   my $select = "<select name=${name}>";
1031
1032   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1033     if (!$convertible_into ||
1034         ($units->{$convertible_into} &&
1035          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1036       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1037     }
1038   }
1039   $select .= "</select>";
1040
1041   $main::lxdebug->leave_sub();
1042
1043   return $select;
1044 }
1045
1046 sub sum_with_unit {
1047   $main::lxdebug->enter_sub();
1048
1049   my $self  = shift;
1050
1051   my $units = $self->retrieve_all_units();
1052
1053   my $sum   = 0;
1054   my $base_unit;
1055
1056   while (2 <= scalar(@_)) {
1057     my $qty  = shift(@_);
1058     my $unit = $units->{shift(@_)};
1059
1060     croak "No unit defined with name $unit" if (!defined $unit);
1061
1062     if (!$base_unit) {
1063       $base_unit = $unit->{base_unit};
1064     } elsif ($base_unit ne $unit->{base_unit}) {
1065       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1066     }
1067
1068     $sum += $qty * $unit->{factor};
1069   }
1070
1071   $main::lxdebug->leave_sub();
1072
1073   return $sum;
1074 }
1075
1076 sub add_unit {
1077   $main::lxdebug->enter_sub();
1078
1079   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1080
1081   SL::DB->client->with_transaction(sub {
1082     my $dbh = SL::DB->client->dbh;
1083
1084     my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1085     my ($sortkey) = selectrow_query($form, $dbh, $query);
1086
1087     $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1088       "VALUES (?, ?, ?, ?)";
1089     do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1090
1091     if ($languages) {
1092       $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1093       my $sth = $dbh->prepare($query);
1094       foreach my $lang (@{$languages}) {
1095         my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1096         $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1097       }
1098       $sth->finish();
1099     }
1100   });
1101
1102   $main::lxdebug->leave_sub();
1103 }
1104
1105 sub save_units {
1106   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1107   $main::lxdebug->enter_sub();
1108
1109   my $rc = SL::DB->client->with_transaction(\&_save_units, $self, $myconfig, $form, $units, $delete_units);
1110
1111   $::lxdebug->leave_sub;
1112   return $rc;
1113 }
1114
1115 sub _save_units {
1116   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1117
1118   my $dbh = SL::DB->client->dbh;
1119
1120   my ($base_unit, $unit, $sth, $query);
1121
1122   $query = "DELETE FROM units_language";
1123   $dbh->do($query) || $form->dberror($query);
1124
1125   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1126     $query = "DELETE FROM units WHERE name IN (";
1127     map({ $query .= "?," } @{$delete_units});
1128     substr($query, -1, 1) = ")";
1129     $dbh->do($query, undef, @{$delete_units}) ||
1130       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1131   }
1132
1133   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1134   $sth = $dbh->prepare($query);
1135
1136   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1137   my $sth_lang = $dbh->prepare($query_lang);
1138
1139   foreach $unit (values(%{$units})) {
1140     $unit->{"depth"} = 0;
1141     my $base_unit = $unit;
1142     while ($base_unit->{"base_unit"}) {
1143       $unit->{"depth"}++;
1144       $base_unit = $units->{$base_unit->{"base_unit"}};
1145     }
1146   }
1147
1148   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1149     if ($unit->{"LANGUAGES"}) {
1150       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1151         next unless ($lang->{"id"} && $lang->{"localized"});
1152         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1153         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1154       }
1155     }
1156
1157     next if ($unit->{"unchanged_unit"});
1158
1159     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1160     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1161   }
1162
1163   $sth->finish();
1164   $sth_lang->finish();
1165
1166   return 1;
1167 }
1168
1169 sub taxes {
1170   $main::lxdebug->enter_sub();
1171
1172   my ($self, $myconfig, $form) = @_;
1173
1174   my $dbh = SL::DB->client->dbh;
1175
1176   my $query = qq|SELECT
1177                    t.id,
1178                    t.taxkey,
1179                    t.taxdescription,
1180                    round(t.rate * 100, 2) AS rate,
1181                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1182                    (SELECT description FROM chart WHERE id = chart_id) AS account_description,
1183                    (SELECT accno FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_accno,
1184                    (SELECT description FROM chart WHERE id = skonto_sales_chart_id) AS skonto_chart_description,
1185                    (SELECT accno FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_accno,
1186                    (SELECT description FROM chart WHERE id = skonto_purchase_chart_id) AS skonto_chart_purchase_description
1187                  FROM tax t
1188                  ORDER BY taxkey, rate|;
1189
1190   my $sth = $dbh->prepare($query);
1191   $sth->execute || $form->dberror($query);
1192
1193   $form->{TAX} = [];
1194   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1195     push @{ $form->{TAX} }, $ref;
1196   }
1197
1198   $sth->finish;
1199
1200   $main::lxdebug->leave_sub();
1201 }
1202
1203 sub get_tax_accounts {
1204   $main::lxdebug->enter_sub();
1205
1206   my ($self, $myconfig, $form) = @_;
1207
1208   my $dbh = SL::DB->client->dbh;
1209
1210   # get Accounts from chart
1211   my $query = qq{ SELECT
1212                  id,
1213                  accno || ' - ' || description AS taxaccount
1214                FROM chart
1215                WHERE link LIKE '%_tax%'
1216                ORDER BY accno
1217              };
1218
1219   my $sth = $dbh->prepare($query);
1220   $sth->execute || $form->dberror($query);
1221
1222   $form->{ACCOUNTS} = [];
1223   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1224     push @{ $form->{ACCOUNTS} }, $ref;
1225   }
1226
1227   $form->{AR_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AR_paid%' } ], sort_by => 'accno ASC');
1228   $form->{AP_PAID} = SL::DB::Manager::Chart->get_all(where => [ link => { like => '%AP_paid%' } ], sort_by => 'accno ASC');
1229
1230   $form->{skontochart_value_title_sub} = sub {
1231     my $item = shift;
1232     return [
1233       $item->{id},
1234       $item->{accno} .' '. $item->{description},
1235     ];
1236   };
1237
1238   $sth->finish;
1239
1240   $main::lxdebug->leave_sub();
1241 }
1242
1243 sub get_tax {
1244   $main::lxdebug->enter_sub();
1245
1246   my ($self, $myconfig, $form) = @_;
1247
1248   my $dbh = SL::DB->client->dbh;
1249
1250   my $query = qq|SELECT
1251                    taxkey,
1252                    taxdescription,
1253                    round(rate * 100, 2) AS rate,
1254                    chart_id,
1255                    chart_categories,
1256                    (id IN (SELECT tax_id
1257                            FROM acc_trans)) AS tax_already_used,
1258                    skonto_sales_chart_id,
1259                    skonto_purchase_chart_id
1260                  FROM tax
1261                  WHERE id = ? |;
1262
1263   my $sth = $dbh->prepare($query);
1264   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1265
1266   my $ref = $sth->fetchrow_hashref("NAME_lc");
1267
1268   map { $form->{$_} = $ref->{$_} } keys %$ref;
1269
1270   $sth->finish;
1271
1272   # see if it is used by a taxkey
1273   $query = qq|SELECT count(*) FROM taxkeys
1274               WHERE tax_id = ? AND chart_id >0|;
1275
1276   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1277
1278   $form->{orphaned} = !$form->{orphaned};
1279   $sth->finish;
1280
1281   if (!$form->{orphaned} ) {
1282     $query = qq|SELECT DISTINCT c.id, c.accno
1283                 FROM taxkeys tk
1284                 JOIN   tax t ON (t.id = tk.tax_id)
1285                 JOIN chart c ON (c.id = tk.chart_id)
1286                 WHERE tk.tax_id = ?|;
1287
1288     $sth = $dbh->prepare($query);
1289     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1290
1291     $form->{TAXINUSE} = [];
1292     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1293       push @{ $form->{TAXINUSE} }, $ref;
1294     }
1295
1296     $sth->finish;
1297   }
1298
1299   $main::lxdebug->leave_sub();
1300 }
1301
1302 sub save_tax {
1303   my ($self, $myconfig, $form) = @_;
1304   $main::lxdebug->enter_sub();
1305
1306   my $rc = SL::DB->client->with_transaction(\&_save_tax, $self, $myconfig, $form);
1307
1308   $::lxdebug->leave_sub;
1309   return $rc;
1310 }
1311
1312 sub _save_tax {
1313   my ($self, $myconfig, $form) = @_;
1314   my $query;
1315
1316   my $dbh = SL::DB->client->dbh;
1317
1318   $form->{rate} = $form->{rate} / 100;
1319
1320   my $chart_categories = '';
1321   $chart_categories .= 'A' if $form->{asset};
1322   $chart_categories .= 'L' if $form->{liability};
1323   $chart_categories .= 'Q' if $form->{equity};
1324   $chart_categories .= 'I' if $form->{revenue};
1325   $chart_categories .= 'E' if $form->{expense};
1326   $chart_categories .= 'C' if $form->{costs};
1327
1328   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);
1329   if ($form->{id} ne "") {
1330     $query = qq|UPDATE tax SET
1331                   taxkey                   = ?,
1332                   taxdescription           = ?,
1333                   rate                     = ?,
1334                   chart_id                 = ?,
1335                   taxnumber                = (SELECT accno FROM chart WHERE id = ? ),
1336                   skonto_sales_chart_id    = ?,
1337                   skonto_purchase_chart_id = ?,
1338                   chart_categories         = ?
1339                 WHERE id = ?|;
1340
1341   } else {
1342     #ok
1343     ($form->{id}) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('id')|);
1344     $query = qq|INSERT INTO tax (
1345                   taxkey,
1346                   taxdescription,
1347                   rate,
1348                   chart_id,
1349                   taxnumber,
1350                   skonto_sales_chart_id,
1351                   skonto_purchase_chart_id,
1352                   chart_categories,
1353                   id
1354                 )
1355                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?), ?, ?,  ?, ?)|;
1356   }
1357   push(@values, $form->{id});
1358   do_query($form, $dbh, $query, @values);
1359
1360   foreach my $language_id (keys %{ $form->{translations} }) {
1361     GenericTranslations->save('dbh'              => $dbh,
1362                               'translation_type' => 'SL::DB::Tax/taxdescription',
1363                               'translation_id'   => $form->{id},
1364                               'language_id'      => $language_id,
1365                               'translation'      => $form->{translations}->{$language_id});
1366   }
1367 }
1368
1369 sub delete_tax {
1370   $main::lxdebug->enter_sub();
1371
1372   my ($self, $myconfig, $form) = @_;
1373   my $query;
1374
1375   SL::DB->client->with_transaction(sub {
1376     $query = qq|DELETE FROM tax WHERE id = ?|;
1377     do_query($form, SL::DB->client->dbh, $query, $form->{id});
1378   });
1379
1380   $main::lxdebug->leave_sub();
1381 }
1382
1383 sub save_price_factor {
1384   $main::lxdebug->enter_sub();
1385
1386   my ($self, $myconfig, $form) = @_;
1387
1388   SL::DB->client->with_transaction(sub {
1389     my $dbh = SL::DB->client->dbh;
1390
1391     my $query;
1392     my @values = ($form->{description}, conv_i($form->{factor}));
1393
1394     if ($form->{id}) {
1395       $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1396       push @values, conv_i($form->{id});
1397
1398     } else {
1399       $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1400     }
1401
1402     do_query($form, $dbh, $query, @values);
1403   });
1404
1405   $main::lxdebug->leave_sub();
1406 }
1407
1408 sub get_all_price_factors {
1409   $main::lxdebug->enter_sub();
1410
1411   my ($self, $myconfig, $form) = @_;
1412
1413   my $dbh = SL::DB->client->dbh;
1414
1415   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1416
1417   $main::lxdebug->leave_sub();
1418 }
1419
1420 sub get_price_factor {
1421   $main::lxdebug->enter_sub();
1422
1423   my ($self, $myconfig, $form) = @_;
1424
1425   # connect to database
1426   my $dbh = SL::DB->client->dbh;
1427
1428   my $query = qq|SELECT description, factor,
1429                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
1430                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
1431                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1432                  FROM price_factors WHERE id = ?|;
1433
1434   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1435
1436   $main::lxdebug->leave_sub();
1437 }
1438
1439 sub delete_price_factor {
1440   $main::lxdebug->enter_sub();
1441
1442   my ($self, $myconfig, $form) = @_;
1443
1444   SL::DB->client->with_transaction(sub {
1445     do_query($form, SL::DB->client->dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1446   });
1447
1448   $main::lxdebug->leave_sub();
1449 }
1450
1451 sub save_warehouse {
1452   $main::lxdebug->enter_sub();
1453
1454   my ($self, $myconfig, $form) = @_;
1455
1456   SL::DB->client->with_transaction(sub {
1457     my $dbh = SL::DB->client->dbh;
1458
1459     my ($query, @values, $sth);
1460
1461     if (!$form->{id}) {
1462       $query        = qq|SELECT nextval('id')|;
1463       ($form->{id}) = selectrow_query($form, $dbh, $query);
1464
1465       $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1466       do_query($form, $dbh, $query, $form->{id});
1467     }
1468
1469     do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1470              $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1471
1472     if (0 < $form->{number_of_new_bins}) {
1473       my ($num_existing_bins) = selectfirst_array_query($form, $dbh, qq|SELECT COUNT(*) FROM bin WHERE warehouse_id = ?|, $form->{id});
1474       $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1475       $sth   = prepare_query($form, $dbh, $query);
1476
1477       foreach my $i (1..$form->{number_of_new_bins}) {
1478         do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}" . ($i + $num_existing_bins));
1479       }
1480
1481       $sth->finish();
1482     }
1483   });
1484
1485   $main::lxdebug->leave_sub();
1486 }
1487
1488 sub save_bins {
1489   $main::lxdebug->enter_sub();
1490
1491   my ($self, $myconfig, $form) = @_;
1492
1493   SL::DB->client->with_transaction(sub {
1494     my $dbh = SL::DB->client->dbh;
1495
1496     my ($query, @values, $sth);
1497
1498     @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1499
1500     if (@values) {
1501       $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1502       do_query($form, $dbh, $query, @values);
1503     }
1504
1505     $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1506     $sth   = prepare_query($form, $dbh, $query);
1507
1508     foreach my $row (1..$form->{rowcount}) {
1509       next if ($form->{"delete_${row}"});
1510
1511       do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1512     }
1513
1514     $sth->finish();
1515   });
1516
1517   $main::lxdebug->leave_sub();
1518 }
1519
1520 sub delete_warehouse {
1521   $main::lxdebug->enter_sub();
1522
1523   my ($self, $myconfig, $form) = @_;
1524
1525   my $rc = SL::DB->client->with_transaction(sub {
1526     my $dbh = SL::DB->client->dbh;
1527
1528     my $id      = conv_i($form->{id});
1529     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|;
1530     my ($count) = selectrow_query($form, $dbh, $query, $id);
1531
1532     if ($count) {
1533       return 0;
1534     }
1535
1536     do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
1537     do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
1538
1539     return 1;
1540   });
1541
1542   $main::lxdebug->leave_sub();
1543
1544   return $rc;
1545 }
1546
1547 sub get_all_warehouses {
1548   $main::lxdebug->enter_sub();
1549
1550   my ($self, $myconfig, $form) = @_;
1551
1552   my $dbh = SL::DB->client->dbh;
1553
1554   my $query = qq|SELECT w.id, w.description, w.invalid,
1555                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
1556                  FROM warehouse w
1557                  ORDER BY w.sortkey|;
1558
1559   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
1560
1561   $main::lxdebug->leave_sub();
1562 }
1563
1564 sub get_warehouse {
1565   $main::lxdebug->enter_sub();
1566
1567   my ($self, $myconfig, $form) = @_;
1568
1569   my $dbh = SL::DB->client->dbh;
1570
1571   my $id    = conv_i($form->{id});
1572   my $query = qq|SELECT w.description, w.invalid
1573                  FROM warehouse w
1574                  WHERE w.id = ?|;
1575
1576   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
1577
1578   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1579
1580   $query = <<SQL;
1581     SELECT b.*,
1582       (   EXISTS(SELECT i.bin_id FROM inventory i WHERE i.bin_id = b.id LIMIT 1)
1583        OR EXISTS(SELECT p.bin_id FROM parts     p WHERE p.bin_id = b.id LIMIT 1))
1584       AS in_use
1585     FROM bin b
1586     WHERE b.warehouse_id = ?
1587 SQL
1588
1589   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1590
1591   $main::lxdebug->leave_sub();
1592 }
1593
1594 1;