Sortierung in Berichten über Kunden und Lieferanten auch auf- und absteigbar sortierb...
[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         sdonumber          = ?,
1510         pdonumber          = ?,
1511         yearend            = ?,
1512         curr               = ?,
1513         businessnumber     = ?|;
1514   my @values = ($accnos{inventory_accno}, $accnos{income_accno}, $accnos{expense_accno},
1515                 $accnos{fxgain_accno},    $accnos{fxloss_accno},
1516                 $form->{invnumber},       $form->{cnnumber},
1517                 $form->{sonumber},        $form->{ponumber},
1518                 $form->{sqnumber},        $form->{rfqnumber},
1519                 $form->{customernumber},  $form->{vendornumber},
1520                 $form->{articlenumber},   $form->{servicenumber},
1521                 $form->{sdonumber},       $form->{pdonumber},
1522                 $form->{yearend},         $currency,
1523                 $form->{businessnumber});
1524   do_query($form, $dbh, $query, @values);
1525
1526   $dbh->commit();
1527
1528   $main::lxdebug->leave_sub();
1529 }
1530
1531
1532 sub save_preferences {
1533   $main::lxdebug->enter_sub();
1534
1535   my ($self, $myconfig, $form, $webdav) = @_;
1536
1537   my $dbh = $form->get_standard_dbh($myconfig);
1538
1539   my ($currency, $businessnumber) = selectrow_query($form, $dbh, qq|SELECT curr, businessnumber FROM defaults|);
1540
1541   # update name
1542   my $query = qq|UPDATE employee SET name = ? WHERE login = ?|;
1543   do_query($form, $dbh, $query, $form->{name}, $form->{login});
1544
1545   my $rc = $dbh->commit();
1546
1547   # save first currency in myconfig
1548   $currency               =~ s/:.*//;
1549   $form->{currency}       =  $currency;
1550
1551   $form->{businessnumber} =  $businessnumber;
1552
1553   my $myconfig = new User($form->{login});
1554
1555   foreach my $item (keys %$form) {
1556     $myconfig->{$item} = $form->{$item};
1557   }
1558
1559   $myconfig->save_member($memberfile);
1560
1561   my $auth = $main::auth;
1562
1563   if ($auth->can_change_password()
1564       && defined $form->{new_password}
1565       && ($form->{new_password} ne '********')) {
1566     $auth->change_password($form->{login}, $form->{new_password});
1567
1568     $form->{password} = $form->{new_password};
1569     $auth->set_session_value('password', $form->{password});
1570     $auth->create_or_refresh_session();
1571   }
1572
1573   if ($webdav) {
1574     @webdavdirs =
1575       qw(angebote bestellungen rechnungen anfragen lieferantenbestellungen einkaufsrechnungen);
1576     foreach $directory (@webdavdirs) {
1577       $file = "webdav/" . $directory . "/webdav-user";
1578       if ($myconfig->{$directory}) {
1579         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1580         while (<HTACCESS>) {
1581           ($login, $password) = split(/:/, $_);
1582           if ($login ne $form->{login}) {
1583             $newfile .= $_;
1584           }
1585         }
1586         close(HTACCESS);
1587         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1588         $newfile .= $myconfig->{login} . ":" . $myconfig->{password} . "\n";
1589         print(HTACCESS $newfile);
1590         close(HTACCESS);
1591       } else {
1592         $form->{$directory} = 0;
1593         open(HTACCESS, "$file") or die "cannot open webdav-user $!\n";
1594         while (<HTACCESS>) {
1595           ($login, $password) = split(/:/, $_);
1596           if ($login ne $form->{login}) {
1597             $newfile .= $_;
1598           }
1599         }
1600         close(HTACCESS);
1601         open(HTACCESS, "> $file") or die "cannot open webdav-user $!\n";
1602         print(HTACCESS $newfile);
1603         close(HTACCESS);
1604       }
1605     }
1606   }
1607
1608   $main::lxdebug->leave_sub();
1609
1610   return $rc;
1611 }
1612
1613 sub defaultaccounts {
1614   $main::lxdebug->enter_sub();
1615
1616   my ($self, $myconfig, $form) = @_;
1617
1618   # connect to database
1619   my $dbh = $form->dbconnect($myconfig);
1620
1621   # get defaults from defaults table
1622   my $query = qq|SELECT * FROM defaults|;
1623   my $sth   = $dbh->prepare($query);
1624   $sth->execute || $form->dberror($query);
1625
1626   $form->{defaults}             = $sth->fetchrow_hashref(NAME_lc);
1627   $form->{defaults}{IC}         = $form->{defaults}{inventory_accno_id};
1628   $form->{defaults}{IC_income}  = $form->{defaults}{income_accno_id};
1629   $form->{defaults}{IC_expense} = $form->{defaults}{expense_accno_id};
1630   $form->{defaults}{FX_gain}    = $form->{defaults}{fxgain_accno_id};
1631   $form->{defaults}{FX_loss}    = $form->{defaults}{fxloss_accno_id};
1632
1633   $sth->finish;
1634
1635   $query = qq|SELECT c.id, c.accno, c.description, c.link
1636               FROM chart c
1637               WHERE c.link LIKE '%IC%'
1638               ORDER BY c.accno|;
1639   $sth = $dbh->prepare($query);
1640   $sth->execute || $self->dberror($query);
1641
1642   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1643     foreach my $key (split(/:/, $ref->{link})) {
1644       if ($key =~ /IC/) {
1645         $nkey = $key;
1646         if ($key =~ /cogs/) {
1647           $nkey = "IC_expense";
1648         }
1649         if ($key =~ /sale/) {
1650           $nkey = "IC_income";
1651         }
1652         %{ $form->{IC}{$nkey}{ $ref->{accno} } } = (
1653                                              id          => $ref->{id},
1654                                              description => $ref->{description}
1655         );
1656       }
1657     }
1658   }
1659   $sth->finish;
1660
1661   $query = qq|SELECT c.id, c.accno, c.description
1662               FROM chart c
1663               WHERE c.category = 'I'
1664               AND c.charttype = 'A'
1665               ORDER BY c.accno|;
1666   $sth = $dbh->prepare($query);
1667   $sth->execute || $self->dberror($query);
1668
1669   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1670     %{ $form->{IC}{FX_gain}{ $ref->{accno} } } = (
1671                                              id          => $ref->{id},
1672                                              description => $ref->{description}
1673     );
1674   }
1675   $sth->finish;
1676
1677   $query = qq|SELECT c.id, c.accno, c.description
1678               FROM chart c
1679               WHERE c.category = 'E'
1680               AND c.charttype = 'A'
1681               ORDER BY c.accno|;
1682   $sth = $dbh->prepare($query);
1683   $sth->execute || $self->dberror($query);
1684
1685   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1686     %{ $form->{IC}{FX_loss}{ $ref->{accno} } } = (
1687                                              id          => $ref->{id},
1688                                              description => $ref->{description}
1689     );
1690   }
1691   $sth->finish;
1692
1693   # now get the tax rates and numbers
1694   $query = qq|SELECT c.id, c.accno, c.description,
1695               t.rate * 100 AS rate, t.taxnumber
1696               FROM chart c, tax t
1697               WHERE c.id = t.chart_id|;
1698
1699   $sth = $dbh->prepare($query);
1700   $sth->execute || $form->dberror($query);
1701
1702   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1703     $form->{taxrates}{ $ref->{accno} }{id}          = $ref->{id};
1704     $form->{taxrates}{ $ref->{accno} }{description} = $ref->{description};
1705     $form->{taxrates}{ $ref->{accno} }{taxnumber}   = $ref->{taxnumber}
1706       if $ref->{taxnumber};
1707     $form->{taxrates}{ $ref->{accno} }{rate} = $ref->{rate} if $ref->{rate};
1708   }
1709
1710   $sth->finish;
1711   $dbh->disconnect;
1712
1713   $main::lxdebug->leave_sub();
1714 }
1715
1716 sub closedto {
1717   $main::lxdebug->enter_sub();
1718
1719   my ($self, $myconfig, $form) = @_;
1720
1721   my $dbh = $form->dbconnect($myconfig);
1722
1723   my $query = qq|SELECT closedto, revtrans FROM defaults|;
1724   my $sth   = $dbh->prepare($query);
1725   $sth->execute || $form->dberror($query);
1726
1727   ($form->{closedto}, $form->{revtrans}) = $sth->fetchrow_array;
1728
1729   $sth->finish;
1730
1731   $dbh->disconnect;
1732
1733   $main::lxdebug->leave_sub();
1734 }
1735
1736 sub closebooks {
1737   $main::lxdebug->enter_sub();
1738
1739   my ($self, $myconfig, $form) = @_;
1740
1741   my $dbh = $form->dbconnect($myconfig);
1742
1743   my ($query, @values);
1744
1745   if ($form->{revtrans}) {
1746     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '1'|;
1747
1748   } elsif ($form->{closedto}) {
1749     $query = qq|UPDATE defaults SET closedto = ?, revtrans = '0'|;
1750     @values = (conv_date($form->{closedto}));
1751
1752   } else {
1753     $query = qq|UPDATE defaults SET closedto = NULL, revtrans = '0'|;
1754   }
1755
1756   # set close in defaults
1757   do_query($form, $dbh, $query, @values);
1758
1759   $dbh->disconnect;
1760
1761   $main::lxdebug->leave_sub();
1762 }
1763
1764 sub get_base_unit {
1765   my ($self, $units, $unit_name, $factor) = @_;
1766
1767   $factor = 1 unless ($factor);
1768
1769   my $unit = $units->{$unit_name};
1770
1771   if (!defined($unit) || !$unit->{"base_unit"} ||
1772       ($unit_name eq $unit->{"base_unit"})) {
1773     return ($unit_name, $factor);
1774   }
1775
1776   return AM->get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
1777 }
1778
1779 sub retrieve_units {
1780   $main::lxdebug->enter_sub();
1781
1782   my ($self, $myconfig, $form, $prefix) = @_;
1783
1784   my $dbh = $form->dbconnect($myconfig);
1785
1786   my $query = "SELECT *, base_unit AS original_base_unit FROM units";
1787
1788   my $sth = prepare_execute_query($form, $dbh, $query);
1789
1790   my $units = {};
1791   while (my $ref = $sth->fetchrow_hashref()) {
1792     $units->{$ref->{"name"}} = $ref;
1793   }
1794   $sth->finish();
1795
1796   my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
1797   $sth = $dbh->prepare($query_lang);
1798   $sth->execute() || $form->dberror($query_lang);
1799   my @languages;
1800   while ($ref = $sth->fetchrow_hashref()) {
1801     push(@languages, $ref);
1802   }
1803   $sth->finish();
1804
1805   $query_lang = "SELECT ul.localized, ul.localized_plural, l.id, l.template_code " .
1806     "FROM units_language ul " .
1807     "LEFT JOIN language l ON ul.language_id = l.id " .
1808     "WHERE ul.unit = ?";
1809   $sth = $dbh->prepare($query_lang);
1810
1811   foreach my $unit (values(%{$units})) {
1812     ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = AM->get_base_unit($units, $unit->{"name"});
1813
1814     $unit->{"LANGUAGES"} = {};
1815     foreach my $lang (@languages) {
1816       $unit->{"LANGUAGES"}->{$lang->{"template_code"}} = { "template_code" => $lang->{"template_code"} };
1817     }
1818
1819     $sth->execute($unit->{"name"}) || $form->dberror($query_lang . " (" . $unit->{"name"} . ")");
1820     while ($ref = $sth->fetchrow_hashref()) {
1821       map({ $unit->{"LANGUAGES"}->{$ref->{"template_code"}}->{$_} = $ref->{$_} } keys(%{$ref}));
1822     }
1823   }
1824   $sth->finish();
1825
1826   $dbh->disconnect();
1827
1828   $main::lxdebug->leave_sub();
1829
1830   return $units;
1831 }
1832
1833 sub retrieve_all_units {
1834   $main::lxdebug->enter_sub();
1835
1836   my $self = shift;
1837
1838   if (!$main::all_units) {
1839     $main::all_units = $self->retrieve_units(\%main::myconfig, $main::form);
1840   }
1841
1842   $main::lxdebug->leave_sub();
1843
1844   return $main::all_units;
1845 }
1846
1847
1848 sub translate_units {
1849   $main::lxdebug->enter_sub();
1850
1851   my ($self, $form, $template_code, $unit, $amount) = @_;
1852
1853   my $units = $self->retrieve_units(\%main::myconfig, $form);
1854
1855   my $h = $units->{$unit}->{"LANGUAGES"}->{$template_code};
1856   my $new_unit = $unit;
1857   if ($h) {
1858     if (($amount != 1) && $h->{"localized_plural"}) {
1859       $new_unit = $h->{"localized_plural"};
1860     } elsif ($h->{"localized"}) {
1861       $new_unit = $h->{"localized"};
1862     }
1863   }
1864
1865   $main::lxdebug->leave_sub();
1866
1867   return $new_unit;
1868 }
1869
1870 sub units_in_use {
1871   $main::lxdebug->enter_sub();
1872
1873   my ($self, $myconfig, $form, $units) = @_;
1874
1875   my $dbh = $form->dbconnect($myconfig);
1876
1877   map({ $_->{"in_use"} = 0; } values(%{$units}));
1878
1879   foreach my $unit (values(%{$units})) {
1880     my $base_unit = $unit->{"original_base_unit"};
1881     while ($base_unit) {
1882       $units->{$base_unit}->{"in_use"} = 1;
1883       $units->{$base_unit}->{"DEPENDING_UNITS"} = [] unless ($units->{$base_unit}->{"DEPENDING_UNITS"});
1884       push(@{$units->{$base_unit}->{"DEPENDING_UNITS"}}, $unit->{"name"});
1885       $base_unit = $units->{$base_unit}->{"original_base_unit"};
1886     }
1887   }
1888
1889   foreach my $unit (values(%{$units})) {
1890     map({ $_ = $dbh->quote($_); } @{$unit->{"DEPENDING_UNITS"}});
1891
1892     foreach my $table (qw(parts invoice orderitems)) {
1893       my $query = "SELECT COUNT(*) FROM $table WHERE unit ";
1894
1895       if (0 == scalar(@{$unit->{"DEPENDING_UNITS"}})) {
1896         $query .= "= " . $dbh->quote($unit->{"name"});
1897       } else {
1898         $query .= "IN (" . $dbh->quote($unit->{"name"}) . "," .
1899           join(",", map({ $dbh->quote($_) } @{$unit->{"DEPENDING_UNITS"}})) . ")";
1900       }
1901
1902       my ($count) = $dbh->selectrow_array($query);
1903       $form->dberror($query) if ($dbh->err);
1904
1905       if ($count) {
1906         $unit->{"in_use"} = 1;
1907         last;
1908       }
1909     }
1910   }
1911
1912   $dbh->disconnect();
1913
1914   $main::lxdebug->leave_sub();
1915 }
1916
1917 sub convertible_units {
1918   $main::lxdebug->enter_sub();
1919
1920   my $self        = shift;
1921   my $units       = shift;
1922   my $filter_unit = shift;
1923   my $not_smaller = shift;
1924
1925   my $conv_units = [];
1926
1927   $filter_unit = $units->{$filter_unit};
1928
1929   foreach my $name (sort { lc $a cmp lc $b } keys %{ $units }) {
1930     my $unit = $units->{$name};
1931
1932     if (($unit->{base_unit} eq $filter_unit->{base_unit}) &&
1933         (!$not_smaller || ($unit->{factor} >= $filter_unit->{factor}))) {
1934       push @{$conv_units}, $unit;
1935     }
1936   }
1937
1938   my @sorted = sort { $b->{factor} <=> $a->{factor} } @{ $conv_units };
1939
1940   $main::lxdebug->leave_sub();
1941
1942   return \@sorted;
1943 }
1944
1945 # if $a is translatable to $b, return the factor between them.
1946 # else return 1
1947 sub convert_unit {
1948   $main::lxdebug->enter_sub(2);
1949   ($this, $a, $b, $all_units) = @_;
1950
1951   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a} && $all_units->{$b};
1952   $main::lxdebug->leave_sub(2) and return 0 unless $all_units->{$a}{base_unit} eq $all_units->{$b}{base_unit};
1953   $main::lxdebug->leave_sub(2) and return $all_units->{$a}{factor} / $all_units->{$b}{factor}; 
1954 }
1955
1956 sub unit_select_data {
1957   $main::lxdebug->enter_sub();
1958
1959   my ($self, $units, $selected, $empty_entry, $convertible_into) = @_;
1960
1961   my $select = [];
1962
1963   if ($empty_entry) {
1964     push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
1965   }
1966
1967   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1968     if (!$convertible_into ||
1969         ($units->{$convertible_into} &&
1970          ($units->{$convertible_into}->{base_unit} eq $units->{$unit}->{base_unit}))) {
1971       push @{$select}, { "name"      => $unit,
1972                          "base_unit" => $units->{$unit}->{"base_unit"},
1973                          "factor"    => $units->{$unit}->{"factor"},
1974                          "selected"  => ($unit eq $selected) ? "selected" : "" };
1975     }
1976   }
1977
1978   $main::lxdebug->leave_sub();
1979
1980   return $select;
1981 }
1982
1983 sub unit_select_html {
1984   $main::lxdebug->enter_sub();
1985
1986   my ($self, $units, $name, $selected, $convertible_into) = @_;
1987
1988   my $select = "<select name=${name}>";
1989
1990   foreach my $unit (sort({ $units->{$a}->{"sortkey"} <=> $units->{$b}->{"sortkey"} } keys(%{$units}))) {
1991     if (!$convertible_into ||
1992         ($units->{$convertible_into} &&
1993          ($units->{$convertible_into}->{"base_unit"} eq $units->{$unit}->{"base_unit"}))) {
1994       $select .= "<option" . (($unit eq $selected) ? " selected" : "") . ">${unit}</option>";
1995     }
1996   }
1997   $select .= "</select>";
1998
1999   $main::lxdebug->leave_sub();
2000
2001   return $select;
2002 }
2003
2004 sub sum_with_unit {
2005   $main::lxdebug->enter_sub();
2006
2007   my $self  = shift;
2008
2009   my $units = $self->retrieve_all_units();
2010
2011   my $sum   = 0;
2012   my $base_unit;
2013
2014   while (2 <= scalar(@_)) {
2015     my $qty  = shift(@_);
2016     my $unit = $units->{shift(@_)};
2017
2018     croak "No unit defined with name $unit" if (!defined $unit);
2019
2020     if (!$base_unit) {
2021       $base_unit = $unit->{base_unit};
2022     } elsif ($base_unit ne $unit->{base_unit}) {
2023       croak "Adding values with incompatible base units $base_unit/$unit->{base_unit}";
2024     }
2025
2026     $sum += $qty * $unit->{factor};
2027   }
2028
2029   $main::lxdebug->leave_sub();
2030
2031   return wantarray ? ($sum, $baseunit) : $sum;
2032 }
2033
2034 sub add_unit {
2035   $main::lxdebug->enter_sub();
2036
2037   my ($self, $myconfig, $form, $name, $base_unit, $factor, $languages) = @_;
2038
2039   my $dbh = $form->dbconnect_noauto($myconfig);
2040
2041   my $query = qq|SELECT COALESCE(MAX(sortkey), 0) + 1 FROM units|;
2042   my ($sortkey) = selectrow_query($form, $dbh, $query);
2043
2044   $query = "INSERT INTO units (name, base_unit, factor, sortkey) " .
2045     "VALUES (?, ?, ?, ?)";
2046   do_query($form, $dbh, $query, $name, $base_unit, $factor, $sortkey);
2047
2048   if ($languages) {
2049     $query = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
2050     my $sth = $dbh->prepare($query);
2051     foreach my $lang (@{$languages}) {
2052       my @values = ($name, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
2053       $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
2054     }
2055     $sth->finish();
2056   }
2057
2058   $dbh->commit();
2059   $dbh->disconnect();
2060
2061   $main::lxdebug->leave_sub();
2062 }
2063
2064 sub save_units {
2065   $main::lxdebug->enter_sub();
2066
2067   my ($self, $myconfig, $form, $units, $delete_units) = @_;
2068
2069   my $dbh = $form->dbconnect_noauto($myconfig);
2070
2071   my ($base_unit, $unit, $sth, $query);
2072
2073   $query = "DELETE FROM units_language";
2074   $dbh->do($query) || $form->dberror($query);
2075
2076   if ($delete_units && (0 != scalar(@{$delete_units}))) {
2077     $query = "DELETE FROM units WHERE name IN (";
2078     map({ $query .= "?," } @{$delete_units});
2079     substr($query, -1, 1) = ")";
2080     $dbh->do($query, undef, @{$delete_units}) ||
2081       $form->dberror($query . " (" . join(", ", @{$delete_units}) . ")");
2082   }
2083
2084   $query = "UPDATE units SET name = ?, base_unit = ?, factor = ? WHERE name = ?";
2085   $sth = $dbh->prepare($query);
2086
2087   my $query_lang = "INSERT INTO units_language (unit, language_id, localized, localized_plural) VALUES (?, ?, ?, ?)";
2088   my $sth_lang = $dbh->prepare($query_lang);
2089
2090   foreach $unit (values(%{$units})) {
2091     $unit->{"depth"} = 0;
2092     my $base_unit = $unit;
2093     while ($base_unit->{"base_unit"}) {
2094       $unit->{"depth"}++;
2095       $base_unit = $units->{$base_unit->{"base_unit"}};
2096     }
2097   }
2098
2099   foreach $unit (sort({ $a->{"depth"} <=> $b->{"depth"} } values(%{$units}))) {
2100     if ($unit->{"LANGUAGES"}) {
2101       foreach my $lang (@{$unit->{"LANGUAGES"}}) {
2102         next unless ($lang->{"id"} && $lang->{"localized"});
2103         my @values = ($unit->{"name"}, $lang->{"id"}, $lang->{"localized"}, $lang->{"localized_plural"});
2104         $sth_lang->execute(@values) || $form->dberror($query_lang . " (" . join(", ", @values) . ")");
2105       }
2106     }
2107
2108     next if ($unit->{"unchanged_unit"});
2109
2110     my @values = ($unit->{"name"}, $unit->{"base_unit"}, $unit->{"factor"}, $unit->{"old_name"});
2111     $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
2112   }
2113
2114   $sth->finish();
2115   $sth_lang->finish();
2116   $dbh->commit();
2117   $dbh->disconnect();
2118
2119   $main::lxdebug->leave_sub();
2120 }
2121
2122 sub swap_units {
2123   $main::lxdebug->enter_sub();
2124
2125   my ($self, $myconfig, $form, $dir, $name_1) = @_;
2126
2127   my $dbh = $form->dbconnect_noauto($myconfig);
2128
2129   my $query;
2130
2131   $query = qq|SELECT sortkey FROM units WHERE name = ?|;
2132   my ($sortkey_1) = selectrow_query($form, $dbh, $query, $name_1);
2133
2134   $query =
2135     qq|SELECT sortkey FROM units | .
2136     qq|WHERE sortkey | . ($dir eq "down" ? ">" : "<") . qq| ? | .
2137     qq|ORDER BY sortkey | . ($dir eq "down" ? "ASC" : "DESC") . qq| LIMIT 1|;
2138   my ($sortkey_2) = selectrow_query($form, $dbh, $query, $sortkey_1);
2139
2140   if (defined($sortkey_1)) {
2141     $query = qq|SELECT name FROM units WHERE sortkey = ${sortkey_2}|;
2142     my ($name_2) = selectrow_query($form, $dbh, $query);
2143
2144     if (defined($name_2)) {
2145       $query = qq|UPDATE units SET sortkey = ? WHERE name = ?|;
2146       my $sth = $dbh->prepare($query);
2147
2148       do_statement($form, $sth, $query, $sortkey_1, $name_2);
2149       do_statement($form, $sth, $query, $sortkey_2, $name_1);
2150     }
2151   }
2152
2153   $dbh->commit();
2154   $dbh->disconnect();
2155
2156   $main::lxdebug->leave_sub();
2157 }
2158
2159 sub taxes {
2160   $main::lxdebug->enter_sub();
2161
2162   my ($self, $myconfig, $form) = @_;
2163
2164   # connect to database
2165   my $dbh = $form->dbconnect($myconfig);
2166
2167   my $query = qq|SELECT
2168                    t.id,
2169                    t.taxkey,
2170                    t.taxdescription,
2171                    round(t.rate * 100, 2) AS rate,
2172                    (SELECT accno FROM chart WHERE id = chart_id) AS taxnumber,
2173                    (SELECT description FROM chart WHERE id = chart_id) AS account_description
2174                  FROM tax t
2175                  ORDER BY taxkey|;
2176
2177   $sth = $dbh->prepare($query);
2178   $sth->execute || $form->dberror($query);
2179
2180   $form->{TAX} = [];
2181   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2182     push @{ $form->{TAX} }, $ref;
2183   }
2184
2185   $sth->finish;
2186   $dbh->disconnect;
2187
2188   $main::lxdebug->leave_sub();
2189 }
2190
2191 sub get_tax_accounts {
2192   $main::lxdebug->enter_sub();
2193
2194   my ($self, $myconfig, $form) = @_;
2195
2196   my $dbh = $form->dbconnect($myconfig);
2197
2198   # get Accounts from chart
2199   my $query = qq{ SELECT
2200                  id,
2201                  accno || ' - ' || description AS taxaccount
2202                FROM chart
2203                WHERE link LIKE '%_tax%'
2204                ORDER BY accno
2205              };
2206
2207   $sth = $dbh->prepare($query);
2208   $sth->execute || $form->dberror($query);
2209
2210   $form->{ACCOUNTS} = [];
2211   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2212     push @{ $form->{ACCOUNTS} }, $ref;
2213   }
2214
2215   $sth->finish;
2216
2217   $dbh->disconnect;
2218
2219   $main::lxdebug->leave_sub();
2220 }
2221
2222 sub get_tax {
2223   $main::lxdebug->enter_sub();
2224
2225   my ($self, $myconfig, $form) = @_;
2226
2227   # connect to database
2228   my $dbh = $form->dbconnect($myconfig);
2229
2230   my $query = qq|SELECT
2231                    taxkey,
2232                    taxdescription,
2233                    round(rate * 100, 2) AS rate,
2234                    chart_id
2235                  FROM tax
2236                  WHERE id = ? |;
2237
2238   my $sth = $dbh->prepare($query);
2239   $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2240
2241   my $ref = $sth->fetchrow_hashref(NAME_lc);
2242
2243   map { $form->{$_} = $ref->{$_} } keys %$ref;
2244
2245   $sth->finish;
2246
2247   # see if it is used by a taxkey
2248   $query = qq|SELECT count(*) FROM taxkeys
2249               WHERE tax_id = ? AND chart_id >0|;
2250
2251   ($form->{orphaned}) = selectrow_query($form, $dbh, $query, $form->{id});
2252
2253   $form->{orphaned} = !$form->{orphaned};
2254   $sth->finish;
2255
2256   if (!$form->{orphaned} ) {
2257     $query = qq|SELECT DISTINCT c.id, c.accno
2258                 FROM taxkeys tk
2259                 JOIN   tax t ON (t.id = tk.tax_id)
2260                 JOIN chart c ON (c.id = tk.chart_id)
2261                 WHERE tk.tax_id = ?|;
2262
2263     $sth = $dbh->prepare($query);
2264     $sth->execute($form->{id}) || $form->dberror($query . " ($form->{id})");
2265
2266     $form->{TAXINUSE} = [];
2267     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2268       push @{ $form->{TAXINUSE} }, $ref;
2269     }
2270
2271     $sth->finish;
2272   }
2273
2274   $dbh->disconnect;
2275
2276   $main::lxdebug->leave_sub();
2277 }
2278
2279 sub save_tax {
2280   $main::lxdebug->enter_sub();
2281
2282   my ($self, $myconfig, $form) = @_;
2283
2284   # connect to database
2285   my $dbh = $form->get_standard_dbh($myconfig);
2286
2287   $form->{rate} = $form->{rate} / 100;
2288
2289   my @values = ($form->{taxkey}, $form->{taxdescription}, $form->{rate}, $form->{chart_id}, $form->{chart_id} );
2290   if ($form->{id} ne "") {
2291     $query = qq|UPDATE tax SET
2292                   taxkey         = ?,
2293                   taxdescription = ?,
2294                   rate           = ?,
2295                   chart_id       = ?,
2296                   taxnumber      = (SELECT accno FROM chart WHERE id= ? )
2297                 WHERE id = ?|;
2298     push(@values, $form->{id});
2299
2300   } else {
2301     #ok
2302     $query = qq|INSERT INTO tax (
2303                   taxkey,
2304                   taxdescription,
2305                   rate,
2306                   chart_id,
2307                   taxnumber
2308                 )
2309                 VALUES (?, ?, ?, ?, (SELECT accno FROM chart WHERE id = ?) )|;
2310   }
2311   do_query($form, $dbh, $query, @values);
2312
2313   $dbh->commit();
2314
2315   $main::lxdebug->leave_sub();
2316 }
2317
2318 sub delete_tax {
2319   $main::lxdebug->enter_sub();
2320
2321   my ($self, $myconfig, $form) = @_;
2322
2323   # connect to database
2324   my $dbh = $form->get_standard_dbh($myconfig);
2325
2326   $query = qq|DELETE FROM tax
2327               WHERE id = ?|;
2328   do_query($form, $dbh, $query, $form->{id});
2329
2330   $dbh->commit();
2331
2332   $main::lxdebug->leave_sub();
2333 }
2334
2335 sub save_price_factor {
2336   $main::lxdebug->enter_sub();
2337
2338   my ($self, $myconfig, $form) = @_;
2339
2340   # connect to database
2341   my $dbh = $form->get_standard_dbh($myconfig);
2342
2343   my $query;
2344   my @values = ($form->{description}, conv_i($form->{factor}));
2345
2346   if ($form->{id}) {
2347     $query = qq|UPDATE price_factors SET description = ?, factor = ? WHERE id = ?|;
2348     push @values, conv_i($form->{id});
2349
2350   } else {
2351     $query = qq|INSERT INTO price_factors (description, factor, sortkey) VALUES (?, ?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM price_factors))|;
2352   }
2353
2354   do_query($form, $dbh, $query, @values);
2355
2356   $dbh->commit();
2357
2358   $main::lxdebug->leave_sub();
2359 }
2360
2361 sub get_all_price_factors {
2362   $main::lxdebug->enter_sub();
2363
2364   my ($self, $myconfig, $form) = @_;
2365
2366   # connect to database
2367   my $dbh = $form->get_standard_dbh($myconfig);
2368
2369   $form->{PRICE_FACTORS} = selectall_hashref_query($form, $dbh, qq|SELECT * FROM price_factors ORDER BY sortkey|);
2370
2371   $main::lxdebug->leave_sub();
2372 }
2373
2374 sub get_price_factor {
2375   $main::lxdebug->enter_sub();
2376
2377   my ($self, $myconfig, $form) = @_;
2378
2379   # connect to database
2380   my $dbh = $form->get_standard_dbh($myconfig);
2381
2382   my $query = qq|SELECT description, factor,
2383                    ((SELECT COUNT(*) FROM parts      WHERE price_factor_id = ?) +
2384                     (SELECT COUNT(*) FROM invoice    WHERE price_factor_id = ?) +
2385                     (SELECT COUNT(*) FROM orderitems WHERE price_factor_id = ?)) = 0 AS orphaned
2386                  FROM price_factors WHERE id = ?|;
2387
2388   ($form->{description}, $form->{factor}, $form->{orphaned}) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x 4);
2389
2390   $main::lxdebug->leave_sub();
2391 }
2392
2393 sub delete_price_factor {
2394   $main::lxdebug->enter_sub();
2395
2396   my ($self, $myconfig, $form) = @_;
2397
2398   # connect to database
2399   my $dbh = $form->get_standard_dbh($myconfig);
2400
2401   do_query($form, $dbh, qq|DELETE FROM price_factors WHERE id = ?|, conv_i($form->{id}));
2402   $dbh->commit();
2403
2404   $main::lxdebug->leave_sub();
2405 }
2406
2407 sub save_warehouse {
2408   $main::lxdebug->enter_sub();
2409
2410   my ($self, $myconfig, $form) = @_;
2411
2412   # connect to database
2413   my $dbh = $form->get_standard_dbh($myconfig);
2414
2415   my ($query, @values, $sth);
2416
2417   if (!$form->{id}) {
2418     $query        = qq|SELECT nextval('id')|;
2419     ($form->{id}) = selectrow_query($form, $dbh, $query);
2420
2421     $query        = qq|INSERT INTO warehouse (id, sortkey) VALUES (?, (SELECT COALESCE(MAX(sortkey), 0) + 1 FROM warehouse))|;
2422     do_query($form, $dbh, $query, $form->{id});
2423   }
2424
2425   do_query($form, $dbh, qq|UPDATE warehouse SET description = ?, invalid = ? WHERE id = ?|,
2426            $form->{description}, $form->{invalid} ? 't' : 'f', conv_i($form->{id}));
2427
2428   if (0 < $form->{number_of_new_bins}) {
2429     $query = qq|INSERT INTO bin (warehouse_id, description) VALUES (?, ?)|;
2430     $sth   = prepare_query($form, $dbh, $query);
2431
2432     foreach my $i (1..$form->{number_of_new_bins}) {
2433       do_statement($form, $sth, $query, conv_i($form->{id}), "$form->{prefix}${i}");
2434     }
2435
2436     $sth->finish();
2437   }
2438
2439   $dbh->commit();
2440
2441   $main::lxdebug->leave_sub();
2442 }
2443
2444 sub save_bins {
2445   $main::lxdebug->enter_sub();
2446
2447   my ($self, $myconfig, $form) = @_;
2448
2449   # connect to database
2450   my $dbh = $form->get_standard_dbh($myconfig);
2451
2452   my ($query, @values, $commit_necessary, $sth);
2453
2454   @values = map { $form->{"id_${_}"} } grep { $form->{"delete_${_}"} } (1..$form->{rowcount});
2455
2456   if (@values) {
2457     $query = qq|DELETE FROM bin WHERE id IN (| . join(', ', ('?') x scalar(@values)) . qq|)|;
2458     do_query($form, $dbh, $query, @values);
2459
2460     $commit_necessary = 1;
2461   }
2462
2463   $query = qq|UPDATE bin SET description = ? WHERE id = ?|;
2464   $sth   = prepare_query($form, $dbh, $query);
2465
2466   foreach my $row (1..$form->{rowcount}) {
2467     next if ($form->{"delete_${row}"});
2468
2469     do_statement($form, $sth, $query, $form->{"description_${row}"}, conv_i($form->{"id_${row}"}));
2470
2471     $commit_necessary = 1;
2472   }
2473
2474   $sth->finish();
2475
2476   $dbh->commit() if ($commit_necessary);
2477
2478   $main::lxdebug->leave_sub();
2479 }
2480
2481 sub delete_warehouse {
2482   $main::lxdebug->enter_sub();
2483
2484   my ($self, $myconfig, $form) = @_;
2485
2486   # connect to database
2487   my $dbh = $form->get_standard_dbh($myconfig);
2488
2489   my $id      = conv_i($form->{id});
2490   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|;
2491   my ($count) = selectrow_query($form, $dbh, $query, $id);
2492
2493   if ($count) {
2494     $main::lxdebug->leave_sub();
2495     return 0;
2496   }
2497
2498   do_query($form, $dbh, qq|DELETE FROM bin       WHERE warehouse_id = ?|, conv_i($form->{id}));
2499   do_query($form, $dbh, qq|DELETE FROM warehouse WHERE id           = ?|, conv_i($form->{id}));
2500
2501   $dbh->commit();
2502
2503   $main::lxdebug->leave_sub();
2504
2505   return 1;
2506 }
2507
2508 sub get_all_warehouses {
2509   $main::lxdebug->enter_sub();
2510
2511   my ($self, $myconfig, $form) = @_;
2512
2513   # connect to database
2514   my $dbh = $form->get_standard_dbh($myconfig);
2515
2516   my $query = qq|SELECT w.id, w.description, w.invalid,
2517                    (SELECT COUNT(b.description) FROM bin b WHERE b.warehouse_id = w.id) AS number_of_bins
2518                  FROM warehouse w
2519                  ORDER BY w.sortkey|;
2520
2521   $form->{WAREHOUSES} = selectall_hashref_query($form, $dbh, $query);
2522
2523   $main::lxdebug->leave_sub();
2524 }
2525
2526 sub get_warehouse {
2527   $main::lxdebug->enter_sub();
2528
2529   my ($self, $myconfig, $form) = @_;
2530
2531   # connect to database
2532   my $dbh = $form->get_standard_dbh($myconfig);
2533
2534   my $id    = conv_i($form->{id});
2535   my $query = qq|SELECT w.description, w.invalid
2536                  FROM warehouse w
2537                  WHERE w.id = ?|;
2538
2539   my $ref   = selectfirst_hashref_query($form, $dbh, $query, $id);
2540
2541   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2542
2543   $query = qq|SELECT b.*, EXISTS
2544                 (SELECT i.warehouse_id
2545                  FROM inventory i
2546                  WHERE i.bin_id = b.id
2547                  LIMIT 1)
2548                 AS in_use
2549               FROM bin b
2550               WHERE b.warehouse_id = ?|;
2551
2552   $form->{BINS} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
2553
2554   $main::lxdebug->leave_sub();
2555 }
2556
2557 1;