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