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