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