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