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