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