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