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