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