Standard-Auswahl für Umlaufvermögenskonto (Bank) mandantenweit setzen. Ferner yearend...
[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   my ($self, $myconfig, $form) = @_;
203
204   # connect to database, turn off AutoCommit
205   my $dbh = $form->dbconnect_noauto($myconfig);
206
207   # sanity check, can't have AR with AR_...
208   if ($form->{AR} || $form->{AP} || $form->{IC}) {
209     map { delete $form->{$_} }
210       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);
211   }
212
213   $form->{link} = "";
214   foreach my $item ($form->{AR},            $form->{AR_amount},
215                     $form->{AR_tax},        $form->{AR_paid},
216                     $form->{AP},            $form->{AP_amount},
217                     $form->{AP_tax},        $form->{AP_paid},
218                     $form->{IC},            $form->{IC_sale},
219                     $form->{IC_cogs},       $form->{IC_taxpart},
220                     $form->{IC_income},     $form->{IC_expense},
221                     $form->{IC_taxservice}, $form->{CT_tax}
222     ) {
223     $form->{link} .= "${item}:" if ($item);
224   }
225   chop $form->{link};
226
227   # strip blanks from accno
228   map { $form->{$_} =~ s/ //g; } qw(accno);
229
230   my ($query, $sth);
231
232   if ($form->{id} eq "NULL") {
233     $form->{id} = "";
234   }
235
236   if (!$form->{id} || $form->{id} eq "") {
237     $query = qq|SELECT nextval('id')|;
238     ($form->{"id"}) = selectrow_query($form, $dbh, $query);
239     $query = qq|INSERT INTO chart (id, accno) VALUES (?, ?)|;
240     do_query($form, $dbh, $query, $form->{"id"}, $form->{"accno"});
241   }
242
243   my @values;
244
245   if ($form->{id}) {
246     $query = qq|UPDATE chart SET
247                   accno = ?,
248                   description = ?,
249                   charttype = ?,
250                   category = ?,
251                   link = ?,
252                   pos_bwa   = ?,
253                   pos_bilanz = ?,
254                   pos_eur = ?,
255                   new_chart_id = ?,
256                   valid_from = ?,
257                   datevautomatik = ?
258                 WHERE id = ?|;
259
260     @values = (
261                   $form->{accno},
262                   $form->{description},
263                   $form->{charttype},
264                   $form->{category},
265                   $form->{link},
266                   conv_i($form->{pos_bwa}),
267                   conv_i($form->{pos_bilanz}),
268                   conv_i($form->{pos_eur}),
269                   conv_i($form->{new_chart_id}),
270                   conv_date($form->{valid_from}),
271                   ($form->{datevautomatik} eq 'T') ? 'true':'false',
272                 $form->{id},
273     );
274
275   }
276
277   do_query($form, $dbh, $query, @values);
278
279   #Save Taxkeys
280
281   my @taxkeys = ();
282
283   my $MAX_TRIES = 10; # Maximum count of taxkeys in form
284   my $tk_count;
285
286   READTAXKEYS:
287   for $tk_count (0 .. $MAX_TRIES) {
288
289     # Loop control
290
291     # Check if the account already exists, else cancel
292
293     print(STDERR "Keine Taxkeys weil ID =: $form->{id}\n");
294
295     last READTAXKEYS if ( $form->{'id'} == 0);
296
297     # check if there is a startdate
298     if ( $form->{"taxkey_startdate_$tk_count"} eq '' ) {
299       $tk_count++;
300       next READTAXKEYS;
301     }
302
303     # Add valid taxkeys into the array
304     push @taxkeys ,
305       {
306         id        => ($form->{"taxkey_id_$tk_count"} eq 'NEW') ? conv_i('') : conv_i($form->{"taxkey_id_$tk_count"}),
307         tax_id    => conv_i($form->{"taxkey_tax_$tk_count"}),
308         startdate => conv_date($form->{"taxkey_startdate_$tk_count"}),
309         chart_id  => conv_i($form->{"id"}),
310         pos_ustva => conv_i($form->{"taxkey_pos_ustva_$tk_count"}),
311         delete    => ( $form->{"taxkey_del_$tk_count"} eq 'delete' ) ? '1' : '',
312       };
313
314     $tk_count++;
315   }
316
317   TAXKEY:
318   for my $j (0 .. $#taxkeys){
319     if ( defined $taxkeys[$j]{'id'} ){
320       # delete Taxkey?
321
322       if ($taxkeys[$j]{'delete'}){
323         $query = qq{
324           DELETE FROM taxkeys WHERE id = ?
325         };
326
327         @values = ($taxkeys[$j]{'id'});
328
329         do_query($form, $dbh, $query, @values);
330
331         next TAXKEY;
332       }
333
334       # UPDATE Taxkey
335
336       $query = qq{
337         UPDATE taxkeys
338         SET taxkey_id = (SELECT taxkey FROM tax WHERE tax.id = ?),
339             chart_id  = ?,
340             tax_id    = ?,
341             pos_ustva = ?,
342             startdate = ?
343         WHERE id = ?
344       };
345       @values = (
346         $taxkeys[$j]{'tax_id'},
347         $taxkeys[$j]{'chart_id'},
348         $taxkeys[$j]{'tax_id'},
349         $taxkeys[$j]{'pos_ustva'},
350         $taxkeys[$j]{'startdate'},
351         $taxkeys[$j]{'id'},
352       );
353       do_query($form, $dbh, $query, @values);
354     }
355     else {
356       # INSERT Taxkey
357
358       $query = qq{
359         INSERT INTO taxkeys (
360           taxkey_id,
361           chart_id,
362           tax_id,
363           pos_ustva,
364           startdate
365         )
366         VALUES ((SELECT taxkey FROM tax WHERE tax.id = ?), ?, ?, ?, ?)
367       };
368       @values = (
369         $taxkeys[$j]{'tax_id'},
370         $taxkeys[$j]{'chart_id'},
371         $taxkeys[$j]{'tax_id'},
372         $taxkeys[$j]{'pos_ustva'},
373         $taxkeys[$j]{'startdate'},
374       );
375
376       do_query($form, $dbh, $query, @values);
377     }
378
379   }
380
381   # commit
382   my $rc = $dbh->commit;
383   $dbh->disconnect;
384
385   $main::lxdebug->leave_sub();
386
387   return $rc;
388 }
389
390 sub delete_account {
391   $main::lxdebug->enter_sub();
392
393   my ($self, $myconfig, $form) = @_;
394
395   # connect to database, turn off AutoCommit
396   my $dbh = $form->dbconnect_noauto($myconfig);
397
398   my $query = qq|SELECT count(*) FROM acc_trans a
399                  WHERE a.chart_id = ?|;
400   my ($count) = selectrow_query($form, $dbh, $query, $form->{id});
401
402   if ($count) {
403     $dbh->disconnect;
404     $main::lxdebug->leave_sub();
405     return;
406   }
407
408   # set inventory_accno_id, income_accno_id, expense_accno_id to defaults
409   foreach my $type (qw(inventory income expense)) {
410     $query =
411       qq|UPDATE parts | .
412       qq|SET ${type}_accno_id = (SELECT ${type}_accno_id FROM defaults) | .
413       qq|WHERE ${type}_accno_id = ?|;
414     do_query($form, $dbh, $query, $form->{id});
415   }
416
417   foreach my $table (qw(partstax customertax vendortax tax)) {
418     $query = qq|DELETE FROM $table
419                 WHERE chart_id = ?|;
420     do_query($form, $dbh, $query, $form->{id});
421   }
422
423   # delete chart of account record
424   $query = qq|DELETE FROM chart
425               WHERE id = ?|;
426   do_query($form, $dbh, $query, $form->{id});
427
428   # delete account taxkeys
429   $query = qq|DELETE FROM taxkeys
430               WHERE chart_id = ?|;
431   do_query($form, $dbh, $query, $form->{id});
432
433   # commit and redirect
434   my $rc = $dbh->commit;
435   $dbh->disconnect;
436
437   $main::lxdebug->leave_sub();
438
439   return $rc;
440 }
441
442 sub departments {
443   $main::lxdebug->enter_sub();
444
445   my ($self, $myconfig, $form) = @_;
446
447   # connect to database
448   my $dbh = $form->dbconnect($myconfig);
449
450   my $query = qq|SELECT d.id, d.description, d.role
451                  FROM department d
452                  ORDER BY 2|;
453
454   my $sth = $dbh->prepare($query);
455   $sth->execute || $form->dberror($query);
456
457   $form->{ALL} = [];
458   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
459     push @{ $form->{ALL} }, $ref;
460   }
461
462   $sth->finish;
463   $dbh->disconnect;
464
465   $main::lxdebug->leave_sub();
466 }
467
468 sub get_department {
469   $main::lxdebug->enter_sub();
470
471   my ($self, $myconfig, $form) = @_;
472
473   # connect to database
474   my $dbh = $form->dbconnect($myconfig);
475
476   my $query = qq|SELECT d.description, d.role
477                  FROM department d
478                  WHERE d.id = ?|;
479   my $sth = $dbh->prepare($query);
480   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
481
482   my $ref = $sth->fetchrow_hashref("NAME_lc");
483
484   map { $form->{$_} = $ref->{$_} } keys %$ref;
485
486   $sth->finish;
487
488   # see if it is in use
489   $query = qq|SELECT count(*) FROM dpt_trans d
490               WHERE d.department_id = ?|;
491   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
492
493   $form->{orphaned} = !$form->{orphaned};
494   $sth->finish;
495
496   $dbh->disconnect;
497
498   $main::lxdebug->leave_sub();
499 }
500
501 sub save_department {
502   $main::lxdebug->enter_sub();
503
504   my ($self, $myconfig, $form) = @_;
505   my ($query);
506
507   # connect to database
508   my $dbh = $form->dbconnect($myconfig);
509
510   my @values = ($form->{description}, $form->{role});
511   if ($form->{id}) {
512     $query = qq|UPDATE department SET
513                 description = ?, role = ?
514                 WHERE id = ?|;
515     push(@values, $form->{id});
516   } else {
517     $query = qq|INSERT INTO department
518                 (description, role)
519                 VALUES (?, ?)|;
520   }
521   do_query($form, $dbh, $query, @values);
522
523   $dbh->disconnect;
524
525   $main::lxdebug->leave_sub();
526 }
527
528 sub delete_department {
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   $query = qq|DELETE FROM department
538               WHERE id = ?|;
539   do_query($form, $dbh, $query, $form->{id});
540
541   $dbh->disconnect;
542
543   $main::lxdebug->leave_sub();
544 }
545
546 sub lead {
547   $main::lxdebug->enter_sub();
548
549   my ($self, $myconfig, $form) = @_;
550
551   # connect to database
552   my $dbh = $form->dbconnect($myconfig);
553
554   my $query = qq|SELECT id, lead
555                  FROM leads
556                  ORDER BY 2|;
557
558   my $sth = $dbh->prepare($query);
559   $sth->execute || $form->dberror($query);
560
561   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
562     push @{ $form->{ALL} }, $ref;
563   }
564
565   $sth->finish;
566   $dbh->disconnect;
567
568   $main::lxdebug->leave_sub();
569 }
570
571 sub get_lead {
572   $main::lxdebug->enter_sub();
573
574   my ($self, $myconfig, $form) = @_;
575
576   # connect to database
577   my $dbh = $form->dbconnect($myconfig);
578
579   my $query =
580     qq|SELECT l.id, l.lead | .
581     qq|FROM leads l | .
582     qq|WHERE l.id = ?|;
583   my $sth = $dbh->prepare($query);
584   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
585
586   my $ref = $sth->fetchrow_hashref("NAME_lc");
587
588   map { $form->{$_} = $ref->{$_} } keys %$ref;
589
590   $sth->finish;
591
592   $dbh->disconnect;
593
594   $main::lxdebug->leave_sub();
595 }
596
597 sub save_lead {
598   $main::lxdebug->enter_sub();
599
600   my ($self, $myconfig, $form) = @_;
601   my ($query);
602
603   # connect to database
604   my $dbh = $form->dbconnect($myconfig);
605
606   my @values = ($form->{description});
607   # id is the old record
608   if ($form->{id}) {
609     $query = qq|UPDATE leads SET
610                 lead = ?
611                 WHERE id = ?|;
612     puhs(@values, $form->{id});
613   } else {
614     $query = qq|INSERT INTO leads
615                 (lead)
616                 VALUES (?)|;
617   }
618   do_query($form, $dbh, $query, @values);
619
620   $dbh->disconnect;
621
622   $main::lxdebug->leave_sub();
623 }
624
625 sub delete_lead {
626   $main::lxdebug->enter_sub();
627
628   my ($self, $myconfig, $form) = @_;
629   my ($query);
630
631   # connect to database
632   my $dbh = $form->dbconnect($myconfig);
633
634   $query = qq|DELETE FROM leads
635               WHERE id = ?|;
636   do_query($form, $dbh, $query, $form->{id});
637
638   $dbh->disconnect;
639
640   $main::lxdebug->leave_sub();
641 }
642
643 sub business {
644   $main::lxdebug->enter_sub();
645
646   my ($self, $myconfig, $form) = @_;
647
648   # connect to database
649   my $dbh = $form->dbconnect($myconfig);
650
651   my $query = qq|SELECT id, description, discount, customernumberinit, salesman
652                  FROM business
653                  ORDER BY 2|;
654
655   my $sth = $dbh->prepare($query);
656   $sth->execute || $form->dberror($query);
657
658   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
659     push @{ $form->{ALL} }, $ref;
660   }
661
662   $sth->finish;
663   $dbh->disconnect;
664
665   $main::lxdebug->leave_sub();
666 }
667
668 sub get_business {
669   $main::lxdebug->enter_sub();
670
671   my ($self, $myconfig, $form) = @_;
672
673   # connect to database
674   my $dbh = $form->dbconnect($myconfig);
675
676   my $query =
677     qq|SELECT b.description, b.discount, b.customernumberinit, b.salesman
678        FROM business b
679        WHERE b.id = ?|;
680   my $sth = $dbh->prepare($query);
681   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
682
683   my $ref = $sth->fetchrow_hashref("NAME_lc");
684
685   map { $form->{$_} = $ref->{$_} } keys %$ref;
686
687   $sth->finish;
688
689   $dbh->disconnect;
690
691   $main::lxdebug->leave_sub();
692 }
693
694 sub save_business {
695   $main::lxdebug->enter_sub();
696
697   my ($self, $myconfig, $form) = @_;
698   my ($query);
699
700   # connect to database
701   my $dbh = $form->dbconnect($myconfig);
702
703   my @values = ($form->{description}, $form->{discount}, $form->{customernumberinit}, $form->{salesman} ? 't' : 'f');
704   # id is the old record
705   if ($form->{id}) {
706     $query = qq|UPDATE business SET
707                 description = ?,
708                 discount = ?,
709                 customernumberinit = ?,
710                 salesman = ?
711                 WHERE id = ?|;
712     push(@values, $form->{id});
713   } else {
714     $query = qq|INSERT INTO business
715                 (description, discount, customernumberinit, salesman)
716                 VALUES (?, ?, ?, ?)|;
717   }
718   do_query($form, $dbh, $query, @values);
719
720   $dbh->disconnect;
721
722   $main::lxdebug->leave_sub();
723 }
724
725 sub delete_business {
726   $main::lxdebug->enter_sub();
727
728   my ($self, $myconfig, $form) = @_;
729
730   # connect to database
731   my $dbh = $form->dbconnect($myconfig);
732
733   my $query = qq|DELETE FROM business
734               WHERE id = ?|;
735   do_query($form, $dbh, $query, $form->{id});
736
737   $dbh->disconnect;
738
739   $main::lxdebug->leave_sub();
740 }
741
742
743 sub language {
744   $main::lxdebug->enter_sub();
745
746   my ($self, $myconfig, $form, $return_list) = @_;
747
748   # connect to database
749   my $dbh = $form->dbconnect($myconfig);
750
751   my $query =
752     "SELECT id, description, template_code, article_code, " .
753     "  output_numberformat, output_dateformat, output_longdates " .
754     "FROM language ORDER BY description";
755
756   my $sth = $dbh->prepare($query);
757   $sth->execute || $form->dberror($query);
758
759   my $ary = [];
760
761   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
762     push(@{ $ary }, $ref);
763   }
764
765   $sth->finish;
766   $dbh->disconnect;
767
768   $main::lxdebug->leave_sub();
769
770   if ($return_list) {
771     return @{$ary};
772   } else {
773     $form->{ALL} = $ary;
774   }
775 }
776
777 sub get_language {
778   $main::lxdebug->enter_sub();
779
780   my ($self, $myconfig, $form) = @_;
781
782   # connect to database
783   my $dbh = $form->dbconnect($myconfig);
784
785   my $query =
786     "SELECT description, template_code, article_code, " .
787     "  output_numberformat, output_dateformat, output_longdates " .
788     "FROM language 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   $dbh->disconnect;
799
800   $main::lxdebug->leave_sub();
801 }
802
803 sub get_language_details {
804   $main::lxdebug->enter_sub();
805
806   my ($self, $myconfig, $form, $id) = @_;
807
808   # connect to database
809   my $dbh = $form->dbconnect($myconfig);
810
811   my $query =
812     "SELECT template_code, " .
813     "  output_numberformat, output_dateformat, output_longdates " .
814     "FROM language WHERE id = ?";
815   my @res = selectrow_query($form, $dbh, $query, $id);
816   $dbh->disconnect;
817
818   $main::lxdebug->leave_sub();
819
820   return @res;
821 }
822
823 sub save_language {
824   $main::lxdebug->enter_sub();
825
826   my ($self, $myconfig, $form) = @_;
827
828   # connect to database
829   my $dbh = $form->dbconnect($myconfig);
830   my (@values, $query);
831
832   map({ push(@values, $form->{$_}); }
833       qw(description template_code article_code
834          output_numberformat output_dateformat output_longdates));
835
836   # id is the old record
837   if ($form->{id}) {
838     $query =
839       "UPDATE language SET " .
840       "  description = ?, template_code = ?, article_code = ?, " .
841       "  output_numberformat = ?, output_dateformat = ?, " .
842       "  output_longdates = ? " .
843       "WHERE id = ?";
844     push(@values, $form->{id});
845   } else {
846     $query =
847       "INSERT INTO language (" .
848       "  description, template_code, article_code, " .
849       "  output_numberformat, output_dateformat, output_longdates" .
850       ") VALUES (?, ?, ?, ?, ?, ?)";
851   }
852   do_query($form, $dbh, $query, @values);
853
854   $dbh->disconnect;
855
856   $main::lxdebug->leave_sub();
857 }
858
859 sub delete_language {
860   $main::lxdebug->enter_sub();
861
862   my ($self, $myconfig, $form) = @_;
863   my $query;
864
865   # connect to database
866   my $dbh = $form->dbconnect_noauto($myconfig);
867
868   foreach my $table (qw(translation_payment_terms units_language)) {
869     $query = qq|DELETE FROM $table WHERE language_id = ?|;
870     do_query($form, $dbh, $query, $form->{"id"});
871   }
872
873   $query = "DELETE FROM language WHERE id = ?";
874   do_query($form, $dbh, $query, $form->{"id"});
875
876   $dbh->commit();
877   $dbh->disconnect;
878
879   $main::lxdebug->leave_sub();
880 }
881
882
883 sub buchungsgruppe {
884   $main::lxdebug->enter_sub();
885
886   my ($self, $myconfig, $form) = @_;
887
888   # connect to database
889   my $dbh = $form->dbconnect($myconfig);
890
891   my $query = qq|SELECT id, description,
892                  inventory_accno_id,
893                  (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
894                  income_accno_id_0,
895                  (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
896                  expense_accno_id_0,
897                  (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
898                  income_accno_id_1,
899                  (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
900                  expense_accno_id_1,
901                  (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
902                  income_accno_id_2,
903                  (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
904                  expense_accno_id_2,
905                  (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
906                  income_accno_id_3,
907                  (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
908                  expense_accno_id_3,
909                  (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
910                  FROM buchungsgruppen
911                  ORDER BY sortkey|;
912
913   my $sth = $dbh->prepare($query);
914   $sth->execute || $form->dberror($query);
915
916   $form->{ALL} = [];
917   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
918     push @{ $form->{ALL} }, $ref;
919   }
920
921   $sth->finish;
922   $dbh->disconnect;
923
924   $main::lxdebug->leave_sub();
925 }
926
927 sub get_buchungsgruppe {
928   $main::lxdebug->enter_sub();
929
930   my ($self, $myconfig, $form) = @_;
931   my $query;
932
933   # connect to database
934   my $dbh = $form->dbconnect($myconfig);
935
936   if ($form->{id}) {
937     $query =
938       qq|SELECT description, inventory_accno_id,
939          (SELECT accno FROM chart WHERE id = inventory_accno_id) AS inventory_accno,
940          income_accno_id_0,
941          (SELECT accno FROM chart WHERE id = income_accno_id_0) AS income_accno_0,
942          expense_accno_id_0,
943          (SELECT accno FROM chart WHERE id = expense_accno_id_0) AS expense_accno_0,
944          income_accno_id_1,
945          (SELECT accno FROM chart WHERE id = income_accno_id_1) AS income_accno_1,
946          expense_accno_id_1,
947          (SELECT accno FROM chart WHERE id = expense_accno_id_1) AS expense_accno_1,
948          income_accno_id_2,
949          (SELECT accno FROM chart WHERE id = income_accno_id_2) AS income_accno_2,
950          expense_accno_id_2,
951          (select accno FROM chart WHERE id = expense_accno_id_2) AS expense_accno_2,
952          income_accno_id_3,
953          (SELECT accno FROM chart WHERE id = income_accno_id_3) AS income_accno_3,
954          expense_accno_id_3,
955          (SELECT accno FROM chart WHERE id = expense_accno_id_3) AS expense_accno_3
956          FROM buchungsgruppen
957          WHERE id = ?|;
958     my $sth = $dbh->prepare($query);
959     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
960
961     my $ref = $sth->fetchrow_hashref("NAME_lc");
962
963     map { $form->{$_} = $ref->{$_} } keys %$ref;
964
965     $sth->finish;
966
967     $query =
968       qq|SELECT count(id) = 0 AS orphaned
969          FROM parts
970          WHERE buchungsgruppen_id = ?|;
971     ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
972   }
973
974   $query = "SELECT inventory_accno_id, income_accno_id, expense_accno_id ".
975     "FROM defaults";
976   ($form->{"std_inventory_accno_id"}, $form->{"std_income_accno_id"},
977    $form->{"std_expense_accno_id"}) = selectrow_query($form, $dbh, $query);
978
979   my $module = "IC";
980   $query = qq|SELECT c.accno, c.description, c.link, c.id,
981               d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
982               FROM chart c, defaults d
983               WHERE c.link LIKE '%$module%'
984               ORDER BY c.accno|;
985
986
987   my $sth = $dbh->prepare($query);
988   $sth->execute || $form->dberror($query);
989   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
990     foreach my $key (split(/:/, $ref->{link})) {
991       if (!$form->{"std_inventory_accno_id"} && ($key eq "IC")) {
992         $form->{"std_inventory_accno_id"} = $ref->{"id"};
993       }
994       if ($key =~ /$module/) {
995         if (   ($ref->{id} eq $ref->{inventory_accno_id})
996             || ($ref->{id} eq $ref->{income_accno_id})
997             || ($ref->{id} eq $ref->{expense_accno_id})) {
998           push @{ $form->{"${module}_links"}{$key} },
999             { accno       => $ref->{accno},
1000               description => $ref->{description},
1001               selected    => "selected",
1002               id          => $ref->{id} };
1003         } else {
1004           push @{ $form->{"${module}_links"}{$key} },
1005             { accno       => $ref->{accno},
1006               description => $ref->{description},
1007               selected    => "",
1008               id          => $ref->{id} };
1009         }
1010       }
1011     }
1012   }
1013   $sth->finish;
1014
1015
1016   $dbh->disconnect;
1017
1018   $main::lxdebug->leave_sub();
1019 }
1020
1021 sub save_buchungsgruppe {
1022   $main::lxdebug->enter_sub();
1023
1024   my ($self, $myconfig, $form) = @_;
1025
1026   # connect to database
1027   my $dbh = $form->dbconnect($myconfig);
1028
1029   my @values = ($form->{description}, $form->{inventory_accno_id},
1030                 $form->{income_accno_id_0}, $form->{expense_accno_id_0},
1031                 $form->{income_accno_id_1}, $form->{expense_accno_id_1},
1032                 $form->{income_accno_id_2}, $form->{expense_accno_id_2},
1033                 $form->{income_accno_id_3}, $form->{expense_accno_id_3});
1034
1035   my $query;
1036
1037   # id is the old record
1038   if ($form->{id}) {
1039     $query = qq|UPDATE buchungsgruppen SET
1040                 description = ?, inventory_accno_id = ?,
1041                 income_accno_id_0 = ?, expense_accno_id_0 = ?,
1042                 income_accno_id_1 = ?, expense_accno_id_1 = ?,
1043                 income_accno_id_2 = ?, expense_accno_id_2 = ?,
1044                 income_accno_id_3 = ?, expense_accno_id_3 = ?
1045                 WHERE id = ?|;
1046     push(@values, $form->{id});
1047   } else {
1048     $query = qq|SELECT COALESCE(MAX(sortkey) + 1, 1) FROM buchungsgruppen|;
1049     my ($sortkey) = $dbh->selectrow_array($query);
1050     $form->dberror($query) if ($dbh->err);
1051     push(@values, $sortkey);
1052     $query = qq|INSERT INTO buchungsgruppen
1053                 (description, inventory_accno_id,
1054                 income_accno_id_0, expense_accno_id_0,
1055                 income_accno_id_1, expense_accno_id_1,
1056                 income_accno_id_2, expense_accno_id_2,
1057                 income_accno_id_3, expense_accno_id_3,
1058                 sortkey)
1059                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1060   }
1061   do_query($form, $dbh, $query, @values);
1062
1063   $dbh->disconnect;
1064
1065   $main::lxdebug->leave_sub();
1066 }
1067
1068 sub delete_buchungsgruppe {
1069   $main::lxdebug->enter_sub();
1070
1071   my ($self, $myconfig, $form) = @_;
1072
1073   # connect to database
1074   my $dbh = $form->dbconnect($myconfig);
1075
1076   my $query = qq|DELETE FROM buchungsgruppen WHERE id = ?|;
1077   do_query($form, $dbh, $query, $form->{id});
1078
1079   $dbh->disconnect;
1080
1081   $main::lxdebug->leave_sub();
1082 }
1083
1084 sub swap_sortkeys {
1085   $main::lxdebug->enter_sub();
1086
1087   my ($self, $myconfig, $form, $table) = @_;
1088
1089   # connect to database
1090   my $dbh = $form->get_standard_dbh($myconfig);
1091
1092   my $query =
1093     qq|SELECT
1094        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey1,
1095        (SELECT sortkey FROM $table WHERE id = ?) AS sortkey2|;
1096   my @values   = ($form->{"id1"}, $form->{"id2"});
1097   my @sortkeys = selectrow_query($form, $dbh, $query, @values);
1098
1099   $query  = qq|UPDATE $table SET sortkey = ? WHERE id = ?|;
1100   my $sth = prepare_query($form, $dbh, $query);
1101
1102   do_statement($form, $sth, $query, $sortkeys[1], $form->{"id1"});
1103   do_statement($form, $sth, $query, $sortkeys[0], $form->{"id2"});
1104
1105   $sth->finish();
1106
1107   $dbh->commit();
1108
1109   $main::lxdebug->leave_sub();
1110 }
1111
1112 sub payment {
1113   $main::lxdebug->enter_sub();
1114
1115   my ($self, $myconfig, $form) = @_;
1116
1117   # connect to database
1118   my $dbh = $form->dbconnect($myconfig);
1119
1120   my $query = qq|SELECT * FROM payment_terms ORDER BY sortkey|;
1121
1122   my $sth = $dbh->prepare($query);
1123   $sth->execute || $form->dberror($query);
1124
1125   $form->{ALL} = [];
1126   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1127     push @{ $form->{ALL} }, $ref;
1128   }
1129
1130   $sth->finish;
1131   $dbh->disconnect;
1132
1133   $main::lxdebug->leave_sub();
1134 }
1135
1136 sub get_payment {
1137   $main::lxdebug->enter_sub();
1138
1139   my ($self, $myconfig, $form) = @_;
1140
1141   # connect to database
1142   my $dbh = $form->dbconnect($myconfig);
1143
1144   my $query = qq|SELECT * FROM payment_terms WHERE id = ?|;
1145   my $sth = $dbh->prepare($query);
1146   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1147
1148   my $ref = $sth->fetchrow_hashref("NAME_lc");
1149   map { $form->{$_} = $ref->{$_} } keys %$ref;
1150   $sth->finish();
1151
1152   $query =
1153     qq|SELECT t.language_id, t.description_long, l.description AS language | .
1154     qq|FROM translation_payment_terms t | .
1155     qq|LEFT JOIN language l ON t.language_id = l.id | .
1156     qq|WHERE t.payment_terms_id = ? | .
1157     qq|UNION | .
1158     qq|SELECT l.id AS language_id, NULL AS description_long, | .
1159     qq|  l.description AS language | .
1160     qq|FROM language l|;
1161   $sth = $dbh->prepare($query);
1162   $sth->execute($form->{"id"}) || $form->dberror($query . " ($form->{id})");
1163
1164   my %mapping;
1165   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1166     $mapping{ $ref->{"language_id"} } = $ref
1167       unless (defined($mapping{ $ref->{"language_id"} }));
1168   }
1169   $sth->finish;
1170
1171   $form->{"TRANSLATION"} = [sort({ $a->{"language"} cmp $b->{"language"} }
1172                                  values(%mapping))];
1173
1174   $dbh->disconnect;
1175
1176   $main::lxdebug->leave_sub();
1177 }
1178
1179 sub save_payment {
1180   $main::lxdebug->enter_sub();
1181
1182   my ($self, $myconfig, $form) = @_;
1183
1184   # connect to database
1185   my $dbh = $form->dbconnect_noauto($myconfig);
1186
1187   my $query;
1188
1189   if (!$form->{id}) {
1190     $query = qq|SELECT nextval('id'), COALESCE(MAX(sortkey) + 1, 1) | .
1191       qq|FROM payment_terms|;
1192     my $sortkey;
1193     ($form->{id}, $sortkey) = selectrow_query($form, $dbh, $query);
1194
1195     $query = qq|INSERT INTO payment_terms (id, sortkey) VALUES (?, ?)|;
1196     do_query($form, $dbh, $query, $form->{id}, $sortkey);
1197
1198   } else {
1199     $query =
1200       qq|DELETE FROM translation_payment_terms | .
1201       qq|WHERE payment_terms_id = ?|;
1202     do_query($form, $dbh, $query, $form->{"id"});
1203   }
1204
1205   $query = qq|UPDATE payment_terms SET
1206               description = ?, description_long = ?,
1207               terms_netto = ?, terms_skonto = ?,
1208               percent_skonto = ?
1209               WHERE id = ?|;
1210   my @values = ($form->{description}, $form->{description_long},
1211                 $form->{terms_netto} * 1, $form->{terms_skonto} * 1,
1212                 $form->{percent_skonto} * 1,
1213                 $form->{id});
1214   do_query($form, $dbh, $query, @values);
1215
1216   $query = qq|SELECT id FROM language|;
1217   my @language_ids;
1218   my $sth = $dbh->prepare($query);
1219   $sth->execute() || $form->dberror($query);
1220
1221   while (my ($id) = $sth->fetchrow_array()) {
1222     push(@language_ids, $id);
1223   }
1224   $sth->finish();
1225
1226   $query =
1227     qq|INSERT INTO translation_payment_terms | .
1228     qq|(language_id, payment_terms_id, description_long) | .
1229     qq|VALUES (?, ?, ?)|;
1230   $sth = $dbh->prepare($query);
1231
1232   foreach my $language_id (@language_ids) {
1233     do_statement($form, $sth, $query, $language_id, $form->{"id"},
1234                  $form->{"description_long_${language_id}"});
1235   }
1236   $sth->finish();
1237
1238   $dbh->commit();
1239   $dbh->disconnect;
1240
1241   $main::lxdebug->leave_sub();
1242 }
1243
1244 sub delete_payment {
1245   $main::lxdebug->enter_sub();
1246
1247   my ($self, $myconfig, $form) = @_;
1248
1249   # connect to database
1250   my $dbh = $form->dbconnect_noauto($myconfig);
1251
1252   my $query =
1253     qq|DELETE FROM translation_payment_terms WHERE payment_terms_id = ?|;
1254   do_query($form, $dbh, $query, $form->{"id"});
1255
1256   $query = qq|DELETE FROM payment_terms WHERE id = ?|;
1257   do_query($form, $dbh, $query, $form->{"id"});
1258
1259   $dbh->commit();
1260   $dbh->disconnect;
1261
1262   $main::lxdebug->leave_sub();
1263 }
1264
1265
1266 sub prepare_template_filename {
1267   $main::lxdebug->enter_sub();
1268
1269   my ($self, $myconfig, $form) = @_;
1270
1271   my ($filename, $display_filename);
1272
1273   if ($form->{type} eq "stylesheet") {
1274     $filename = "css/$myconfig->{stylesheet}";
1275     $display_filename = $myconfig->{stylesheet};
1276
1277   } else {
1278     $filename = $form->{formname};
1279
1280     if ($form->{language}) {
1281       my ($id, $template_code) = split(/--/, $form->{language});
1282       $filename .= "_${template_code}";
1283     }
1284
1285     if ($form->{printer}) {
1286       my ($id, $template_code) = split(/--/, $form->{printer});
1287       $filename .= "_${template_code}";
1288     }
1289
1290     $filename .= "." . ($form->{format} eq "html" ? "html" : "tex");
1291     $filename =~ s|.*/||;
1292     $display_filename = $filename;
1293     $filename = "$myconfig->{templates}/$filename";
1294   }
1295
1296   $main::lxdebug->leave_sub();
1297
1298   return ($filename, $display_filename);
1299 }
1300
1301
1302 sub load_template {
1303   $main::lxdebug->enter_sub();
1304
1305   my ($self, $filename) = @_;
1306
1307   my ($content, $lines) = ("", 0);
1308
1309   local *TEMPLATE;
1310
1311   if (open(TEMPLATE, $filename)) {
1312     while (<TEMPLATE>) {
1313       $content .= $_;
1314       $lines++;
1315     }
1316     close(TEMPLATE);
1317   }
1318
1319   $content = Encode::decode('utf-8-strict', $content) if $::locale->is_utf8;
1320
1321   $main::lxdebug->leave_sub();
1322
1323   return ($content, $lines);
1324 }
1325
1326 sub save_template {
1327   $main::lxdebug->enter_sub();
1328
1329   my ($self, $filename, $content) = @_;
1330
1331   local *TEMPLATE;
1332
1333   my $error = "";
1334
1335   if (open(TEMPLATE, ">$filename")) {
1336     $content = Encode::encode('utf-8-strict', $content) if $::locale->is_utf8;
1337     $content =~ s/\r\n/\n/g;
1338     print(TEMPLATE $content);
1339     close(TEMPLATE);
1340   } else {
1341     $error = $!;
1342   }
1343
1344   $main::lxdebug->leave_sub();
1345
1346   return $error;
1347 }
1348
1349 sub save_defaults {
1350   $main::lxdebug->enter_sub();
1351
1352   my $self     = shift;
1353   my %params   = @_;
1354
1355   my $myconfig = \%main::myconfig;
1356   my $form     = $main::form;
1357
1358   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1359
1360   my %accnos;
1361   map { ($accnos{$_}) = split(m/--/, $form->{$_}) } qw(inventory_accno income_accno expense_accno fxgain_accno fxloss_accno ar_paid_accno);
1362
1363   $form->{curr}  =~ s/ //g;
1364   my @currencies =  grep { $_ ne '' } split m/:/, $form->{curr};
1365   my $currency   =  join ':', @currencies;
1366
1367   # these defaults are database wide
1368
1369   my $query =
1370     qq|UPDATE defaults SET
1371         inventory_accno_id = (SELECT c.id FROM chart c WHERE c.accno = ?),
1372         income_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1373         expense_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1374         fxgain_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1375         fxloss_accno_id    = (SELECT c.id FROM chart c WHERE c.accno = ?),
1376         ar_paid_accno_id   = (SELECT c.id FROM chart c WHERE c.accno = ?),
1377         invnumber          = ?,
1378         cnnumber           = ?,
1379         sonumber           = ?,
1380         ponumber           = ?,
1381         sqnumber           = ?,
1382         rfqnumber          = ?,
1383         customernumber     = ?,
1384         vendornumber       = ?,
1385         articlenumber      = ?,
1386         servicenumber      = ?,
1387         sdonumber          = ?,
1388         pdonumber          = ?,
1389         curr               = ?,
1390         businessnumber     = ?,
1391         weightunit         = ?|;
1392   my @values = ($accnos{inventory_accno}, $accnos{income_accno}, $accnos{expense_accno},
1393                 $accnos{fxgain_accno},    $accnos{fxloss_accno}, $accnos{ar_paid_accno},
1394                 $form->{invnumber},       $form->{cnnumber},
1395                 $form->{sonumber},        $form->{ponumber},
1396                 $form->{sqnumber},        $form->{rfqnumber},
1397                 $form->{customernumber},  $form->{vendornumber},
1398                 $form->{articlenumber},   $form->{servicenumber},
1399                 $form->{sdonumber},       $form->{pdonumber},
1400                 $currency,
1401                 $form->{businessnumber},  $form->{weightunit});
1402   do_query($form, $dbh, $query, @values);
1403
1404   $dbh->commit();
1405
1406   $main::lxdebug->leave_sub();
1407 }
1408
1409
1410 sub save_preferences {
1411   $main::lxdebug->enter_sub();
1412
1413   my ($self, $myconfig, $form, $webdav) = @_;
1414
1415   my $dbh = $form->get_standard_dbh($myconfig);
1416
1417   my ($currency, $businessnumber) = selectrow_query($form, $dbh, qq|SELECT curr, businessnumber FROM defaults|);
1418
1419   # update name
1420   my $query = qq|UPDATE employee SET name = ? WHERE login = ?|;
1421   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1422
1423   my $rc = $dbh->commit();
1424
1425   # save first currency in myconfig
1426   $currency               =~ s/:.*//;
1427   $form->{currency}       =  $currency;
1428
1429   $form->{businessnumber} =  $businessnumber;
1430
1431   $myconfig = new User($form->{login});
1432
1433   foreach my $item (keys %$form) {
1434     $myconfig->{$item} = $form->{$item};
1435   }
1436
1437   $myconfig->save_member($main::memberfile);
1438
1439   my $auth = $main::auth;
1440
1441   if ($auth->can_change_password()
1442       && defined $form->{new_password}
1443       && ($form->{new_password} ne '********')) {
1444     $auth->change_password($form->{login}, $form->{new_password});
1445
1446     $form->{password} = $form->{new_password};
1447     $auth->set_session_value('password', $form->{password});
1448     $auth->create_or_refresh_session();
1449   }
1450
1451   $main::lxdebug->leave_sub();
1452
1453   return $rc;
1454 }
1455
1456 sub get_defaults {
1457   $main::lxdebug->enter_sub();
1458
1459   my $self     = shift;
1460   my %params   = @_;
1461
1462   my $myconfig = \%main::myconfig;
1463   my $form     = $main::form;
1464
1465   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1466
1467   my $defaults = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM defaults|) || {};
1468
1469   $defaults->{weightunit} ||= 'kg';
1470
1471   $main::lxdebug->leave_sub();
1472
1473   return $defaults;
1474 }
1475
1476 sub defaultaccounts {
1477   $main::lxdebug->enter_sub();
1478
1479   my ($self, $myconfig, $form) = @_;
1480
1481   # connect to database
1482   my $dbh = $form->dbconnect($myconfig);
1483
1484   # get defaults from defaults table
1485   my $query = qq|SELECT * FROM defaults|;
1486   my $sth   = $dbh->prepare($query);
1487   $sth->execute || $form->dberror($query);
1488
1489   $form->{defaults}               = $sth->fetchrow_hashref("NAME_lc");
1490   $form->{defaults}{IC}           = $form->{defaults}{inventory_accno_id};
1491   $form->{defaults}{IC_income}    = $form->{defaults}{income_accno_id};
1492   $form->{defaults}{IC_expense}   = $form->{defaults}{expense_accno_id};
1493   $form->{defaults}{FX_gain}      = $form->{defaults}{fxgain_accno_id};
1494   $form->{defaults}{FX_loss}      = $form->{defaults}{fxloss_accno_id};
1495   $form->{defaults}{AR_paid}      = $form->{defaults}{ar_paid_accno_id};
1496
1497   $form->{defaults}{weightunit} ||= 'kg';
1498
1499   $sth->finish;
1500
1501   $query = qq|SELECT c.id, c.accno, c.description, c.link
1502               FROM chart c
1503               WHERE c.link LIKE '%IC%'
1504               ORDER BY c.accno|;
1505   $sth = $dbh->prepare($query);
1506   $sth->execute || $self->dberror($query);
1507
1508   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1509     foreach my $key (split(/:/, $ref->{link})) {
1510       if ($key =~ /IC/) {
1511         my $nkey = $key;
1512         if ($key =~ /cogs/) {
1513           $nkey = "IC_expense";
1514         }
1515         if ($key =~ /sale/) {
1516           $nkey = "IC_income";
1517         }
1518         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1519                                              id          => $ref->{id},
1520                                              description => $ref->{description}
1521         );
1522       }
1523     }
1524   }
1525   $sth->finish;
1526
1527   $query = qq|SELECT c.id, c.accno, c.description
1528               FROM chart c
1529               WHERE c.category = 'I'
1530               AND c.charttype = 'A'
1531               ORDER BY c.accno|;
1532   $sth = $dbh->prepare($query);
1533   $sth->execute || $self->dberror($query);
1534
1535   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1536     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1537                                              id          => $ref->{id},
1538                                              description => $ref->{description}
1539     );
1540   }
1541   $sth->finish;
1542
1543   $query = qq|SELECT c.id, c.accno, c.description
1544               FROM chart c
1545               WHERE c.category = 'E'
1546               AND c.charttype = 'A'
1547               ORDER BY c.accno|;
1548   $sth = $dbh->prepare($query);
1549   $sth->execute || $self->dberror($query);
1550
1551   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1552     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1553                                              id          => $ref->{id},
1554                                              description => $ref->{description}
1555     );
1556   }
1557   $sth->finish;
1558
1559   # now get the tax rates and numbers
1560   $query = qq|SELECT c.id, c.accno, c.description,
1561               t.rate * 100 AS rate, t.taxnumber
1562               FROM chart c, tax t
1563               WHERE c.id = t.chart_id|;
1564
1565   $sth = $dbh->prepare($query);
1566   $sth->execute || $form->dberror($query);
1567
1568   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1569     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1570     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1571     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1572       if $ref->{taxnumber};
1573     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1574   }
1575   # Abfrage für Standard Umlaufvermögenskonto
1576   $query =
1577     qq|SELECT id, accno, description, link | .
1578     qq|FROM chart | .
1579     qq|WHERE link LIKE ? |.
1580     qq|ORDER BY accno|;
1581   $sth = prepare_execute_query($form, $dbh, $query, '%AR%');
1582   $sth->execute || $form->dberror($query);#
1583   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1584     foreach my $item (split(/:/, $ref->{link})) {
1585       if ($item eq "AR_paid") {
1586         %{ $form->{IC}{AR_paid}{ $ref->{accno} } } = (
1587                                              id          => $ref->{id},
1588                                              description => $ref->{description}
1589           );
1590       }
1591     }
1592   }
1593
1594   $sth->finish;
1595   $dbh->disconnect;
1596
1597   $main::lxdebug->leave_sub();
1598 }
1599
1600 sub closedto {
1601   $main::lxdebug->enter_sub();
1602
1603   my ($self, $myconfig, $form) = @_;
1604
1605   my $dbh = $form->dbconnect($myconfig);
1606
1607   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1608   my $sth   = $dbh->prepare($query);
1609   $sth->execute || $form->dberror($query);
1610
1611   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1612
1613   $sth->finish;
1614
1615   $dbh->disconnect;
1616
1617   $main::lxdebug->leave_sub();
1618 }
1619
1620 sub closebooks {
1621   $main::lxdebug->enter_sub();
1622
1623   my ($self, $myconfig, $form) = @_;
1624
1625   my $dbh = $form->dbconnect($myconfig);
1626
1627   my ($query, @values);
1628
1629   if ($form->{revtrans}) {
1630     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1631
1632   } elsif ($form->{closedto}) {
1633     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1634     @values = (conv_date($form->{closedto}));
1635
1636   } else {
1637     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1638   }
1639
1640   # set close in defaults
1641   do_query($form, $dbh, $query, @values);
1642
1643   $dbh->disconnect;
1644
1645   $main::lxdebug->leave_sub();
1646 }
1647
1648 sub get_base_unit {
1649   my ($self, $units, $unit_name, $factor) = @_;
1650
1651   $factor = 1 unless ($factor);
1652
1653   my $unit = $units->{$unit_name};
1654
1655   if (!defined($unit) || !$unit->{"base_unit"} ||
1656       ($unit_name eq $unit->{"base_unit"})) {
1657     return ($unit_name, $factor);
1658   }
1659
1660   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1661 }
1662
1663 sub retrieve_units {
1664   $main::lxdebug->enter_sub();
1665
1666   my ($self, $myconfig, $form, $prefix) = @_;
1667
1668   my $dbh = $form->get_standard_dbh;
1669
1670   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1671
1672   my $sth = prepare_execute_query($form, $dbh, $query);
1673
1674   my $units = {};
1675   while (my $ref = $sth->fetchrow_hashref()) {
1676     $units->{$ref->{"name"}} = $ref;
1677   }
1678   $sth->finish();
1679
1680   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1681   $sth = $dbh->prepare($query_lang);
1682   $sth->execute() || $form->dberror($query_lang);
1683   my @languages;
1684   while (my $ref = $sth->fetchrow_hashref()) {
1685     push(@languages, $ref);
1686   }
1687   $sth->finish();
1688
1689   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1690     "FROM units_language ul " .
1691     "LEFT JOIN language l ON ul.language_id = l.id " .
1692     "WHERE ul.unit = ?";
1693   $sth = $dbh->prepare($query_lang);
1694
1695   foreach my $unit (values(%{$units})) {
1696     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1697
1698     $unit->{"LANGUAGES"} = {};
1699     foreach my $lang (@languages) {
1700       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1701     }
1702
1703     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1704     while (my $ref = $sth->fetchrow_hashref()) {
1705       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1706     }
1707   }
1708   $sth->finish;
1709
1710   $main::lxdebug->leave_sub();
1711
1712   return $units;
1713 }
1714
1715 sub retrieve_all_units {
1716   $main::lxdebug->enter_sub();
1717
1718   my $self = shift;
1719
1720   if (!$main::all_units) {
1721     $main::all_units = $self->retrieve_units(\%main::myconfig, $main::form);
1722   }
1723
1724   $main::lxdebug->leave_sub();
1725
1726   return $main::all_units;
1727 }
1728
1729
1730 sub translate_units {
1731   $main::lxdebug->enter_sub();
1732
1733   my ($self, $form, $template_code, $unit, $amount) = @_;
1734
1735   my $units = $self->retrieve_units(\%main::myconfig, $form);
1736
1737   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1738   my $new_unit = $unit;
1739   if ($h) {
1740     if (($amount != 1) && $h->{"localized_plural"}) {
1741       $new_unit = $h->{"localized_plural"};
1742     } elsif ($h->{"localized"}) {
1743       $new_unit = $h->{"localized"};
1744     }
1745   }
1746
1747   $main::lxdebug->leave_sub();
1748
1749   return $new_unit;
1750 }
1751
1752 sub units_in_use {
1753   $main::lxdebug->enter_sub();
1754
1755   my ($self, $myconfig, $form, $units) = @_;
1756
1757   my $dbh = $form->dbconnect($myconfig);
1758
1759   map({ $_->{"in_use"} = 0; } values(%{$units}));
1760
1761   foreach my $unit (values(%{$units})) {
1762     my $base_unit = $unit->{"original_base_unit"};
1763     while ($base_unit) {
1764       $units->{$base_unit}->{"in_use"} = 1;
1765       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1766       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1767       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1768     }
1769   }
1770
1771   foreach my $unit (values(%{$units})) {
1772     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1773
1774     foreach my $table (qw(parts invoice orderitems)) {
1775       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1776
1777       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1778         $query .= "= " . $dbh->quote($unit->{"name"});
1779       } else {
1780         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1781           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1782       }
1783
1784       my ($count) = $dbh->selectrow_array($query);
1785       $form->dberror($query) if ($dbh->err);
1786
1787       if ($count) {
1788         $unit->{"in_use"} = 1;
1789         last;
1790       }
1791     }
1792   }
1793
1794   $dbh->disconnect();
1795
1796   $main::lxdebug->leave_sub();
1797 }
1798
1799 sub convertible_units {
1800   $main::lxdebug->enter_sub();
1801
1802   my $self        = shift;
1803   my $units       = shift;
1804   my $filter_unit = shift;
1805   my $not_smaller = shift;
1806
1807   my $conv_units = [];
1808
1809   $filter_unit = $units->{$filter_unit};
1810
1811   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1812     my $unit = $units->{$name};
1813
1814     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1815         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1816       push @{$conv_units}, $unit;
1817     }
1818   }
1819
1820   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1821
1822   $main::lxdebug->leave_sub();
1823
1824   return \@sorted;
1825 }
1826
1827 # if $a is translatable to $b, return the factor between them.
1828 # else return 1
1829 sub convert_unit {
1830   $main::lxdebug->enter_sub(2);
1831   my ($this, $a, $b, $all_units) = @_;
1832
1833   $main::lxdebug->leave_sub(2) and return 0 unless $a && $b;
1834   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1835   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1836   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor};
1837 }
1838
1839 sub unit_select_data {
1840   $main::lxdebug->enter_sub();
1841
1842   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1843
1844   my $select = [];
1845
1846   if ($empty_entry) {
1847     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1848   }
1849
1850   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1851     if (!$convertible_into ||
1852         ($units->{$convertible_into} &&
1853          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1854       push @{$select}, { "name"      => $unit,
1855                          "base_unit" => $units->{$unit}->{"base_unit"},
1856                          "factor"    => $units->{$unit}->{"factor"},
1857                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1858     }
1859   }
1860
1861   $main::lxdebug->leave_sub();
1862
1863   return $select;
1864 }
1865
1866 sub unit_select_html {
1867   $main::lxdebug->enter_sub();
1868
1869   my ($self, $units, $name, $selected, $convertible_into) = @_;
1870
1871   my $select = "<select name=${name}>";
1872
1873   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1874     if (!$convertible_into ||
1875         ($units->{$convertible_into} &&
1876          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1877       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1878     }
1879   }
1880   $select .= "</select>";
1881
1882   $main::lxdebug->leave_sub();
1883
1884   return $select;
1885 }
1886
1887 sub sum_with_unit {
1888   $main::lxdebug->enter_sub();
1889
1890   my $self  = shift;
1891
1892   my $units = $self->retrieve_all_units();
1893
1894   my $sum   = 0;
1895   my $base_unit;
1896
1897   while (2 <= scalar(@_)) {
1898     my $qty  = shift(@_);
1899     my $unit = $units->{shift(@_)};
1900
1901     croak "No unit defined with name $unit" if (!defined $unit);
1902
1903     if (!$base_unit) {
1904       $base_unit = $unit->{base_unit};
1905     } elsif ($base_unit ne $unit->{base_unit}) {
1906       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
1907     }
1908
1909     $sum += $qty * $unit->{factor};
1910   }
1911
1912   $main::lxdebug->leave_sub();
1913
1914   return wantarray ? ($sum, $base_unit) : $sum;
1915 }
1916
1917 sub add_unit {
1918   $main::lxdebug->enter_sub();
1919
1920   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
1921
1922   my $dbh = $form->dbconnect_noauto($myconfig);
1923
1924   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
1925   my ($sortkey) = selectrow_query($form, $dbh, $query);
1926
1927   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
1928     "VALUES (?, ?, ?, ?)";
1929   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
1930
1931   if ($languages) {
1932     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1933     my $sth = $dbh->prepare($query);
1934     foreach my $lang (@{$languages}) {
1935       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1936       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1937     }
1938     $sth->finish();
1939   }
1940
1941   $dbh->commit();
1942   $dbh->disconnect();
1943
1944   $main::lxdebug->leave_sub();
1945 }
1946
1947 sub save_units {
1948   $main::lxdebug->enter_sub();
1949
1950   my ($self, $myconfig, $form, $units, $delete_units) = @_;
1951
1952   my $dbh = $form->dbconnect_noauto($myconfig);
1953
1954   my ($base_unit, $unit, $sth, $query);
1955
1956   $query = "DELETE FROM units_language";
1957   $dbh->do($query) || $form->dberror($query);
1958
1959   if ($delete_units && (0 != scalar(@{$delete_units}))) {
1960     $query = "DELETE FROM units WHERE name IN (";
1961     map({ $query .= "?," } @{$delete_units});
1962     substr($query, -1, 1) = ")";
1963     $dbh->do($query, undef, @{$delete_units}) ||
1964       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
1965   }
1966
1967   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
1968   $sth = $dbh->prepare($query);
1969
1970   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
1971   my $sth_lang = $dbh->prepare($query_lang);
1972
1973   foreach $unit (values(%{$units})) {
1974     $unit->{"depth"} = 0;
1975     my $base_unit = $unit;
1976     while ($base_unit->{"base_unit"}) {
1977       $unit->{"depth"}++;
1978       $base_unit = $units->{$base_unit->{"base_unit"}};
1979     }
1980   }
1981
1982   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
1983     if ($unit->{"LANGUAGES"}) {
1984       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
1985         next unless ($lang->{"id"} && $lang->{"localized"});
1986         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
1987         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
1988       }
1989     }
1990
1991     next if ($unit->{"unchanged_unit"});
1992
1993     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
1994     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1995   }
1996
1997   $sth->finish();
1998   $sth_lang->finish();
1999   $dbh->commit();
2000   $dbh->disconnect();
2001
2002   $main::lxdebug->leave_sub();
2003 }
2004
2005 sub swap_units {
2006   $main::lxdebug->enter_sub();
2007
2008   my ($self, $myconfig, $form, $dir, $name_1) = @_;
2009
2010   my $dbh = $form->dbconnect_noauto($myconfig);
2011
2012   my $query;
2013
2014   $query = qq|SELECT sortkey FROM units WHERE name = ?|;
2015   my ($sortkey_1) = selectrow_query($form, $dbh, $query, $name_1);
2016
2017   $query =
2018     qq|SELECT sortkey FROM units | .
2019     qq|WHERE sortkey | . ($dir eq "down" ? ">" : "<") . qq| ? | .
2020     qq|ORDER BY sortkey | . ($dir eq "down" ? "ASC" : "DESC") . qq| LIMIT 1|;
2021   my ($sortkey_2) = selectrow_query($form, $dbh, $query, $sortkey_1);
2022
2023   if (defined($sortkey_1)) {
2024     $query = qq|SELECT name FROM units WHERE sortkey = ${sortkey_2}|;
2025     my ($name_2) = selectrow_query($form, $dbh, $query);
2026
2027     if (defined($name_2)) {
2028       $query = qq|UPDATE units SET sortkey = ? WHERE name = ?|;
2029       my $sth = $dbh->prepare($query);
2030
2031       do_statement($form, $sth, $query, $sortkey_1, $name_2);
2032       do_statement($form, $sth, $query, $sortkey_2, $name_1);
2033     }
2034   }
2035
2036   $dbh->commit();
2037   $dbh->disconnect();
2038
2039   $main::lxdebug->leave_sub();
2040 }
2041
2042 sub taxes {
2043   $main::lxdebug->enter_sub();
2044
2045   my ($self, $myconfig, $form) = @_;
2046
2047   # connect to database
2048   my $dbh = $form->dbconnect($myconfig);
2049
2050   my $query = qq|SELECT
2051                    t.id,
2052                    t.taxkey,
2053                    t.taxdescription,
2054                    round(t.rate * 100, 2) AS rate,
2055                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
2056                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
2057                  FROM tax t
2058                  ORDER BY taxkey|;
2059
2060   my $sth = $dbh->prepare($query);
2061   $sth->execute || $form->dberror($query);
2062
2063   $form->{TAX} = [];
2064   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2065     push @{ $form->{TAX} }, $ref;
2066   }
2067
2068   $sth->finish;
2069   $dbh->disconnect;
2070
2071   $main::lxdebug->leave_sub();
2072 }
2073
2074 sub get_tax_accounts {
2075   $main::lxdebug->enter_sub();
2076
2077   my ($self, $myconfig, $form) = @_;
2078
2079   my $dbh = $form->dbconnect($myconfig);
2080
2081   # get Accounts from chart
2082   my $query = qq{ SELECT
2083                  id,
2084                  accno || ' - ' || description AS taxaccount
2085                FROM chart
2086                WHERE link LIKE '%_tax%'
2087                ORDER BY accno
2088              };
2089
2090   my $sth = $dbh->prepare($query);
2091   $sth->execute || $form->dberror($query);
2092
2093   $form->{ACCOUNTS} = [];
2094   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2095     push @{ $form->{ACCOUNTS} }, $ref;
2096   }
2097
2098   $sth->finish;
2099
2100   $dbh->disconnect;
2101
2102   $main::lxdebug->leave_sub();
2103 }
2104
2105 sub get_tax {
2106   $main::lxdebug->enter_sub();
2107
2108   my ($self, $myconfig, $form) = @_;
2109
2110   # connect to database
2111   my $dbh = $form->dbconnect($myconfig);
2112
2113   my $query = qq|SELECT
2114                    taxkey,
2115                    taxdescription,
2116                    round(rate * 100, 2) AS rate,
2117                    chart_id
2118                  FROM tax
2119                  WHERE id = ? |;
2120
2121   my $sth = $dbh->prepare($query);
2122   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2123
2124   my $ref = $sth->fetchrow_hashref("NAME_lc");
2125
2126   map { $form->{$_} = $ref->{$_} } keys %$ref;
2127
2128   $sth->finish;
2129
2130   # see if it is used by a taxkey
2131   $query = qq|SELECT count(*) FROM taxkeys
2132               WHERE tax_id = ? AND chart_id >0|;
2133
2134   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
2135
2136   $form->{orphaned} = !$form->{orphaned};
2137   $sth->finish;
2138
2139   if (!$form->{orphaned} ) {
2140     $query = qq|SELECT DISTINCT c.id, c.accno
2141                 FROM taxkeys tk
2142                 JOIN   tax t ON (t.id = tk.tax_id)
2143                 JOIN chart c ON (c.id = tk.chart_id)
2144                 WHERE tk.tax_id = ?|;
2145
2146     $sth = $dbh->prepare($query);
2147     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2148
2149     $form->{TAXINUSE} = [];
2150     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2151       push @{ $form->{TAXINUSE} }, $ref;
2152     }
2153
2154     $sth->finish;
2155   }
2156
2157   $dbh->disconnect;
2158
2159   $main::lxdebug->leave_sub();
2160 }
2161
2162 sub save_tax {
2163   $main::lxdebug->enter_sub();
2164
2165   my ($self, $myconfig, $form) = @_;
2166   my $query;
2167
2168   # connect to database
2169   my $dbh = $form->get_standard_dbh($myconfig);
2170
2171   $form->{rate} = $form->{rate} / 100;
2172
2173   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
2174   if ($form->{id} ne "") {
2175     $query = qq|UPDATE tax SET
2176                   taxkey         = ?,
2177                   taxdescription = ?,
2178                   rate           = ?,
2179                   chart_id       = ?,
2180                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
2181                 WHERE id = ?|;
2182     push(@values, $form->{id});
2183
2184   } else {
2185     #ok
2186     $query = qq|INSERT INTO tax (
2187                   taxkey,
2188                   taxdescription,
2189                   rate,
2190                   chart_id,
2191                   taxnumber
2192                 )
2193                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
2194   }
2195   do_query($form, $dbh, $query, @values);
2196
2197   $dbh->commit();
2198
2199   $main::lxdebug->leave_sub();
2200 }
2201
2202 sub delete_tax {
2203   $main::lxdebug->enter_sub();
2204
2205   my ($self, $myconfig, $form) = @_;
2206   my $query;
2207
2208   # connect to database
2209   my $dbh = $form->get_standard_dbh($myconfig);
2210
2211   $query = qq|DELETE FROM tax
2212               WHERE id = ?|;
2213   do_query($form, $dbh, $query, $form->{id});
2214
2215   $dbh->commit();
2216
2217   $main::lxdebug->leave_sub();
2218 }
2219
2220 sub save_price_factor {
2221   $main::lxdebug->enter_sub();
2222
2223   my ($self, $myconfig, $form) = @_;
2224
2225   # connect to database
2226   my $dbh = $form->get_standard_dbh($myconfig);
2227
2228   my $query;
2229   my @values = ($form->{description}, conv_i($form->{factor}));
2230
2231   if ($form->{id}) {
2232     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
2233     push @values, conv_i($form->{id});
2234
2235   } else {
2236     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
2237   }
2238
2239   do_query($form, $dbh, $query, @values);
2240
2241   $dbh->commit();
2242
2243   $main::lxdebug->leave_sub();
2244 }
2245
2246 sub get_all_price_factors {
2247   $main::lxdebug->enter_sub();
2248
2249   my ($self, $myconfig, $form) = @_;
2250
2251   # connect to database
2252   my $dbh = $form->get_standard_dbh($myconfig);
2253
2254   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
2255
2256   $main::lxdebug->leave_sub();
2257 }
2258
2259 sub get_price_factor {
2260   $main::lxdebug->enter_sub();
2261
2262   my ($self, $myconfig, $form) = @_;
2263
2264   # connect to database
2265   my $dbh = $form->get_standard_dbh($myconfig);
2266
2267   my $query = qq|SELECT description, factor,
2268                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
2269                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
2270                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
2271                  FROM price_factors WHERE id = ?|;
2272
2273   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
2274
2275   $main::lxdebug->leave_sub();
2276 }
2277
2278 sub delete_price_factor {
2279   $main::lxdebug->enter_sub();
2280
2281   my ($self, $myconfig, $form) = @_;
2282
2283   # connect to database
2284   my $dbh = $form->get_standard_dbh($myconfig);
2285
2286   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
2287   $dbh->commit();
2288
2289   $main::lxdebug->leave_sub();
2290 }
2291
2292 sub save_warehouse {
2293   $main::lxdebug->enter_sub();
2294
2295   my ($self, $myconfig, $form) = @_;
2296
2297   # connect to database
2298   my $dbh = $form->get_standard_dbh($myconfig);
2299
2300   my ($query, @values, $sth);
2301
2302   if (!$form->{id}) {
2303     $query        = qq|SELECT nextval('id')|;
2304     ($form->{id}) = selectrow_query($form, $dbh, $query);
2305
2306     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
2307     do_query($form, $dbh, $query, $form->{id});
2308   }
2309
2310   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
2311            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
2312
2313   if (0 < $form->{number_of_new_bins}) {
2314     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
2315     $sth   = prepare_query($form, $dbh, $query);
2316
2317     foreach my $i (1..$form->{number_of_new_bins}) {
2318       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
2319     }
2320
2321     $sth->finish();
2322   }
2323
2324   $dbh->commit();
2325
2326   $main::lxdebug->leave_sub();
2327 }
2328
2329 sub save_bins {
2330   $main::lxdebug->enter_sub();
2331
2332   my ($self, $myconfig, $form) = @_;
2333
2334   # connect to database
2335   my $dbh = $form->get_standard_dbh($myconfig);
2336
2337   my ($query, @values, $commit_necessary, $sth);
2338
2339   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
2340
2341   if (@values) {
2342     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
2343     do_query($form, $dbh, $query, @values);
2344
2345     $commit_necessary = 1;
2346   }
2347
2348   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
2349   $sth   = prepare_query($form, $dbh, $query);
2350
2351   foreach my $row (1..$form->{rowcount}) {
2352     next if ($form->{"delete_${row}"});
2353
2354     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
2355
2356     $commit_necessary = 1;
2357   }
2358
2359   $sth->finish();
2360
2361   $dbh->commit() if ($commit_necessary);
2362
2363   $main::lxdebug->leave_sub();
2364 }
2365
2366 sub delete_warehouse {
2367   $main::lxdebug->enter_sub();
2368
2369   my ($self, $myconfig, $form) = @_;
2370
2371   # connect to database
2372   my $dbh = $form->get_standard_dbh($myconfig);
2373
2374   my $id      = conv_i($form->{id});
2375   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|;
2376   my ($count) = selectrow_query($form, $dbh, $query, $id);
2377
2378   if ($count) {
2379     $main::lxdebug->leave_sub();
2380     return 0;
2381   }
2382
2383   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2384   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2385
2386   $dbh->commit();
2387
2388   $main::lxdebug->leave_sub();
2389
2390   return 1;
2391 }
2392
2393 sub get_all_warehouses {
2394   $main::lxdebug->enter_sub();
2395
2396   my ($self, $myconfig, $form) = @_;
2397
2398   # connect to database
2399   my $dbh = $form->get_standard_dbh($myconfig);
2400
2401   my $query = qq|SELECT w.id, w.description, w.invalid,
2402                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2403                  FROM warehouse w
2404                  ORDER BY w.sortkey|;
2405
2406   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2407
2408   $main::lxdebug->leave_sub();
2409 }
2410
2411 sub get_warehouse {
2412   $main::lxdebug->enter_sub();
2413
2414   my ($self, $myconfig, $form) = @_;
2415
2416   # connect to database
2417   my $dbh = $form->get_standard_dbh($myconfig);
2418
2419   my $id    = conv_i($form->{id});
2420   my $query = qq|SELECT w.description, w.invalid
2421                  FROM warehouse w
2422                  WHERE w.id = ?|;
2423
2424   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2425
2426   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2427
2428   $query = qq|SELECT b.*, EXISTS
2429                 (SELECT i.warehouse_id
2430                  FROM inventory i
2431                  WHERE i.bin_id = b.id
2432                  LIMIT 1)
2433                 AS in_use
2434               FROM bin b
2435               WHERE b.warehouse_id = ?|;
2436
2437   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2438
2439   $main::lxdebug->leave_sub();
2440 }
2441
2442 1;