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