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