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