Lagerverwaltung implementiert.
[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, $type, $prefix) = @_;
1780
1781   my $dbh = $form->dbconnect($myconfig);
1782
1783   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1784   my @values;
1785   if ($type) {
1786     $query .= " WHERE (type = ?)";
1787     @values = ($type);
1788   }
1789
1790   my $sth = $dbh->prepare($query);
1791   $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
1792
1793   my $units = {};
1794   while (my $ref = $sth->fetchrow_hashref()) {
1795     $units->{$ref->{"name"}} = $ref;
1796   }
1797   $sth->finish();
1798
1799   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1800   $sth = $dbh->prepare($query_lang);
1801   $sth->execute() || $form->dberror($query_lang);
1802   my @languages;
1803   while ($ref = $sth->fetchrow_hashref()) {
1804     push(@languages, $ref);
1805   }
1806   $sth->finish();
1807
1808   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1809     "FROM units_language ul " .
1810     "LEFT JOIN language l ON ul.language_id = l.id " .
1811     "WHERE ul.unit = ?";
1812   $sth = $dbh->prepare($query_lang);
1813
1814   foreach my $unit (values(%{$units})) {
1815     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1816
1817     $unit->{"LANGUAGES"} = {};
1818     foreach my $lang (@languages) {
1819       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1820     }
1821
1822     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1823     while ($ref = $sth->fetchrow_hashref()) {
1824       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1825     }
1826   }
1827   $sth->finish();
1828
1829   $dbh->disconnect();
1830
1831   $main::lxdebug->leave_sub();
1832
1833   return $units;
1834 }
1835
1836 sub retrieve_all_units {
1837   $main::lxdebug->enter_sub();
1838
1839   my $self = shift;
1840
1841   if (!$main::all_units) {
1842     $main::all_units = $self->retrieve_units(\%main::myconfig, $main::form);
1843   }
1844
1845   $main::lxdebug->leave_sub();
1846
1847   return $main::all_units;
1848 }
1849
1850
1851 sub translate_units {
1852   $main::lxdebug->enter_sub();
1853
1854   my ($self, $form, $template_code, $unit, $amount) = @_;
1855
1856   my $units = $self->retrieve_units(\%main::myconfig, $form);
1857
1858   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1859   my $new_unit = $unit;
1860   if ($h) {
1861     if (($amount != 1) && $h->{"localized_plural"}) {
1862       $new_unit = $h->{"localized_plural"};
1863     } elsif ($h->{"localized"}) {
1864       $new_unit = $h->{"localized"};
1865     }
1866   }
1867
1868   $main::lxdebug->leave_sub();
1869
1870   return $new_unit;
1871 }
1872
1873 sub units_in_use {
1874   $main::lxdebug->enter_sub();
1875
1876   my ($self, $myconfig, $form, $units) = @_;
1877
1878   my $dbh = $form->dbconnect($myconfig);
1879
1880   map({ $_->{"in_use"} = 0; } values(%{$units}));
1881
1882   foreach my $unit (values(%{$units})) {
1883     my $base_unit = $unit->{"original_base_unit"};
1884     while ($base_unit) {
1885       $units->{$base_unit}->{"in_use"} = 1;
1886       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1887       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1888       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1889     }
1890   }
1891
1892   foreach my $unit (values(%{$units})) {
1893     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1894
1895     foreach my $table (qw(parts invoice orderitems)) {
1896       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1897
1898       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1899         $query .= "= " . $dbh->quote($unit->{"name"});
1900       } else {
1901         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1902           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1903       }
1904
1905       my ($count) = $dbh->selectrow_array($query);
1906       $form->dberror($query) if ($dbh->err);
1907
1908       if ($count) {
1909         $unit->{"in_use"} = 1;
1910         last;
1911       }
1912     }
1913   }
1914
1915   $dbh->disconnect();
1916
1917   $main::lxdebug->leave_sub();
1918 }
1919
1920 sub convertible_units {
1921   $main::lxdebug->enter_sub();
1922
1923   my $self        = shift;
1924   my $units       = shift;
1925   my $filter_unit = shift;
1926   my $not_smaller = shift;
1927
1928   my $conv_units = [];
1929
1930   $filter_unit = $units->{$filter_unit};
1931
1932   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1933     my $unit = $units->{$name};
1934
1935     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1936         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1937       push @{$conv_units}, $unit;
1938     }
1939   }
1940
1941   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1942
1943   $main::lxdebug->leave_sub();
1944
1945   return \@sorted;
1946 }
1947
1948 # if $a is translatable to $b, return the factor between them.
1949 # else return 1
1950 sub convert_unit {
1951   $main::lxdebug->enter_sub(2);
1952   ($this, $a, $b, $all_units) = @_;
1953
1954   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1955   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1956   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor}; 
1957 }
1958
1959 sub unit_select_data {
1960   $main::lxdebug->enter_sub();
1961
1962   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1963
1964   my $select = [];
1965
1966   if ($empty_entry) {
1967     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1968   }
1969
1970   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1971     if (!$convertible_into ||
1972         ($units->{$convertible_into} &&
1973          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1974       push @{$select}, { "name"      => $unit,
1975                          "base_unit" => $units->{$unit}->{"base_unit"},
1976                          "factor"    => $units->{$unit}->{"factor"},
1977                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1978     }
1979   }
1980
1981   $main::lxdebug->leave_sub();
1982
1983   return $select;
1984 }
1985
1986 sub unit_select_html {
1987   $main::lxdebug->enter_sub();
1988
1989   my ($self, $units, $name, $selected, $convertible_into) = @_;
1990
1991   my $select = "<select name=${name}>";
1992
1993   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1994     if (!$convertible_into ||
1995         ($units->{$convertible_into} &&
1996          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1997       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1998     }
1999   }
2000   $select .= "</select>";
2001
2002   $main::lxdebug->leave_sub();
2003
2004   return $select;
2005 }
2006
2007 sub sum_with_unit {
2008   $main::lxdebug->enter_sub();
2009
2010   my $self  = shift;
2011
2012   my $units = $self->retrieve_all_units();
2013
2014   my $sum   = 0;
2015   my $base_unit;
2016
2017   while (2 <= scalar(@_)) {
2018     my $qty  = shift(@_);
2019     my $unit = $units->{shift(@_)};
2020
2021     croak "No unit defined with name $unit" if (!defined $unit);
2022
2023     if (!$base_unit) {
2024       $base_unit = $unit->{base_unit};
2025     } elsif ($base_unit ne $unit->{base_unit}) {
2026       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
2027     }
2028
2029     $sum += $qty * $unit->{factor};
2030   }
2031
2032   $main::lxdebug->leave_sub();
2033
2034   return wantarray ? ($sum, $baseunit) : $sum;
2035 }
2036
2037 sub add_unit {
2038   $main::lxdebug->enter_sub();
2039
2040   my ($self, $myconfig, $form, $name, $base_unit, $factor, $type, $languages) = @_;
2041
2042   my $dbh = $form->dbconnect_noauto($myconfig);
2043
2044   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
2045   my ($sortkey) = selectrow_query($form, $dbh, $query);
2046
2047   $query = "INSERT INTO units (name, base_unit, factor, type, sortkey) " .
2048     "VALUES (?, ?, ?, ?, ?)";
2049   do_query($form, $dbh, $query, $name, $base_unit, $factor, $type, $sortkey);
2050
2051   if ($languages) {
2052     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
2053     my $sth = $dbh->prepare($query);
2054     foreach my $lang (@{$languages}) {
2055       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
2056       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
2057     }
2058     $sth->finish();
2059   }
2060
2061   $dbh->commit();
2062   $dbh->disconnect();
2063
2064   $main::lxdebug->leave_sub();
2065 }
2066
2067 sub save_units {
2068   $main::lxdebug->enter_sub();
2069
2070   my ($self, $myconfig, $form, $type, $units, $delete_units) = @_;
2071
2072   my $dbh = $form->dbconnect_noauto($myconfig);
2073
2074   my ($base_unit, $unit, $sth, $query);
2075
2076   $query = "DELETE FROM units_language";
2077   $dbh->do($query) || $form->dberror($query);
2078
2079   if ($delete_units && (0 != scalar(@{$delete_units}))) {
2080     $query = "DELETE FROM units WHERE name IN (";
2081     map({ $query .= "?," } @{$delete_units});
2082     substr($query, -1, 1) = ")";
2083     $dbh->do($query, undef, @{$delete_units}) ||
2084       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
2085   }
2086
2087   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
2088   $sth = $dbh->prepare($query);
2089
2090   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
2091   my $sth_lang = $dbh->prepare($query_lang);
2092
2093   foreach $unit (values(%{$units})) {
2094     $unit->{"depth"} = 0;
2095     my $base_unit = $unit;
2096     while ($base_unit->{"base_unit"}) {
2097       $unit->{"depth"}++;
2098       $base_unit = $units->{$base_unit->{"base_unit"}};
2099     }
2100   }
2101
2102   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
2103     if ($unit->{"LANGUAGES"}) {
2104       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
2105         next unless ($lang->{"id"} && $lang->{"localized"});
2106         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
2107         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
2108       }
2109     }
2110
2111     next if ($unit->{"unchanged_unit"});
2112
2113     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
2114     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
2115   }
2116
2117   $sth->finish();
2118   $sth_lang->finish();
2119   $dbh->commit();
2120   $dbh->disconnect();
2121
2122   $main::lxdebug->leave_sub();
2123 }
2124
2125 sub swap_units {
2126   $main::lxdebug->enter_sub();
2127
2128   my ($self, $myconfig, $form, $dir, $name_1, $unit_type) = @_;
2129
2130   my $dbh = $form->dbconnect_noauto($myconfig);
2131
2132   my $query;
2133
2134   $query = qq|SELECT sortkey FROM units WHERE name = ?|;
2135   my ($sortkey_1) = selectrow_query($form, $dbh, $query, $name_1);
2136
2137   $query =
2138     qq|SELECT sortkey FROM units | .
2139     qq|WHERE sortkey | . ($dir eq "down" ? ">" : "<") . qq| ? AND type = ? | .
2140     qq|ORDER BY sortkey | . ($dir eq "down" ? "ASC" : "DESC") . qq| LIMIT 1|;
2141   my ($sortkey_2) = selectrow_query($form, $dbh, $query, $sortkey_1, $unit_type);
2142
2143   if (defined($sortkey_1)) {
2144     $query = qq|SELECT name FROM units WHERE sortkey = ${sortkey_2}|;
2145     my ($name_2) = selectrow_query($form, $dbh, $query);
2146
2147     if (defined($name_2)) {
2148       $query = qq|UPDATE units SET sortkey = ? WHERE name = ?|;
2149       my $sth = $dbh->prepare($query);
2150
2151       do_statement($form, $sth, $query, $sortkey_1, $name_2);
2152       do_statement($form, $sth, $query, $sortkey_2, $name_1);
2153     }
2154   }
2155
2156   $dbh->commit();
2157   $dbh->disconnect();
2158
2159   $main::lxdebug->leave_sub();
2160 }
2161
2162 sub taxes {
2163   $main::lxdebug->enter_sub();
2164
2165   my ($self, $myconfig, $form) = @_;
2166
2167   # connect to database
2168   my $dbh = $form->dbconnect($myconfig);
2169
2170   my $query = qq|SELECT
2171                    t.id,
2172                    t.taxkey,
2173                    t.taxdescription,
2174                    round(t.rate * 100, 2) AS rate,
2175                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
2176                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
2177                  FROM tax t
2178                  ORDER BY taxkey|;
2179
2180   $sth = $dbh->prepare($query);
2181   $sth->execute || $form->dberror($query);
2182
2183   $form->{TAX} = [];
2184   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2185     push @{ $form->{TAX} }, $ref;
2186   }
2187
2188   $sth->finish;
2189   $dbh->disconnect;
2190
2191   $main::lxdebug->leave_sub();
2192 }
2193
2194 sub get_tax_accounts {
2195   $main::lxdebug->enter_sub();
2196
2197   my ($self, $myconfig, $form) = @_;
2198
2199   my $dbh = $form->dbconnect($myconfig);
2200
2201   # get Accounts from chart
2202   my $query = qq{ SELECT
2203                  id,
2204                  accno || ' - ' || description AS taxaccount
2205                FROM chart
2206                WHERE link LIKE '%_tax%'
2207                ORDER BY accno
2208              };
2209
2210   $sth = $dbh->prepare($query);
2211   $sth->execute || $form->dberror($query);
2212
2213   $form->{ACCOUNTS} = [];
2214   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2215     push @{ $form->{ACCOUNTS} }, $ref;
2216   }
2217
2218   $sth->finish;
2219
2220   $dbh->disconnect;
2221
2222   $main::lxdebug->leave_sub();
2223 }
2224
2225 sub get_tax {
2226   $main::lxdebug->enter_sub();
2227
2228   my ($self, $myconfig, $form) = @_;
2229
2230   # connect to database
2231   my $dbh = $form->dbconnect($myconfig);
2232
2233   my $query = qq|SELECT
2234                    taxkey,
2235                    taxdescription,
2236                    round(rate * 100, 2) AS rate,
2237                    chart_id
2238                  FROM tax
2239                  WHERE id = ? |;
2240
2241   my $sth = $dbh->prepare($query);
2242   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2243
2244   my $ref = $sth->fetchrow_hashref(NAME_lc);
2245
2246   map { $form->{$_} = $ref->{$_} } keys %$ref;
2247
2248   $sth->finish;
2249
2250   # see if it is used by a taxkey
2251   $query = qq|SELECT count(*) FROM taxkeys
2252               WHERE tax_id = ? AND chart_id >0|;
2253
2254   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
2255
2256   $form->{orphaned} = !$form->{orphaned};
2257   $sth->finish;
2258
2259   if (!$form->{orphaned} ) {
2260     $query = qq|SELECT DISTINCT c.id, c.accno
2261                 FROM taxkeys tk
2262                 JOIN   tax t ON (t.id = tk.tax_id)
2263                 JOIN chart c ON (c.id = tk.chart_id)
2264                 WHERE tk.tax_id = ?|;
2265
2266     $sth = $dbh->prepare($query);
2267     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2268
2269     $form->{TAXINUSE} = [];
2270     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2271       push @{ $form->{TAXINUSE} }, $ref;
2272     }
2273
2274     $sth->finish;
2275   }
2276
2277   $dbh->disconnect;
2278
2279   $main::lxdebug->leave_sub();
2280 }
2281
2282 sub save_tax {
2283   $main::lxdebug->enter_sub();
2284
2285   my ($self, $myconfig, $form) = @_;
2286
2287   # connect to database
2288   my $dbh = $form->get_standard_dbh($myconfig);
2289
2290   $form->{rate} = $form->{rate} / 100;
2291
2292   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
2293   if ($form->{id} ne "") {
2294     $query = qq|UPDATE tax SET
2295                   taxkey         = ?,
2296                   taxdescription = ?,
2297                   rate           = ?,
2298                   chart_id       = ?,
2299                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
2300                 WHERE id = ?|;
2301     push(@values, $form->{id});
2302
2303   } else {
2304     #ok
2305     $query = qq|INSERT INTO tax (
2306                   taxkey,
2307                   taxdescription,
2308                   rate,
2309                   chart_id,
2310                   taxnumber
2311                 )
2312                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
2313   }
2314   do_query($form, $dbh, $query, @values);
2315
2316   $dbh->commit();
2317
2318   $main::lxdebug->leave_sub();
2319 }
2320
2321 sub delete_tax {
2322   $main::lxdebug->enter_sub();
2323
2324   my ($self, $myconfig, $form) = @_;
2325
2326   # connect to database
2327   my $dbh = $form->get_standard_dbh($myconfig);
2328
2329   $query = qq|DELETE FROM tax
2330               WHERE id = ?|;
2331   do_query($form, $dbh, $query, $form->{id});
2332
2333   $dbh->commit();
2334
2335   $main::lxdebug->leave_sub();
2336 }
2337
2338 sub save_price_factor {
2339   $main::lxdebug->enter_sub();
2340
2341   my ($self, $myconfig, $form) = @_;
2342
2343   # connect to database
2344   my $dbh = $form->get_standard_dbh($myconfig);
2345
2346   my $query;
2347   my @values = ($form->{description}, conv_i($form->{factor}));
2348
2349   if ($form->{id}) {
2350     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
2351     push @values, conv_i($form->{id});
2352
2353   } else {
2354     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
2355   }
2356
2357   do_query($form, $dbh, $query, @values);
2358
2359   $dbh->commit();
2360
2361   $main::lxdebug->leave_sub();
2362 }
2363
2364 sub get_all_price_factors {
2365   $main::lxdebug->enter_sub();
2366
2367   my ($self, $myconfig, $form) = @_;
2368
2369   # connect to database
2370   my $dbh = $form->get_standard_dbh($myconfig);
2371
2372   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
2373
2374   $main::lxdebug->leave_sub();
2375 }
2376
2377 sub get_price_factor {
2378   $main::lxdebug->enter_sub();
2379
2380   my ($self, $myconfig, $form) = @_;
2381
2382   # connect to database
2383   my $dbh = $form->get_standard_dbh($myconfig);
2384
2385   my $query = qq|SELECT description, factor,
2386                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
2387                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
2388                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
2389                  FROM price_factors WHERE id = ?|;
2390
2391   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
2392
2393   $main::lxdebug->leave_sub();
2394 }
2395
2396 sub delete_price_factor {
2397   $main::lxdebug->enter_sub();
2398
2399   my ($self, $myconfig, $form) = @_;
2400
2401   # connect to database
2402   my $dbh = $form->get_standard_dbh($myconfig);
2403
2404   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
2405   $dbh->commit();
2406
2407   $main::lxdebug->leave_sub();
2408 }
2409
2410 sub save_warehouse {
2411   $main::lxdebug->enter_sub();
2412
2413   my ($self, $myconfig, $form) = @_;
2414
2415   # connect to database
2416   my $dbh = $form->get_standard_dbh($myconfig);
2417
2418   my ($query, @values, $sth);
2419
2420   if (!$form->{id}) {
2421     $query        = qq|SELECT nextval('id')|;
2422     ($form->{id}) = selectrow_query($form, $dbh, $query);
2423
2424     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
2425     do_query($form, $dbh, $query, $form->{id});
2426   }
2427
2428   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
2429            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
2430
2431   if (0 < $form->{number_of_new_bins}) {
2432     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
2433     $sth   = prepare_query($form, $dbh, $query);
2434
2435     foreach my $i (1..$form->{number_of_new_bins}) {
2436       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
2437     }
2438
2439     $sth->finish();
2440   }
2441
2442   $dbh->commit();
2443
2444   $main::lxdebug->leave_sub();
2445 }
2446
2447 sub save_bins {
2448   $main::lxdebug->enter_sub();
2449
2450   my ($self, $myconfig, $form) = @_;
2451
2452   # connect to database
2453   my $dbh = $form->get_standard_dbh($myconfig);
2454
2455   my ($query, @values, $commit_necessary, $sth);
2456
2457   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
2458
2459   if (@values) {
2460     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
2461     do_query($form, $dbh, $query, @values);
2462
2463     $commit_necessary = 1;
2464   }
2465
2466   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
2467   $sth   = prepare_query($form, $dbh, $query);
2468
2469   foreach my $row (1..$form->{rowcount}) {
2470     next if ($form->{"delete_${row}"});
2471
2472     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
2473
2474     $commit_necessary = 1;
2475   }
2476
2477   $sth->finish();
2478
2479   $dbh->commit() if ($commit_necessary);
2480
2481   $main::lxdebug->leave_sub();
2482 }
2483
2484 sub delete_warehouse {
2485   $main::lxdebug->enter_sub();
2486
2487   my ($self, $myconfig, $form) = @_;
2488
2489   # connect to database
2490   my $dbh = $form->get_standard_dbh($myconfig);
2491
2492   my $id      = conv_i($form->{id});
2493   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|;
2494   my ($count) = selectrow_query($form, $dbh, $query, $id);
2495
2496   if ($count) {
2497     $main::lxdebug->leave_sub();
2498     return 0;
2499   }
2500
2501   do_query($form, $dbh, qq|DELETE FROM warehouse_access WHERE warehouse_id = ?|, conv_i($form->{id}));
2502   do_query($form, $dbh, qq|DELETE FROM bin              WHERE warehouse_id = ?|, conv_i($form->{id}));
2503   do_query($form, $dbh, qq|DELETE FROM warehouse        WHERE id           = ?|, conv_i($form->{id}));
2504
2505   $dbh->commit();
2506
2507   $main::lxdebug->leave_sub();
2508
2509   return 1;
2510 }
2511
2512 sub get_all_warehouses {
2513   $main::lxdebug->enter_sub();
2514
2515   my ($self, $myconfig, $form) = @_;
2516
2517   # connect to database
2518   my $dbh = $form->get_standard_dbh($myconfig);
2519
2520   my $query = qq|SELECT w.id, w.description, w.invalid
2521                  FROM warehouse w
2522                  ORDER BY w.sortkey|;
2523
2524   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2525
2526   $main::lxdebug->leave_sub();
2527 }
2528
2529 sub get_warehouse {
2530   $main::lxdebug->enter_sub();
2531
2532   my ($self, $myconfig, $form) = @_;
2533
2534   # connect to database
2535   my $dbh = $form->get_standard_dbh($myconfig);
2536
2537   my $id    = conv_i($form->{id});
2538   my $query = qq|SELECT w.description, w.invalid
2539                  FROM warehouse w
2540                  WHERE w.id = ?|;
2541
2542   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id, $id);
2543
2544   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2545
2546   $query = qq|SELECT b.*, EXISTS
2547                 (SELECT i.warehouse_id
2548                  FROM inventory i
2549                  WHERE i.bin_id = b.id
2550                  LIMIT 1)
2551                 AS in_use
2552               FROM bin b
2553               WHERE b.warehouse_id = ?|;
2554
2555   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2556
2557   $main::lxdebug->leave_sub();
2558 }
2559
2560 1;