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