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