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