Dokumentation für Flags in Variablen in Druckvorlagen
[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., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Administration module
32 #    Chart of Accounts
33 #    template routines
34 #    preferences
35 #
36 #======================================================================
37
38 package AM;
39
40 use Carp;
41 use Data::Dumper;
42 use Encode;
43 use SL::DBUtils;
44
45 use strict;
46
47 sub get_account {
48   $main::lxdebug->enter_sub();
49
50   my ($self, $myconfig, $form) = @_;
51
52   # connect to database
53   my $dbh = $form->dbconnect($myconfig);
54   my $query = qq{
55     SELECT c.accno, c.description, c.charttype, c.category,
56       c.link, c.pos_bilanz, c.pos_eur, c.new_chart_id, c.valid_from,
57       c.pos_bwa, datevautomatik,
58       tk.taxkey_id, tk.pos_ustva, tk.tax_id,
59       tk.tax_id || '--' || tk.taxkey_id AS tax, tk.startdate
60     FROM chart c
61     LEFT JOIN taxkeys tk
62     ON (c.id=tk.chart_id AND tk.id =
63       (SELECT id FROM taxkeys
64        WHERE taxkeys.chart_id = c.id AND startdate <= current_date
65        ORDER BY startdate DESC LIMIT 1))
66     WHERE c.id = ?
67     };
68
69
70   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
71   my $sth = $dbh->prepare($query);
72   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
73
74   my $ref = $sth->fetchrow_hashref("NAME_lc");
75
76   foreach my $key (keys %$ref) {
77     $form->{"$key"} = $ref->{"$key"};
78   }
79
80   $sth->finish;
81
82   # get default accounts
83   $query = qq|SELECT inventory_accno_id, income_accno_id, expense_accno_id
84               FROM defaults|;
85   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
86   $sth = $dbh->prepare($query);
87   $sth->execute || $form->dberror($query);
88
89   $ref = $sth->fetchrow_hashref("NAME_lc");
90
91   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
92
93   $sth->finish;
94
95
96
97   # get taxkeys and description
98   $query = qq{
99     SELECT
100       id,
101       (SELECT accno FROM chart WHERE id=tax.chart_id) AS chart_accno,
102       taxkey,
103       id||'--'||taxkey AS tax,
104       taxdescription,
105       rate
106     FROM tax ORDER BY taxkey
107   };
108   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
109   $sth = $dbh->prepare($query);
110   $sth->execute || $form->dberror($query);
111
112   $form->{TAXKEY} = [];
113
114   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
115     push @{ $form->{TAXKEY} }, $ref;
116   }
117
118   $sth->finish;
119   if ($form->{id}) {
120     # get new accounts
121     $query = qq|SELECT id, accno,description
122                 FROM chart
123                 WHERE link = ?
124                 ORDER BY accno|;
125     $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
126     $sth = $dbh->prepare($query);
127     $sth->execute($form->{link}) || $form->dberror($query . " ($form->{link})");
128
129     $form->{NEWACCOUNT} = [];
130     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
131       push @{ $form->{NEWACCOUNT} }, $ref;
132     }
133
134     $sth->finish;
135
136     # get the taxkeys of account
137
138     $query = qq{
139       SELECT
140         tk.id,
141         tk.chart_id,
142         c.accno,
143         tk.tax_id,
144         t.taxdescription,
145         t.rate,
146         tk.taxkey_id,
147         tk.pos_ustva,
148         tk.startdate
149       FROM taxkeys tk
150       LEFT JOIN   tax t ON (t.id = tk.tax_id)
151       LEFT JOIN chart c ON (c.id = t.chart_id)
152
153       WHERE tk.chart_id = ?
154       ORDER BY startdate DESC
155     };
156     $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
157     $sth = $dbh->prepare($query);
158
159     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
160
161     $form->{ACCOUNT_TAXKEYS} = [];
162
163     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
164       push @{ $form->{ACCOUNT_TAXKEYS} }, $ref;
165     }
166
167     $sth->finish;
168
169   }
170   # check if we have any transactions
171   $query = qq|SELECT a.trans_id FROM acc_trans a
172               WHERE a.chart_id = ?|;
173   $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
174   $sth = $dbh->prepare($query);
175   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
176
177   ($form->{orphaned}) = $sth->fetchrow_array;
178   $form->{orphaned} = !$form->{orphaned};
179   $sth->finish;
180
181   # check if new account is active
182   $form->{new_chart_valid} = 0;
183   if ($form->{new_chart_id}) {
184     $query = qq|SELECT current_date-valid_from FROM chart
185                 WHERE id = ?|;
186     $main::lxdebug->message(LXDebug->QUERY(), "\$query=\n $query");
187     my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
188     if ($count >=0) {
189       $form->{new_chart_valid} = 1;
190     }
191     $sth->finish;
192   }
193
194   $dbh->disconnect;
195
196   $main::lxdebug->leave_sub();
197 }
198
199 sub save_account {
200   $main::lxdebug->enter_sub();
201
202   # TODO: it should be forbidden to change an account to a heading if there
203   # have been bookings to this account in the past
204
205   my ($self, $myconfig, $form) = @_;
206
207   # connect to database, turn off AutoCommit
208   my $dbh = $form->dbconnect_noauto($myconfig);
209
210   # sanity check, can't have AR with AR_...
211   if ($form->{AR} || $form->{AP} || $form->{IC}) {
212     map { delete $form->{$_} }
213       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 CT_tax);
214   }
215
216   $form->{link} = "";
217   foreach my $item ($form->{AR},            $form->{AR_amount},
218                     $form->{AR_tax},        $form->{AR_paid},
219                     $form->{AP},            $form->{AP_amount},
220                     $form->{AP_tax},        $form->{AP_paid},
221                     $form->{IC},            $form->{IC_sale},
222                     $form->{IC_cogs},       $form->{IC_taxpart},
223                     $form->{IC_income},     $form->{IC_expense},
224                     $form->{IC_taxservice}, $form->{CT_tax}
225     ) {
226     $form->{link} .= "${item}:" if ($item);
227   }
228   chop $form->{link};
229
230   # strip blanks from accno
231   map { $form->{$_} =~ s/ //g; } qw(accno);
232
233   my ($query, $sth);
234
235   if ($form->{id} eq "NULL") {
236     $form->{id} = "";
237   }
238
239   if (!$form->{id} || $form->{id} eq "") {
240     $query = qq|SELECT nextval('id')|;
241     ($form->{"id"}) = selectrow_query($form, $dbh, $query);
242     $query = qq|INSERT INTO chart (id, accno) VALUES (?, ?)|;
243     do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"});
244   }
245
246   my @values;
247
248
249   if ($form->{id}) {
250
251     # if charttype is heading make sure certain values are empty
252     # specifically, if charttype is changed from an existing account, empty the
253     # fields unnecessary for headings, so that e.g. heading doesn't appear in
254     # drop-down menues due to still having a valid "link" entry
255
256     if ( $form->{charttype} eq 'H' ) {
257       $form->{link} = '';
258       $form->{pos_bwa} = '';
259       $form->{pos_bilanz} = '';
260       $form->{pos_eur} = '';
261       $form->{new_chart_id} = '';
262       $form->{valid_from} = '';
263     };
264
265     $query = qq|UPDATE chart SET
266                   accno = ?,
267                   description = ?,
268                   charttype = ?,
269                   category = ?,
270                   link = ?,
271                   pos_bwa   = ?,
272                   pos_bilanz = ?,
273                   pos_eur = ?,
274                   new_chart_id = ?,
275                   valid_from = ?,
276                   datevautomatik = ?
277                 WHERE id = ?|;
278
279     @values = (
280                   $form->{accno},
281                   $form->{description},
282                   $form->{charttype},
283                   $form->{category},
284                   $form->{link},
285                   conv_i($form->{pos_bwa}),
286                   conv_i($form->{pos_bilanz}),
287                   conv_i($form->{pos_eur}),
288                   conv_i($form->{new_chart_id}),
289                   conv_date($form->{valid_from}),
290                   ($form->{datevautomatik} eq 'T') ? 'true':'false',
291                 $form->{id},
292     );
293
294
295   }
296
297   do_query($form, $dbh, $query, @values);
298
299   #Save Taxkeys
300
301   my @taxkeys = ();
302
303   my $MAX_TRIES = 10; # Maximum count of taxkeys in form
304   my $tk_count;
305
306   READTAXKEYS:
307   for $tk_count (0 .. $MAX_TRIES) {
308
309     # Loop control
310
311     # Check if the account already exists, else cancel
312
313     print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
314
315     last READTAXKEYS if ( $form->{'id'} == 0);
316
317     # check if there is a startdate
318     if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
319       $tk_count++;
320       next READTAXKEYS;
321     }
322
323     # Add valid taxkeys into the array
324     push @taxkeys ,
325       {
326         id        => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
327         tax_id    => conv_i($form->{"taxkey_tax_$tk_count"}),
328         startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
329         chart_id  => conv_i($form->{"id"}),
330         pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
331         delete    => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
332       };
333
334     $tk_count++;
335   }
336
337   TAXKEY:
338   for my $j (0 .. $#taxkeys){
339     if ( defined $taxkeys[$j]{'id'} ){
340       # delete Taxkey?
341
342       if ($taxkeys[$j]{'delete'}){
343         $query = qq{
344           DELETE FROM taxkeys WHERE id = ?
345         };
346
347         @values = ($taxkeys[$j]{'id'});
348
349         do_query($form, $dbh, $query, @values);
350
351         next TAXKEY;
352       }
353
354       # UPDATE Taxkey
355
356       $query = qq{
357         UPDATE taxkeys
358         SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
359             chart_id  = ?,
360             tax_id    = ?,
361             pos_ustva = ?,
362             startdate = ?
363         WHERE id = ?
364       };
365       @values = (
366         $taxkeys[$j]{'tax_id'},
367         $taxkeys[$j]{'chart_id'},
368         $taxkeys[$j]{'tax_id'},
369         $taxkeys[$j]{'pos_ustva'},
370         $taxkeys[$j]{'startdate'},
371         $taxkeys[$j]{'id'},
372       );
373       do_query($form, $dbh, $query, @values);
374     }
375     else {
376       # INSERT Taxkey
377
378       $query = qq{
379         INSERT INTO taxkeys (
380           taxkey_id,
381           chart_id,
382           tax_id,
383           pos_ustva,
384           startdate
385         )
386         VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
387       };
388       @values = (
389         $taxkeys[$j]{'tax_id'},
390         $taxkeys[$j]{'chart_id'},
391         $taxkeys[$j]{'tax_id'},
392         $taxkeys[$j]{'pos_ustva'},
393         $taxkeys[$j]{'startdate'},
394       );
395
396       do_query($form, $dbh, $query, @values);
397     }
398
399   }
400
401   # Update chart.taxkey_id to the latest from taxkeys for this chart.
402   $query = <<SQL;
403     UPDATE chart
404     SET taxkey_id = (
405       SELECT taxkey_id
406       FROM taxkeys
407       WHERE taxkeys.chart_id = chart.id
408       ORDER BY startdate DESC
409       LIMIT 1
410     )
411     WHERE id = ?
412 SQL
413
414   do_query($form, $dbh, $query, $form->{id});
415
416   # commit
417   my $rc = $dbh->commit;
418   $dbh->disconnect;
419
420   $main::lxdebug->leave_sub();
421
422   return $rc;
423 }
424
425 sub delete_account {
426   $main::lxdebug->enter_sub();
427
428   my ($self, $myconfig, $form) = @_;
429
430   # connect to database, turn off AutoCommit
431   my $dbh = $form->dbconnect_noauto($myconfig);
432
433   my $query = qq|SELECT count(*) FROM acc_trans a
434                  WHERE a.chart_id = ?|;
435   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
436
437   if ($count) {
438     $dbh->disconnect;
439     $main::lxdebug->leave_sub();
440     return;
441   }
442
443   # set inventory_accno_id, income_accno_id, expense_accno_id to defaults
444   foreach my $type (qw(inventory income expense)) {
445     $query =
446       qq|UPDATE parts | .
447       qq|SET ${type}_accno_id = (SELECT ${type}_accno_id FROM defaults) | .
448       qq|WHERE ${type}_accno_id = ?|;
449     do_query($form, $dbh, $query, $form->{id});
450   }
451
452   foreach my $table (qw(partstax customertax vendortax tax)) {
453     $query = qq|DELETE FROM $table
454                 WHERE chart_id = ?|;
455     do_query($form, $dbh, $query, $form->{id});
456   }
457
458   # delete chart of account record
459   $query = qq|DELETE FROM chart
460               WHERE id = ?|;
461   do_query($form, $dbh, $query, $form->{id});
462
463   # delete account taxkeys
464   $query = qq|DELETE FROM taxkeys
465               WHERE chart_id = ?|;
466   do_query($form, $dbh, $query, $form->{id});
467
468   # commit and redirect
469   my $rc = $dbh->commit;
470   $dbh->disconnect;
471
472   $main::lxdebug->leave_sub();
473
474   return $rc;
475 }
476
477 sub lead {
478   $main::lxdebug->enter_sub();
479
480   my ($self, $myconfig, $form) = @_;
481
482   # connect to database
483   my $dbh = $form->dbconnect($myconfig);
484
485   my $query = qq|SELECT id, lead
486                  FROM leads
487                  ORDER BY 2|;
488
489   my $sth = $dbh->prepare($query);
490   $sth->execute || $form->dberror($query);
491
492   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
493     push @{ $form->{ALL} }, $ref;
494   }
495
496   $sth->finish;
497   $dbh->disconnect;
498
499   $main::lxdebug->leave_sub();
500 }
501
502 sub get_lead {
503   $main::lxdebug->enter_sub();
504
505   my ($self, $myconfig, $form) = @_;
506
507   # connect to database
508   my $dbh = $form->dbconnect($myconfig);
509
510   my $query =
511     qq|SELECT l.id, l.lead | .
512     qq|FROM leads l | .
513     qq|WHERE l.id = ?|;
514   my $sth = $dbh->prepare($query);
515   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
516
517   my $ref = $sth->fetchrow_hashref("NAME_lc");
518
519   map { $form->{$_} = $ref->{$_} } keys %$ref;
520
521   $sth->finish;
522
523   $dbh->disconnect;
524
525   $main::lxdebug->leave_sub();
526 }
527
528 sub save_lead {
529   $main::lxdebug->enter_sub();
530
531   my ($self, $myconfig, $form) = @_;
532   my ($query);
533
534   # connect to database
535   my $dbh = $form->dbconnect($myconfig);
536
537   my @values = ($form->{description});
538   # id is the old record
539   if ($form->{id}) {
540     $query = qq|UPDATE leads SET
541                 lead = ?
542                 WHERE id = ?|;
543     puhs(@values, $form->{id});
544   } else {
545     $query = qq|INSERT INTO leads
546                 (lead)
547                 VALUES (?)|;
548   }
549   do_query($form, $dbh, $query, @values);
550
551   $dbh->disconnect;
552
553   $main::lxdebug->leave_sub();
554 }
555
556 sub delete_lead {
557   $main::lxdebug->enter_sub();
558
559   my ($self, $myconfig, $form) = @_;
560   my ($query);
561
562   # connect to database
563   my $dbh = $form->dbconnect($myconfig);
564
565   $query = qq|DELETE FROM leads
566               WHERE id = ?|;
567   do_query($form, $dbh, $query, $form->{id});
568
569   $dbh->disconnect;
570
571   $main::lxdebug->leave_sub();
572 }
573
574 sub language {
575   $main::lxdebug->enter_sub();
576
577   my ($self, $myconfig, $form, $return_list) = @_;
578
579   # connect to database
580   my $dbh = $form->dbconnect($myconfig);
581
582   my $query =
583     "SELECT id, description, template_code, article_code, " .
584     "  output_numberformat, output_dateformat, output_longdates " .
585     "FROM language ORDER BY description";
586
587   my $sth = $dbh->prepare($query);
588   $sth->execute || $form->dberror($query);
589
590   my $ary = [];
591
592   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
593     push(@{ $ary }, $ref);
594   }
595
596   $sth->finish;
597   $dbh->disconnect;
598
599   $main::lxdebug->leave_sub();
600
601   if ($return_list) {
602     return @{$ary};
603   } else {
604     $form->{ALL} = $ary;
605   }
606 }
607
608 sub get_language {
609   $main::lxdebug->enter_sub();
610
611   my ($self, $myconfig, $form) = @_;
612
613   # connect to database
614   my $dbh = $form->dbconnect($myconfig);
615
616   my $query =
617     "SELECT description, template_code, article_code, " .
618     "  output_numberformat, output_dateformat, output_longdates " .
619     "FROM language WHERE id = ?";
620   my $sth = $dbh->prepare($query);
621   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
622
623   my $ref = $sth->fetchrow_hashref("NAME_lc");
624
625   map { $form->{$_} = $ref->{$_} } keys %$ref;
626
627   $sth->finish;
628
629   $dbh->disconnect;
630
631   $main::lxdebug->leave_sub();
632 }
633
634 sub get_language_details {
635   $main::lxdebug->enter_sub();
636
637   my ($self, $myconfig, $form, $id) = @_;
638
639   # connect to database
640   my $dbh = $form->dbconnect($myconfig);
641
642   my $query =
643     "SELECT template_code, " .
644     "  output_numberformat, output_dateformat, output_longdates " .
645     "FROM language WHERE id = ?";
646   my @res = selectrow_query($form, $dbh, $query, $id);
647   $dbh->disconnect;
648
649   $main::lxdebug->leave_sub();
650
651   return @res;
652 }
653
654 sub save_language {
655   $main::lxdebug->enter_sub();
656
657   my ($self, $myconfig, $form) = @_;
658
659   # connect to database
660   my $dbh = $form->dbconnect($myconfig);
661   my (@values, $query);
662
663   map({ push(@values, $form->{$_}); }
664       qw(description template_code article_code
665          output_numberformat output_dateformat output_longdates));
666
667   # id is the old record
668   if ($form->{id}) {
669     $query =
670       "UPDATE language SET " .
671       "  description = ?, template_code = ?, article_code = ?, " .
672       "  output_numberformat = ?, output_dateformat = ?, " .
673       "  output_longdates = ? " .
674       "WHERE id = ?";
675     push(@values, $form->{id});
676   } else {
677     $query =
678       "INSERT INTO language (" .
679       "  description, template_code, article_code, " .
680       "  output_numberformat, output_dateformat, output_longdates" .
681       ") VALUES (?, ?, ?, ?, ?, ?)";
682   }
683   do_query($form, $dbh, $query, @values);
684
685   $dbh->disconnect;
686
687   $main::lxdebug->leave_sub();
688 }
689
690 sub delete_language {
691   $main::lxdebug->enter_sub();
692
693   my ($self, $myconfig, $form) = @_;
694   my $query;
695
696   # connect to database
697   my $dbh = $form->dbconnect_noauto($myconfig);
698
699   foreach my $table (qw(generic_translations units_language)) {
700     $query = qq|DELETE FROM $table WHERE language_id = ?|;
701     do_query($form, $dbh, $query, $form->{"id"});
702   }
703
704   $query = "DELETE FROM language WHERE id = ?";
705   do_query($form, $dbh, $query, $form->{"id"});
706
707   $dbh->commit();
708   $dbh->disconnect;
709
710   $main::lxdebug->leave_sub();
711 }
712
713
714 sub buchungsgruppe {
715   $main::lxdebug->enter_sub();
716
717   my ($self, $myconfig, $form) = @_;
718
719   # connect to database
720   my $dbh = $form->dbconnect($myconfig);
721
722   my $query = qq|SELECT id, description,
723                  inventory_accno_id,
724                  (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
725                  income_accno_id_0,
726                  (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
727                  expense_accno_id_0,
728                  (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
729                  income_accno_id_1,
730                  (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
731                  expense_accno_id_1,
732                  (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
733                  income_accno_id_2,
734                  (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
735                  expense_accno_id_2,
736                  (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
737                  income_accno_id_3,
738                  (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
739                  expense_accno_id_3,
740                  (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
741                  FROM buchungsgruppen
742                  ORDER BY sortkey|;
743
744   my $sth = $dbh->prepare($query);
745   $sth->execute || $form->dberror($query);
746
747   $form->{ALL} = [];
748   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
749     push @{ $form->{ALL} }, $ref;
750   }
751
752   $sth->finish;
753   $dbh->disconnect;
754
755   $main::lxdebug->leave_sub();
756 }
757
758 sub get_buchungsgruppe {
759   $main::lxdebug->enter_sub();
760
761   my ($self, $myconfig, $form) = @_;
762   my $query;
763
764   # connect to database
765   my $dbh = $form->dbconnect($myconfig);
766
767   if ($form->{id}) {
768     $query =
769       qq|SELECT description, inventory_accno_id,
770          (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
771          income_accno_id_0,
772          (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
773          expense_accno_id_0,
774          (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
775          income_accno_id_1,
776          (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
777          expense_accno_id_1,
778          (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
779          income_accno_id_2,
780          (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
781          expense_accno_id_2,
782          (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
783          income_accno_id_3,
784          (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
785          expense_accno_id_3,
786          (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
787          FROM buchungsgruppen
788          WHERE id = ?|;
789     my $sth = $dbh->prepare($query);
790     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
791
792     my $ref = $sth->fetchrow_hashref("NAME_lc");
793
794     map { $form->{$_} = $ref->{$_} } keys %$ref;
795
796     $sth->finish;
797
798     $query =
799       qq|SELECT count(id) = 0 AS orphaned
800          FROM parts
801          WHERE buchungsgruppen_id = ?|;
802     ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
803   }
804
805   $query = "SELECT inventory_accno_id, income_accno_id, expense_accno_id ".
806     "FROM defaults";
807   ($form->{"std_inventory_accno_id"}, $form->{"std_income_accno_id"},
808    $form->{"std_expense_accno_id"}) = selectrow_query($form, $dbh, $query);
809
810   my $module = "IC";
811   $query = qq|SELECT c.accno, c.description, c.link, c.id,
812               d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
813               FROM chart c, defaults d
814               WHERE c.link LIKE '%$module%'
815               ORDER BY c.accno|;
816
817
818   my $sth = $dbh->prepare($query);
819   $sth->execute || $form->dberror($query);
820   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
821     foreach my $key (split(/:/, $ref->{link})) {
822       if (!$form->{"std_inventory_accno_id"} && ($key eq "IC")) {
823         $form->{"std_inventory_accno_id"} = $ref->{"id"};
824       }
825       if ($key =~ /$module/) {
826         if (   ($ref->{id} eq $ref->{inventory_accno_id})
827             || ($ref->{id} eq $ref->{income_accno_id})
828             || ($ref->{id} eq $ref->{expense_accno_id})) {
829           push @{ $form->{"${module}_links"}{$key} },
830             { accno       => $ref->{accno},
831               description => $ref->{description},
832               selected    => "selected",
833               id          => $ref->{id} };
834         } else {
835           push @{ $form->{"${module}_links"}{$key} },
836             { accno       => $ref->{accno},
837               description => $ref->{description},
838               selected    => "",
839               id          => $ref->{id} };
840         }
841       }
842     }
843   }
844   $sth->finish;
845
846
847   $dbh->disconnect;
848
849   $main::lxdebug->leave_sub();
850 }
851
852 sub save_buchungsgruppe {
853   $main::lxdebug->enter_sub();
854
855   my ($self, $myconfig, $form) = @_;
856
857   # connect to database
858   my $dbh = $form->dbconnect($myconfig);
859
860   my @values = ($form->{description}, $form->{inventory_accno_id},
861                 $form->{income_accno_id_0}, $form->{expense_accno_id_0},
862                 $form->{income_accno_id_1}, $form->{expense_accno_id_1},
863                 $form->{income_accno_id_2}, $form->{expense_accno_id_2},
864                 $form->{income_accno_id_3}, $form->{expense_accno_id_3});
865
866   my $query;
867
868   # id is the old record
869   if ($form->{id}) {
870     $query = qq|UPDATE buchungsgruppen SET
871                 description = ?, inventory_accno_id = ?,
872                 income_accno_id_0 = ?, expense_accno_id_0 = ?,
873                 income_accno_id_1 = ?, expense_accno_id_1 = ?,
874                 income_accno_id_2 = ?, expense_accno_id_2 = ?,
875                 income_accno_id_3 = ?, expense_accno_id_3 = ?
876                 WHERE id = ?|;
877     push(@values, $form->{id});
878   } else {
879     $query = qq|SELECT COALESCE(MAX(sortkey) + 1, 1) FROM buchungsgruppen|;
880     my ($sortkey) = $dbh->selectrow_array($query);
881     $form->dberror($query) if ($dbh->err);
882     push(@values, $sortkey);
883     $query = qq|INSERT INTO buchungsgruppen
884                 (description, inventory_accno_id,
885                 income_accno_id_0, expense_accno_id_0,
886                 income_accno_id_1, expense_accno_id_1,
887                 income_accno_id_2, expense_accno_id_2,
888                 income_accno_id_3, expense_accno_id_3,
889                 sortkey)
890                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
891   }
892   do_query($form, $dbh, $query, @values);
893
894   $dbh->disconnect;
895
896   $main::lxdebug->leave_sub();
897 }
898
899 sub delete_buchungsgruppe {
900   $main::lxdebug->enter_sub();
901
902   my ($self, $myconfig, $form) = @_;
903
904   # connect to database
905   my $dbh = $form->dbconnect($myconfig);
906
907   my $query = qq|DELETE FROM buchungsgruppen WHERE id = ?|;
908   do_query($form, $dbh, $query, $form->{id});
909
910   $dbh->disconnect;
911
912   $main::lxdebug->leave_sub();
913 }
914
915 sub swap_sortkeys {
916   $main::lxdebug->enter_sub();
917
918   my ($self, $myconfig, $form, $table) = @_;
919
920   # connect to database
921   my $dbh = $form->get_standard_dbh($myconfig);
922
923   my $query =
924     qq|SELECT
925        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey1,
926        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey2|;
927   my @values   = ($form->{"id1"}, $form->{"id2"});
928   my @sortkeys = selectrow_query($form, $dbh, $query, @values);
929
930   $query  = qq|UPDATE $table SET sortkey = ? WHERE id = ?|;
931   my $sth = prepare_query($form, $dbh, $query);
932
933   do_statement($form, $sth, $query, $sortkeys[1], $form->{"id1"});
934   do_statement($form, $sth, $query, $sortkeys[0], $form->{"id2"});
935
936   $sth->finish();
937
938   $dbh->commit();
939
940   $main::lxdebug->leave_sub();
941 }
942
943 sub prepare_template_filename {
944   $main::lxdebug->enter_sub();
945
946   my ($self, $myconfig, $form) = @_;
947
948   my ($filename, $display_filename);
949
950   if ($form->{type} eq "stylesheet") {
951     $filename = "css/$myconfig->{stylesheet}";
952     $display_filename = $myconfig->{stylesheet};
953
954   } else {
955     $filename = $form->{formname};
956
957     if ($form->{language}) {
958       my ($id, $template_code) = split(/--/, $form->{language});
959       $filename .= "_${template_code}";
960     }
961
962     if ($form->{printer}) {
963       my ($id, $template_code) = split(/--/, $form->{printer});
964       $filename .= "_${template_code}";
965     }
966
967     $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
968     $filename =~ s|.*/||;
969     $display_filename = $filename;
970     $filename = "$myconfig->{templates}/$filename";
971   }
972
973   $main::lxdebug->leave_sub();
974
975   return ($filename, $display_filename);
976 }
977
978
979 sub load_template {
980   $main::lxdebug->enter_sub();
981
982   my ($self, $filename) = @_;
983
984   my ($content, $lines) = ("", 0);
985
986   local *TEMPLATE;
987
988   if (open(TEMPLATE, $filename)) {
989     while (<TEMPLATE>) {
990       $content .= $_;
991       $lines++;
992     }
993     close(TEMPLATE);
994   }
995
996   $content = Encode::decode('utf-8-strict', $content) if $::locale->is_utf8;
997
998   $main::lxdebug->leave_sub();
999
1000   return ($content, $lines);
1001 }
1002
1003 sub save_template {
1004   $main::lxdebug->enter_sub();
1005
1006   my ($self, $filename, $content) = @_;
1007
1008   local *TEMPLATE;
1009
1010   my $error = "";
1011
1012   if (open(TEMPLATE, ">", $filename)) {
1013     $content = Encode::encode('utf-8-strict', $content) if $::locale->is_utf8;
1014     $content =~ s/\r\n/\n/g;
1015     print(TEMPLATE $content);
1016     close(TEMPLATE);
1017   } else {
1018     $error = $!;
1019   }
1020
1021   $main::lxdebug->leave_sub();
1022
1023   return $error;
1024 }
1025
1026 sub save_defaults {
1027   $main::lxdebug->enter_sub();
1028
1029   my $self     = shift;
1030   my %params   = @_;
1031
1032   my $myconfig = \%main::myconfig;
1033   my $form     = $main::form;
1034
1035   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1036
1037   my %accnos;
1038   map { ($accnos{$_}) = split(m/--/, $form->{$_}) } qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno ar_paid_accno);
1039
1040   $form->{curr}  =~ s/ //g;
1041   my @currencies =  grep { $_ ne '' } split m/:/, $form->{curr};
1042   my $currency   =  join ':', @currencies;
1043
1044   # these defaults are database wide
1045
1046   my $query =
1047     qq|UPDATE defaults SET
1048         inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?),
1049         income_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1050         expense_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1051         fxgain_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1052         fxloss_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1053         ar_paid_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1054         invnumber          = ?,
1055         cnnumber           = ?,
1056         sonumber           = ?,
1057         ponumber           = ?,
1058         sqnumber           = ?,
1059         rfqnumber          = ?,
1060         customernumber     = ?,
1061         vendornumber       = ?,
1062         articlenumber      = ?,
1063         servicenumber      = ?,
1064         sdonumber          = ?,
1065         pdonumber          = ?,
1066         curr               = ?,
1067         businessnumber     = ?,
1068         weightunit         = ?,
1069         language_id        = ?|;
1070   my @values = ($accnos{inventory_accno}, $accnos{income_accno}, $accnos{expense_accno},
1071                 $accnos{fxgain_accno},    $accnos{fxloss_accno}, $accnos{ar_paid_accno},
1072                 $form->{invnumber},       $form->{cnnumber},
1073                 $form->{sonumber},        $form->{ponumber},
1074                 $form->{sqnumber},        $form->{rfqnumber},
1075                 $form->{customernumber},  $form->{vendornumber},
1076                 $form->{articlenumber},   $form->{servicenumber},
1077                 $form->{sdonumber},       $form->{pdonumber},
1078                 $currency,
1079                 $form->{businessnumber},  $form->{weightunit},
1080                 conv_i($form->{language_id}));
1081   do_query($form, $dbh, $query, @values);
1082
1083   $dbh->commit();
1084
1085   $main::lxdebug->leave_sub();
1086 }
1087
1088
1089 sub save_preferences {
1090   $main::lxdebug->enter_sub();
1091
1092   my ($self, $myconfig, $form) = @_;
1093
1094   my $dbh = $form->get_standard_dbh($myconfig);
1095
1096   my ($currency, $businessnumber) = selectrow_query($form, $dbh, qq|SELECT curr, businessnumber FROM defaults|);
1097
1098   # update name
1099   my $query = qq|UPDATE employee SET name = ? WHERE login = ?|;
1100   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1101
1102   my $rc = $dbh->commit();
1103
1104   # save first currency in myconfig
1105   $currency               =~ s/:.*//;
1106   $form->{currency}       =  $currency;
1107
1108   $form->{businessnumber} =  $businessnumber;
1109
1110   $myconfig = new User($form->{login});
1111
1112   foreach my $item (keys %$form) {
1113     $myconfig->{$item} = $form->{$item};
1114   }
1115
1116   $myconfig->save_member;
1117
1118   my $auth = $main::auth;
1119
1120   $main::lxdebug->leave_sub();
1121
1122   return $rc;
1123 }
1124
1125 sub get_defaults {
1126   $main::lxdebug->enter_sub();
1127
1128   my $self     = shift;
1129   my %params   = @_;
1130
1131   my $myconfig = \%main::myconfig;
1132   my $form     = $main::form;
1133
1134   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1135
1136   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
1137
1138   $defaults->{weightunit} ||= 'kg';
1139
1140   $main::lxdebug->leave_sub();
1141
1142   return $defaults;
1143 }
1144
1145 sub defaultaccounts {
1146   $main::lxdebug->enter_sub();
1147
1148   my ($self, $myconfig, $form) = @_;
1149
1150   # connect to database
1151   my $dbh = $form->dbconnect($myconfig);
1152
1153   # get defaults from defaults table
1154   my $query = qq|SELECT * FROM defaults|;
1155   my $sth   = $dbh->prepare($query);
1156   $sth->execute || $form->dberror($query);
1157
1158   $form->{defaults}               = $sth->fetchrow_hashref("NAME_lc");
1159   $form->{defaults}{IC}           = $form->{defaults}{inventory_accno_id};
1160   $form->{defaults}{IC_income}    = $form->{defaults}{income_accno_id};
1161   $form->{defaults}{IC_expense}   = $form->{defaults}{expense_accno_id};
1162   $form->{defaults}{FX_gain}      = $form->{defaults}{fxgain_accno_id};
1163   $form->{defaults}{FX_loss}      = $form->{defaults}{fxloss_accno_id};
1164   $form->{defaults}{AR_paid}      = $form->{defaults}{ar_paid_accno_id};
1165
1166   $form->{defaults}{weightunit} ||= 'kg';
1167
1168   $sth->finish;
1169
1170   $query = qq|SELECT c.id, c.accno, c.description, c.link
1171               FROM chart c
1172               WHERE c.link LIKE '%IC%'
1173               ORDER BY c.accno|;
1174   $sth = $dbh->prepare($query);
1175   $sth->execute || $self->dberror($query);
1176
1177   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1178     foreach my $key (split(/:/, $ref->{link})) {
1179       if ($key =~ /IC/) {
1180         my $nkey = $key;
1181         if ($key =~ /cogs/) {
1182           $nkey = "IC_expense";
1183         }
1184         if ($key =~ /sale/) {
1185           $nkey = "IC_income";
1186         }
1187         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1188                                              id          => $ref->{id},
1189                                              description => $ref->{description}
1190         );
1191       }
1192     }
1193   }
1194   $sth->finish;
1195
1196   $query = qq|SELECT c.id, c.accno, c.description
1197               FROM chart c
1198               WHERE c.category = 'I'
1199               AND c.charttype = 'A'
1200               ORDER BY c.accno|;
1201   $sth = $dbh->prepare($query);
1202   $sth->execute || $self->dberror($query);
1203
1204   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1205     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1206                                              id          => $ref->{id},
1207                                              description => $ref->{description}
1208     );
1209   }
1210   $sth->finish;
1211
1212   $query = qq|SELECT c.id, c.accno, c.description
1213               FROM chart c
1214               WHERE c.category = 'E'
1215               AND c.charttype = 'A'
1216               ORDER BY c.accno|;
1217   $sth = $dbh->prepare($query);
1218   $sth->execute || $self->dberror($query);
1219
1220   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1221     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1222                                              id          => $ref->{id},
1223                                              description => $ref->{description}
1224     );
1225   }
1226   $sth->finish;
1227
1228   # now get the tax rates and numbers
1229   $query = qq|SELECT c.id, c.accno, c.description,
1230               t.rate * 100 AS rate, t.taxnumber
1231               FROM chart c, tax t
1232               WHERE c.id = t.chart_id|;
1233
1234   $sth = $dbh->prepare($query);
1235   $sth->execute || $form->dberror($query);
1236
1237   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1238     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1239     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1240     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1241       if $ref->{taxnumber};
1242     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1243   }
1244   # Abfrage für Standard Umlaufvermögenskonto
1245   $query =
1246     qq|SELECT id, accno, description, link | .
1247     qq|FROM chart | .
1248     qq|WHERE link LIKE ? |.
1249     qq|ORDER BY accno|;
1250   $sth = prepare_execute_query($form, $dbh, $query, '%AR%');
1251   $sth->execute || $form->dberror($query);#
1252   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1253     foreach my $item (split(/:/, $ref->{link})) {
1254       if ($item eq "AR_paid") {
1255         %{ $form->{IC}{AR_paid}{ $ref->{accno} } } = (
1256                                              id          => $ref->{id},
1257                                              description => $ref->{description}
1258           );
1259       }
1260     }
1261   }
1262
1263   $sth->finish;
1264   $dbh->disconnect;
1265
1266   $main::lxdebug->leave_sub();
1267 }
1268
1269 sub closedto {
1270   $main::lxdebug->enter_sub();
1271
1272   my ($self, $myconfig, $form) = @_;
1273
1274   my $dbh = $form->dbconnect($myconfig);
1275
1276   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1277   my $sth   = $dbh->prepare($query);
1278   $sth->execute || $form->dberror($query);
1279
1280   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1281
1282   $sth->finish;
1283
1284   $dbh->disconnect;
1285
1286   $main::lxdebug->leave_sub();
1287 }
1288
1289 sub closebooks {
1290   $main::lxdebug->enter_sub();
1291
1292   my ($self, $myconfig, $form) = @_;
1293
1294   my $dbh = $form->dbconnect($myconfig);
1295
1296   my ($query, @values);
1297
1298   if ($form->{revtrans}) {
1299     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1300
1301   } elsif ($form->{closedto}) {
1302     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1303     @values = (conv_date($form->{closedto}));
1304
1305   } else {
1306     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1307   }
1308
1309   # set close in defaults
1310   do_query($form, $dbh, $query, @values);
1311
1312   $dbh->disconnect;
1313
1314   $main::lxdebug->leave_sub();
1315 }
1316
1317 sub get_base_unit {
1318   my ($self, $units, $unit_name, $factor) = @_;
1319
1320   $factor = 1 unless ($factor);
1321
1322   my $unit = $units->{$unit_name};
1323
1324   if (!defined($unit) || !$unit->{"base_unit"} ||
1325       ($unit_name eq $unit->{"base_unit"})) {
1326     return ($unit_name, $factor);
1327   }
1328
1329   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1330 }
1331
1332 sub retrieve_units {
1333   $main::lxdebug->enter_sub();
1334
1335   my ($self, $myconfig, $form, $prefix) = @_;
1336   $prefix ||= '';
1337
1338   my $dbh = $form->get_standard_dbh;
1339
1340   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1341
1342   my $sth = prepare_execute_query($form, $dbh, $query);
1343
1344   my $units = {};
1345   while (my $ref = $sth->fetchrow_hashref()) {
1346     $units->{$ref->{"name"}} = $ref;
1347   }
1348   $sth->finish();
1349
1350   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1351   $sth = $dbh->prepare($query_lang);
1352   $sth->execute() || $form->dberror($query_lang);
1353   my @languages;
1354   while (my $ref = $sth->fetchrow_hashref()) {
1355     push(@languages, $ref);
1356   }
1357   $sth->finish();
1358
1359   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1360     "FROM units_language ul " .
1361     "LEFT JOIN language l ON ul.language_id = l.id " .
1362     "WHERE ul.unit = ?";
1363   $sth = $dbh->prepare($query_lang);
1364
1365   foreach my $unit (values(%{$units})) {
1366     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1367
1368     $unit->{"LANGUAGES"} = {};
1369     foreach my $lang (@languages) {
1370       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1371     }
1372
1373     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1374     while (my $ref = $sth->fetchrow_hashref()) {
1375       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1376     }
1377   }
1378   $sth->finish;
1379
1380   $main::lxdebug->leave_sub();
1381
1382   return $units;
1383 }
1384
1385 sub retrieve_all_units {
1386   $main::lxdebug->enter_sub();
1387
1388   my $self = shift;
1389
1390   if (!$::request->{cache}{all_units}) {
1391     $::request->{cache}{all_units} = $self->retrieve_units(\%main::myconfig, $main::form);
1392   }
1393
1394   $main::lxdebug->leave_sub();
1395
1396   return $::request->{cache}{all_units};
1397 }
1398
1399
1400 sub translate_units {
1401   $main::lxdebug->enter_sub();
1402
1403   my ($self, $form, $template_code, $unit, $amount) = @_;
1404
1405   my $units = $self->retrieve_units(\%main::myconfig, $form);
1406
1407   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1408   my $new_unit = $unit;
1409   if ($h) {
1410     if (($amount != 1) && $h->{"localized_plural"}) {
1411       $new_unit = $h->{"localized_plural"};
1412     } elsif ($h->{"localized"}) {
1413       $new_unit = $h->{"localized"};
1414     }
1415   }
1416
1417   $main::lxdebug->leave_sub();
1418
1419   return $new_unit;
1420 }
1421
1422 sub units_in_use {
1423   $main::lxdebug->enter_sub();
1424
1425   my ($self, $myconfig, $form, $units) = @_;
1426
1427   my $dbh = $form->dbconnect($myconfig);
1428
1429   map({ $_->{"in_use"} = 0; } values(%{$units}));
1430
1431   foreach my $unit (values(%{$units})) {
1432     my $base_unit = $unit->{"original_base_unit"};
1433     while ($base_unit) {
1434       $units->{$base_unit}->{"in_use"} = 1;
1435       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1436       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1437       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1438     }
1439   }
1440
1441   foreach my $unit (values(%{$units})) {
1442     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1443
1444     foreach my $table (qw(parts invoice orderitems)) {
1445       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1446
1447       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1448         $query .= "= " . $dbh->quote($unit->{"name"});
1449       } else {
1450         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1451           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1452       }
1453
1454       my ($count) = $dbh->selectrow_array($query);
1455       $form->dberror($query) if ($dbh->err);
1456
1457       if ($count) {
1458         $unit->{"in_use"} = 1;
1459         last;
1460       }
1461     }
1462   }
1463
1464   $dbh->disconnect();
1465
1466   $main::lxdebug->leave_sub();
1467 }
1468
1469 sub convertible_units {
1470   $main::lxdebug->enter_sub();
1471
1472   my $self        = shift;
1473   my $units       = shift;
1474   my $filter_unit = shift;
1475   my $not_smaller = shift;
1476
1477   my $conv_units = [];
1478
1479   $filter_unit = $units->{$filter_unit};
1480
1481   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1482     my $unit = $units->{$name};
1483
1484     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1485         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1486       push @{$conv_units}, $unit;
1487     }
1488   }
1489
1490   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1491
1492   $main::lxdebug->leave_sub();
1493
1494   return \@sorted;
1495 }
1496
1497 # if $a is translatable to $b, return the factor between them.
1498 # else return 1
1499 sub convert_unit {
1500   $main::lxdebug->enter_sub(2);
1501   my ($this, $a, $b, $all_units) = @_;
1502
1503   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1504   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1505   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1506   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1507 }
1508
1509 sub unit_select_data {
1510   $main::lxdebug->enter_sub();
1511
1512   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1513
1514   my $select = [];
1515
1516   if ($empty_entry) {
1517     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1518   }
1519
1520   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1521     if (!$convertible_into ||
1522         ($units->{$convertible_into} &&
1523          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1524       push @{$select}, { "name"      => $unit,
1525                          "base_unit" => $units->{$unit}->{"base_unit"},
1526                          "factor"    => $units->{$unit}->{"factor"},
1527                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1528     }
1529   }
1530
1531   $main::lxdebug->leave_sub();
1532
1533   return $select;
1534 }
1535
1536 sub unit_select_html {
1537   $main::lxdebug->enter_sub();
1538
1539   my ($self, $units, $name, $selected, $convertible_into) = @_;
1540
1541   my $select = "<select name=${name}>";
1542
1543   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1544     if (!$convertible_into ||
1545         ($units->{$convertible_into} &&
1546          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1547       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1548     }
1549   }
1550   $select .= "</select>";
1551
1552   $main::lxdebug->leave_sub();
1553
1554   return $select;
1555 }
1556
1557 sub sum_with_unit {
1558   $main::lxdebug->enter_sub();
1559
1560   my $self  = shift;
1561
1562   my $units = $self->retrieve_all_units();
1563
1564   my $sum   = 0;
1565   my $base_unit;
1566
1567   while (2 <= scalar(@_)) {
1568     my $qty  = shift(@_);
1569     my $unit = $units->{shift(@_)};
1570
1571     croak "No unit defined with name $unit" if (!defined $unit);
1572
1573     if (!$base_unit) {
1574       $base_unit = $unit->{base_unit};
1575     } elsif ($base_unit ne $unit->{base_unit}) {
1576       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1577     }
1578
1579     $sum += $qty * $unit->{factor};
1580   }
1581
1582   $main::lxdebug->leave_sub();
1583
1584   return wantarray ? ($sum, $base_unit) : $sum;
1585 }
1586
1587 sub add_unit {
1588   $main::lxdebug->enter_sub();
1589
1590   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1591
1592   my $dbh = $form->dbconnect_noauto($myconfig);
1593
1594   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1595   my ($sortkey) = selectrow_query($form, $dbh, $query);
1596
1597   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1598     "VALUES (?, ?, ?, ?)";
1599   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1600
1601   if ($languages) {
1602     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1603     my $sth = $dbh->prepare($query);
1604     foreach my $lang (@{$languages}) {
1605       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1606       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1607     }
1608     $sth->finish();
1609   }
1610
1611   $dbh->commit();
1612   $dbh->disconnect();
1613
1614   $main::lxdebug->leave_sub();
1615 }
1616
1617 sub save_units {
1618   $main::lxdebug->enter_sub();
1619
1620   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1621
1622   my $dbh = $form->dbconnect_noauto($myconfig);
1623
1624   my ($base_unit, $unit, $sth, $query);
1625
1626   $query = "DELETE FROM units_language";
1627   $dbh->do($query) || $form->dberror($query);
1628
1629   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1630     $query = "DELETE FROM units WHERE name IN (";
1631     map({ $query .= "?," } @{$delete_units});
1632     substr($query, -1, 1) = ")";
1633     $dbh->do($query, undef, @{$delete_units}) ||
1634       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1635   }
1636
1637   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1638   $sth = $dbh->prepare($query);
1639
1640   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1641   my $sth_lang = $dbh->prepare($query_lang);
1642
1643   foreach $unit (values(%{$units})) {
1644     $unit->{"depth"} = 0;
1645     my $base_unit = $unit;
1646     while ($base_unit->{"base_unit"}) {
1647       $unit->{"depth"}++;
1648       $base_unit = $units->{$base_unit->{"base_unit"}};
1649     }
1650   }
1651
1652   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1653     if ($unit->{"LANGUAGES"}) {
1654       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1655         next unless ($lang->{"id"} && $lang->{"localized"});
1656         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1657         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1658       }
1659     }
1660
1661     next if ($unit->{"unchanged_unit"});
1662
1663     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1664     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1665   }
1666
1667   $sth->finish();
1668   $sth_lang->finish();
1669   $dbh->commit();
1670   $dbh->disconnect();
1671
1672   $main::lxdebug->leave_sub();
1673 }
1674
1675 sub taxes {
1676   $main::lxdebug->enter_sub();
1677
1678   my ($self, $myconfig, $form) = @_;
1679
1680   # connect to database
1681   my $dbh = $form->dbconnect($myconfig);
1682
1683   my $query = qq|SELECT
1684                    t.id,
1685                    t.taxkey,
1686                    t.taxdescription,
1687                    round(t.rate * 100, 2) AS rate,
1688                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
1689                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
1690                  FROM tax t
1691                  ORDER BY taxkey|;
1692
1693   my $sth = $dbh->prepare($query);
1694   $sth->execute || $form->dberror($query);
1695
1696   $form->{TAX} = [];
1697   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1698     push @{ $form->{TAX} }, $ref;
1699   }
1700
1701   $sth->finish;
1702   $dbh->disconnect;
1703
1704   $main::lxdebug->leave_sub();
1705 }
1706
1707 sub get_tax_accounts {
1708   $main::lxdebug->enter_sub();
1709
1710   my ($self, $myconfig, $form) = @_;
1711
1712   my $dbh = $form->dbconnect($myconfig);
1713
1714   # get Accounts from chart
1715   my $query = qq{ SELECT
1716                  id,
1717                  accno || ' - ' || description AS taxaccount
1718                FROM chart
1719                WHERE link LIKE '%_tax%'
1720                ORDER BY accno
1721              };
1722
1723   my $sth = $dbh->prepare($query);
1724   $sth->execute || $form->dberror($query);
1725
1726   $form->{ACCOUNTS} = [];
1727   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1728     push @{ $form->{ACCOUNTS} }, $ref;
1729   }
1730
1731   $sth->finish;
1732
1733   $dbh->disconnect;
1734
1735   $main::lxdebug->leave_sub();
1736 }
1737
1738 sub get_tax {
1739   $main::lxdebug->enter_sub();
1740
1741   my ($self, $myconfig, $form) = @_;
1742
1743   # connect to database
1744   my $dbh = $form->dbconnect($myconfig);
1745
1746   my $query = qq|SELECT
1747                    taxkey,
1748                    taxdescription,
1749                    round(rate * 100, 2) AS rate,
1750                    chart_id
1751                  FROM tax
1752                  WHERE id = ? |;
1753
1754   my $sth = $dbh->prepare($query);
1755   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1756
1757   my $ref = $sth->fetchrow_hashref("NAME_lc");
1758
1759   map { $form->{$_} = $ref->{$_} } keys %$ref;
1760
1761   $sth->finish;
1762
1763   # see if it is used by a taxkey
1764   $query = qq|SELECT count(*) FROM taxkeys
1765               WHERE tax_id = ? AND chart_id >0|;
1766
1767   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
1768
1769   $form->{orphaned} = !$form->{orphaned};
1770   $sth->finish;
1771
1772   if (!$form->{orphaned} ) {
1773     $query = qq|SELECT DISTINCT c.id, c.accno
1774                 FROM taxkeys tk
1775                 JOIN   tax t ON (t.id = tk.tax_id)
1776                 JOIN chart c ON (c.id = tk.chart_id)
1777                 WHERE tk.tax_id = ?|;
1778
1779     $sth = $dbh->prepare($query);
1780     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
1781
1782     $form->{TAXINUSE} = [];
1783     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1784       push @{ $form->{TAXINUSE} }, $ref;
1785     }
1786
1787     $sth->finish;
1788   }
1789
1790   $dbh->disconnect;
1791
1792   $main::lxdebug->leave_sub();
1793 }
1794
1795 sub save_tax {
1796   $main::lxdebug->enter_sub();
1797
1798   my ($self, $myconfig, $form) = @_;
1799   my $query;
1800
1801   # connect to database
1802   my $dbh = $form->get_standard_dbh($myconfig);
1803
1804   $form->{rate} = $form->{rate} / 100;
1805
1806   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
1807   if ($form->{id} ne "") {
1808     $query = qq|UPDATE tax SET
1809                   taxkey         = ?,
1810                   taxdescription = ?,
1811                   rate           = ?,
1812                   chart_id       = ?,
1813                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
1814                 WHERE id = ?|;
1815     push(@values, $form->{id});
1816
1817   } else {
1818     #ok
1819     $query = qq|INSERT INTO tax (
1820                   taxkey,
1821                   taxdescription,
1822                   rate,
1823                   chart_id,
1824                   taxnumber
1825                 )
1826                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
1827   }
1828   do_query($form, $dbh, $query, @values);
1829
1830   $dbh->commit();
1831
1832   $main::lxdebug->leave_sub();
1833 }
1834
1835 sub delete_tax {
1836   $main::lxdebug->enter_sub();
1837
1838   my ($self, $myconfig, $form) = @_;
1839   my $query;
1840
1841   # connect to database
1842   my $dbh = $form->get_standard_dbh($myconfig);
1843
1844   $query = qq|DELETE FROM tax
1845               WHERE id = ?|;
1846   do_query($form, $dbh, $query, $form->{id});
1847
1848   $dbh->commit();
1849
1850   $main::lxdebug->leave_sub();
1851 }
1852
1853 sub save_price_factor {
1854   $main::lxdebug->enter_sub();
1855
1856   my ($self, $myconfig, $form) = @_;
1857
1858   # connect to database
1859   my $dbh = $form->get_standard_dbh($myconfig);
1860
1861   my $query;
1862   my @values = ($form->{description}, conv_i($form->{factor}));
1863
1864   if ($form->{id}) {
1865     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
1866     push @values, conv_i($form->{id});
1867
1868   } else {
1869     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
1870   }
1871
1872   do_query($form, $dbh, $query, @values);
1873
1874   $dbh->commit();
1875
1876   $main::lxdebug->leave_sub();
1877 }
1878
1879 sub get_all_price_factors {
1880   $main::lxdebug->enter_sub();
1881
1882   my ($self, $myconfig, $form) = @_;
1883
1884   # connect to database
1885   my $dbh = $form->get_standard_dbh($myconfig);
1886
1887   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
1888
1889   $main::lxdebug->leave_sub();
1890 }
1891
1892 sub get_price_factor {
1893   $main::lxdebug->enter_sub();
1894
1895   my ($self, $myconfig, $form) = @_;
1896
1897   # connect to database
1898   my $dbh = $form->get_standard_dbh($myconfig);
1899
1900   my $query = qq|SELECT description, factor,
1901                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
1902                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
1903                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
1904                  FROM price_factors WHERE id = ?|;
1905
1906   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
1907
1908   $main::lxdebug->leave_sub();
1909 }
1910
1911 sub delete_price_factor {
1912   $main::lxdebug->enter_sub();
1913
1914   my ($self, $myconfig, $form) = @_;
1915
1916   # connect to database
1917   my $dbh = $form->get_standard_dbh($myconfig);
1918
1919   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
1920   $dbh->commit();
1921
1922   $main::lxdebug->leave_sub();
1923 }
1924
1925 sub save_warehouse {
1926   $main::lxdebug->enter_sub();
1927
1928   my ($self, $myconfig, $form) = @_;
1929
1930   # connect to database
1931   my $dbh = $form->get_standard_dbh($myconfig);
1932
1933   my ($query, @values, $sth);
1934
1935   if (!$form->{id}) {
1936     $query        = qq|SELECT nextval('id')|;
1937     ($form->{id}) = selectrow_query($form, $dbh, $query);
1938
1939     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
1940     do_query($form, $dbh, $query, $form->{id});
1941   }
1942
1943   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
1944            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
1945
1946   if (0 < $form->{number_of_new_bins}) {
1947     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
1948     $sth   = prepare_query($form, $dbh, $query);
1949
1950     foreach my $i (1..$form->{number_of_new_bins}) {
1951       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
1952     }
1953
1954     $sth->finish();
1955   }
1956
1957   $dbh->commit();
1958
1959   $main::lxdebug->leave_sub();
1960 }
1961
1962 sub save_bins {
1963   $main::lxdebug->enter_sub();
1964
1965   my ($self, $myconfig, $form) = @_;
1966
1967   # connect to database
1968   my $dbh = $form->get_standard_dbh($myconfig);
1969
1970   my ($query, @values, $commit_necessary, $sth);
1971
1972   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
1973
1974   if (@values) {
1975     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
1976     do_query($form, $dbh, $query, @values);
1977
1978     $commit_necessary = 1;
1979   }
1980
1981   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
1982   $sth   = prepare_query($form, $dbh, $query);
1983
1984   foreach my $row (1..$form->{rowcount}) {
1985     next if ($form->{"delete_${row}"});
1986
1987     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
1988
1989     $commit_necessary = 1;
1990   }
1991
1992   $sth->finish();
1993
1994   $dbh->commit() if ($commit_necessary);
1995
1996   $main::lxdebug->leave_sub();
1997 }
1998
1999 sub delete_warehouse {
2000   $main::lxdebug->enter_sub();
2001
2002   my ($self, $myconfig, $form) = @_;
2003
2004   # connect to database
2005   my $dbh = $form->get_standard_dbh($myconfig);
2006
2007   my $id      = conv_i($form->{id});
2008   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|;
2009   my ($count) = selectrow_query($form, $dbh, $query, $id);
2010
2011   if ($count) {
2012     $main::lxdebug->leave_sub();
2013     return 0;
2014   }
2015
2016   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2017   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2018
2019   $dbh->commit();
2020
2021   $main::lxdebug->leave_sub();
2022
2023   return 1;
2024 }
2025
2026 sub get_all_warehouses {
2027   $main::lxdebug->enter_sub();
2028
2029   my ($self, $myconfig, $form) = @_;
2030
2031   # connect to database
2032   my $dbh = $form->get_standard_dbh($myconfig);
2033
2034   my $query = qq|SELECT w.id, w.description, w.invalid,
2035                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2036                  FROM warehouse w
2037                  ORDER BY w.sortkey|;
2038
2039   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2040
2041   $main::lxdebug->leave_sub();
2042 }
2043
2044 sub get_warehouse {
2045   $main::lxdebug->enter_sub();
2046
2047   my ($self, $myconfig, $form) = @_;
2048
2049   # connect to database
2050   my $dbh = $form->get_standard_dbh($myconfig);
2051
2052   my $id    = conv_i($form->{id});
2053   my $query = qq|SELECT w.description, w.invalid
2054                  FROM warehouse w
2055                  WHERE w.id = ?|;
2056
2057   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2058
2059   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2060
2061   $query = qq|SELECT b.*, EXISTS
2062                 (SELECT i.warehouse_id
2063                  FROM inventory i
2064                  WHERE i.bin_id = b.id
2065                  LIMIT 1)
2066                 AS in_use
2067               FROM bin b
2068               WHERE b.warehouse_id = ?|;
2069
2070   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2071
2072   $main::lxdebug->leave_sub();
2073 }
2074
2075 1;