Undefinierte Werte aus der Liste der "gewollten Variablen" rauswerfen, weil die Liste...
[kivitendo-erp.git] / SL / IS.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) 1998-2002
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 # Inventory invoicing module
32 #
33 #======================================================================
34
35 package IS;
36
37 use Data::Dumper;
38 use SL::AM;
39
40 sub invoice_details {
41   $main::lxdebug->enter_sub();
42
43   my ($self, $myconfig, $form, $locale) = @_;
44
45   $form->{duedate} = $form->{invdate} unless ($form->{duedate});
46
47   # connect to database
48   my $dbh = $form->dbconnect($myconfig);
49
50   my $query = qq|SELECT date '$form->{duedate}' - date '$form->{invdate}'
51                  AS terms
52                  FROM defaults|;
53   my $sth = $dbh->prepare($query);
54   $sth->execute || $form->dberror($query);
55
56   ($form->{terms}) = $sth->fetchrow_array;
57   $sth->finish;
58
59   my $tax = 0;
60   my $item;
61   my $i;
62   my @partsgroup = ();
63   my $partsgroup;
64   my %oid = ('Pg'     => 'oid',
65              'Oracle' => 'rowid');
66
67   # sort items by partsgroup
68   for $i (1 .. $form->{rowcount}) {
69     $partsgroup = "";
70     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
71       $partsgroup = $form->{"partsgroup_$i"};
72     }
73     push @partsgroup, [$i, $partsgroup];
74   }
75
76   my $sameitem = "";
77   my @taxaccounts;
78   my %taxaccounts;
79   my %taxbase;
80   my $taxrate;
81   my $taxamount;
82   my $taxbase;
83   my $taxdiff;
84   my $nodiscount;
85   my $yesdiscount;
86   my $nodiscount_subtotal = 0;
87   my $discount_subtotal = 0;
88   my $position = 0;
89   my $subtotal_header = 0;
90   my $subposition = 0;
91
92
93   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
94     $i = $item->[0];
95
96     if ($item->[1] ne $sameitem) {
97       push(@{ $form->{description} }, qq|$item->[1]|);
98       $sameitem = $item->[1];
99
100       map { push(@{ $form->{$_} }, "") }
101         qw(runningnumber number serialnumber bin partnotes qty unit deliverydate sellprice listprice netprice discount linetotal);
102     }
103
104     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
105
106     if ($form->{"qty_$i"} != 0) {
107
108       # add number, description and qty to $form->{number},
109       if ($form->{"subtotal_$i"} && !$subtotal_header) {
110         $subtotal_header = $i;
111         $position = int($position);
112         $subposition = 0;
113         $position++;
114       } elsif ($subtotal_header) {
115         $subposition += 1;
116         $position = int($position);
117         $position = $position.".".$subposition;
118       } else {
119         $position = int($position);
120         $position++;
121       }
122       push(@{ $form->{runningnumber} }, $position);
123       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
124       push(@{ $form->{serialnumber} },  qq|$form->{"serialnumber_$i"}|);
125       push(@{ $form->{bin} },           qq|$form->{"bin_$i"}|);
126       push(@{ $form->{"partnotes"} },   qq|$form->{"partnotes_$i"}|);
127       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
128       push(@{ $form->{longdescription} },   qq|$form->{"longdescription_$i"}|);
129       push(@{ $form->{qty} },
130            $form->format_amount($myconfig, $form->{"qty_$i"}));
131       push(@{ $form->{unit} },            qq|$form->{"unit_$i"}|);
132       push(@{ $form->{deliverydate_oe} }, qq|$form->{"deliverydate_$i"}|);
133
134       push(@{ $form->{sellprice} },    $form->{"sellprice_$i"});
135       push(@{ $form->{ordnumber_oe} }, qq|$form->{"ordnumber_$i"}|);
136       push(@{ $form->{transdate_oe} }, qq|$form->{"transdate_$i"}|);
137       push(@{ $form->{invnumber} }, qq|$form->{"invnumber"}|);
138       push(@{ $form->{invdate} }, qq|$form->{"invdate"}|);
139
140       if ($form->{lizenzen}) {
141         if ($form->{"licensenumber_$i"}) {
142           $query =
143             qq|SELECT l.licensenumber, l.validuntil FROM license l WHERE l.id = $form->{"licensenumber_$i"}|;
144           $sth = $dbh->prepare($query);
145           $sth->execute || $form->dberror($query);
146
147           ($licensenumber, $validuntil) = $sth->fetchrow_array;
148           push(@{ $form->{licensenumber} }, $licensenumber);
149           push(@{ $form->{validuntil} },
150                $locale->date($myconfig, $validuntil, 0));
151           $sth->finish;
152         } else {
153           push(@{ $form->{licensenumber} }, "");
154           push(@{ $form->{validuntil} },    "");
155         }
156       }
157
158       # listprice
159       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
160
161       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
162       my ($dec) = ($sellprice =~ /\.(\d+)/);
163       $dec = length $dec;
164       my $decimalplaces = ($dec > 2) ? $dec : 2;
165
166       my $i_discount =
167         $form->round_amount(
168                             $sellprice * $form->parse_amount($myconfig,
169                                                  $form->{"discount_$i"}) / 100,
170                             $decimalplaces);
171
172       my $discount =
173         $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
174
175       # keep a netprice as well, (sellprice - discount)
176       $form->{"netprice_$i"} = $sellprice - $i_discount;
177
178       push(@{ $form->{netprice} },
179            ($form->{"netprice_$i"} != 0)
180            ? $form->format_amount(
181                                  $myconfig, $form->{"netprice_$i"},
182                                  $decimalplaces
183              )
184            : " ");
185
186       my $linetotal =
187         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
188
189       my $nodiscount_linetotal =
190         $form->round_amount($form->{"qty_$i"} * $sellprice, 2);
191
192       $discount =
193         ($discount != 0)
194         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
195         : " ";
196       $linetotal = ($linetotal != 0) ? $linetotal : " ";
197
198       push(@{ $form->{discount} },   $discount);
199       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
200       if (($form->{"discount_$i"} ne "") && ($form->{"discount_$i"} != 0)) {
201         $form->{discount_p} = $form->{"discount_$i"};
202       }
203       $form->{total} += $linetotal;
204       $discount_subtotal += $linetotal;
205       $form->{nodiscount_total} += $nodiscount_linetotal;
206       $nodiscount_subtotal += $nodiscount_linetotal;
207       $form->{discount_total} += $form->parse_amount($myconfig, $discount);
208
209       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
210         $discount_subtotal = $form->format_amount($myconfig, $discount_subtotal, 2);
211         push(@{ $form->{discount_sub} },  $discount_subtotal);
212         $nodiscount_subtotal = $form->format_amount($myconfig, $nodiscount_subtotal, 2);
213         push(@{ $form->{nodiscount_sub} }, $nodiscount_subtotal);
214         $discount_subtotal = 0;
215         $nodiscount_subtotal = 0;
216         $subtotal_header = 0;
217       } else {
218         push(@{ $form->{discount_sub} }, "");
219         push(@{ $form->{nodiscount_sub} }, "");
220       }
221
222       if ($linetotal == $netto_linetotal) {
223         $nodiscount += $linetotal;
224       }
225
226       push(@{ $form->{linetotal} },
227            $form->format_amount($myconfig, $linetotal, 2));
228       push(@{ $form->{nodiscount_linetotal} },
229            $form->format_amount($myconfig, $nodiscount_linetotal, 2));
230
231
232       
233       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
234       $taxrate     = 0;
235       $taxdiff     = 0;
236
237       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
238
239       if ($form->{taxincluded}) {
240
241         # calculate tax
242         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
243         $taxbase = $linetotal - $taxamount;
244       } else {
245         $taxamount = $linetotal * $taxrate;
246         $taxbase   = $linetotal;
247       }
248
249       if ($form->round_amount($taxrate, 7) == 0) {
250         if ($form->{taxincluded}) {
251           foreach $item (@taxaccounts) {
252             $taxamount =
253               $form->round_amount($linetotal * $form->{"${item}_rate"} /
254                                     (1 + abs($form->{"${item}_rate"})),
255                                   2);
256
257             $taxaccounts{$item} += $taxamount;
258             $taxdiff            += $taxamount;
259
260             $taxbase{$item} += $taxbase;
261           }
262           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
263         } else {
264           foreach $item (@taxaccounts) {
265             $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
266             $taxbase{$item}     += $taxbase;
267           }
268         }
269       } else {
270         foreach $item (@taxaccounts) {
271           $taxaccounts{$item} +=
272             $taxamount * $form->{"${item}_rate"} / $taxrate;
273           $taxbase{$item} += $taxbase;
274         }
275       }
276       $tax_rate = $taxrate * 100;
277       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
278       if ($form->{"assembly_$i"}) {
279         $sameitem = "";
280
281         # get parts and push them onto the stack
282         my $sortorder = "";
283         if ($form->{groupitems}) {
284           $sortorder =
285             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
286         } else {
287           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
288         }
289
290         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
291                     pg.partsgroup
292                     FROM assembly a
293                     JOIN parts p ON (a.parts_id = p.id)
294                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
295                     WHERE a.bom = '1'
296                     AND a.id = '$form->{"id_$i"}'
297                     $sortorder|;
298         $sth = $dbh->prepare($query);
299         $sth->execute || $form->dberror($query);
300
301         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
302           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
303             map { push(@{ $form->{$_} }, "") }
304               qw(runningnumber number serialnumber unit qty bin sellprice listprice netprice discount linetotal nodiscount_linetotal);
305             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
306             push(@{ $form->{description} }, $sameitem);
307           }
308
309           map { $form->{"a_$_"} = $ref->{$_} } qw(partnumber description);
310
311           push(@{ $form->{description} },
312                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
313                  )
314                  . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
315           map { push(@{ $form->{$_} }, "") }
316             qw(number unit qty runningnumber serialnumber bin sellprice listprice netprice discount linetotal nodiscount_linetotal);
317
318         }
319         $sth->finish;
320       }
321     }
322   }
323
324   foreach my $item (sort keys %taxaccounts) {
325     push(@{ $form->{taxbase} },
326           $form->format_amount($myconfig, $taxbase{$item}, 2));
327
328     $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
329
330     push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
331     push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
332     push(@{ $form->{taxrate} },
333           $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
334     push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
335   }
336
337   for my $i (1 .. $form->{paidaccounts}) {
338     if ($form->{"paid_$i"}) {
339       push(@{ $form->{payment} }, $form->{"paid_$i"});
340       my ($accno, $description) = split /--/, $form->{"AR_paid_$i"};
341       push(@{ $form->{paymentaccount} }, $description);
342       push(@{ $form->{paymentdate} },    $form->{"datepaid_$i"});
343       push(@{ $form->{paymentsource} },  $form->{"source_$i"});
344
345       $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
346     }
347   }
348
349   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
350   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
351   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
352   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
353   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
354   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
355
356   $form->{invtotal} =
357     ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
358   $form->{total} =
359     $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
360   $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
361   $form->set_payment_options($myconfig, $form->{invdate});
362   $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
363
364   $form->{username} = $myconfig->{name};
365
366   $dbh->disconnect;
367
368   $main::lxdebug->leave_sub();
369 }
370
371 sub project_description {
372   $main::lxdebug->enter_sub();
373
374   my ($self, $dbh, $id) = @_;
375
376   my $query = qq|SELECT p.description
377                  FROM project p
378                  WHERE p.id = $id|;
379   my $sth = $dbh->prepare($query);
380   $sth->execute || $form->dberror($query);
381
382   ($_) = $sth->fetchrow_array;
383
384   $sth->finish;
385
386   $main::lxdebug->leave_sub();
387
388   return $_;
389 }
390
391 sub customer_details {
392   $main::lxdebug->enter_sub();
393
394   my ($self, $myconfig, $form, @wanted_vars) = @_;
395
396   # connect to database
397   my $dbh = $form->dbconnect($myconfig);
398
399   # get contact id, set it if nessessary
400   $form->{cp_id} *= 1;
401
402   $contact = "";
403   if ($form->{cp_id}) {
404     $contact = "and cp.cp_id = $form->{cp_id}";
405   }
406
407   # get rest for the customer
408   my $query = qq|SELECT ct.*, cp.*, ct.notes as customernotes
409                  FROM customer ct
410                  LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
411                  WHERE ct.id = $form->{customer_id} $contact order by cp.cp_id limit 1|;
412   my $sth = $dbh->prepare($query);
413   $sth->execute || $form->dberror($query);
414
415   $ref = $sth->fetchrow_hashref(NAME_lc);
416
417   # remove id and taxincluded before copy back
418   delete @$ref{qw(id taxincluded)};
419
420   @wanted_vars = grep({ $_ } @wanted_vars);
421   if (scalar(@wanted_vars) > 0) {
422     my %h_wanted_vars;
423     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
424     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
425   }
426
427   map { $form->{$_} = $ref->{$_} } keys %$ref;
428   $sth->finish;
429
430   if ($form->{delivery_customer_id}) {
431     my $query = qq|SELECT ct.*, ct.notes as customernotes
432                  FROM customer ct
433                  WHERE ct.id = $form->{delivery_customer_id} limit 1|;
434     my $sth = $dbh->prepare($query);
435     $sth->execute || $form->dberror($query);
436
437     $ref = $sth->fetchrow_hashref(NAME_lc);
438
439     $sth->finish;
440     map { $form->{"dc_$_"} = $ref->{$_} } keys %$ref;
441   }
442
443   if ($form->{delivery_vendor_id}) {
444     my $query = qq|SELECT ct.*, ct.notes as customernotes
445                  FROM customer ct
446                  WHERE ct.id = $form->{delivery_vendor_id} limit 1|;
447     my $sth = $dbh->prepare($query);
448     $sth->execute || $form->dberror($query);
449
450     $ref = $sth->fetchrow_hashref(NAME_lc);
451
452     $sth->finish;
453     map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
454   }
455   $dbh->disconnect;
456
457   $main::lxdebug->leave_sub();
458 }
459
460 sub post_invoice {
461   $main::lxdebug->enter_sub();
462
463   my ($self, $myconfig, $form) = @_;
464
465   # connect to database, turn off autocommit
466   my $dbh = $form->dbconnect_noauto($myconfig);
467
468   my ($query, $sth, $null, $project_id, $deliverydate);
469   my $exchangerate = 0;
470
471   ($null, $form->{employee_id}) = split /--/, $form->{employee};
472   unless ($form->{employee_id}) {
473     $form->get_employee($dbh);
474   }
475
476   $form->{contact_id} = $form->{cp_id};
477   $form->{contact_id} *= 1;
478   $form->{payment_id} *= 1;
479   $form->{language_id} *= 1;
480   $form->{taxzone_id} *= 1;
481   $form->{delivery_customer_id} *= 1;
482   $form->{delivery_vendor_id} *= 1;
483   $form->{storno} *= 1;
484   $form->{shipto_id} *= 1;
485
486
487   ($null, $form->{department_id}) = split(/--/, $form->{department});
488   $form->{department_id} *= 1;
489
490   my $service_units = AM->retrieve_units($myconfig,$form,"service");
491   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
492
493
494
495   if ($form->{id}) {
496
497     &reverse_invoice($dbh, $form);
498
499   } else {
500     my $uid = rand() . time;
501
502     $uid .= $form->{login};
503
504     $uid = substr($uid, 2, 75);
505
506     $query = qq|INSERT INTO ar (invnumber, employee_id)
507                 VALUES ('$uid', $form->{employee_id})|;
508     $dbh->do($query) || $form->dberror($query);
509
510     $query = qq|SELECT a.id FROM ar a
511                 WHERE a.invnumber = '$uid'|;
512     $sth = $dbh->prepare($query);
513     $sth->execute || $form->dberror($query);
514
515     ($form->{id}) = $sth->fetchrow_array;
516     $sth->finish;
517   }
518
519   map { $form->{$_} =~ s/\'/\'\'/g }
520     (qw(invnumber shippingpoint shipvia notes intnotes message));
521
522   my ($netamount, $invoicediff) = (0, 0);
523   my ($amount, $linetotal, $lastincomeaccno);
524
525   if ($form->{currency} eq $form->{defaultcurrency}) {
526     $form->{exchangerate} = 1;
527   } else {
528     $exchangerate =
529       $form->check_exchangerate($myconfig, $form->{currency},
530                                 $form->{transdate}, 'buy');
531   }
532
533   $form->{exchangerate} =
534     ($exchangerate)
535     ? $exchangerate
536     : $form->parse_amount($myconfig, $form->{exchangerate});
537
538   $form->{expense_inventory} = "";
539
540   foreach my $i (1 .. $form->{rowcount}) {
541     if ($form->{type} eq "credit_note") {
542       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}) * -1;
543       $form->{shipped} = 1;   
544     } else {
545       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
546     }
547     my $basefactor;
548     my $basqty;
549
550     if ($form->{storno}) {
551       $form->{"qty_$i"} *= -1;
552     }
553
554     if ($form->{"qty_$i"} != 0) {
555
556       # get item baseunit
557       $query = qq|SELECT p.unit
558                   FROM parts p
559                   WHERE p.id = $form->{"id_$i"}|;
560       $sth = $dbh->prepare($query);
561       $sth->execute || $form->dberror($query);
562
563       my ($item_unit) = $sth->fetchrow_array();
564       $sth->finish;
565
566       if ($form->{"inventory_accno_$i"}) {
567         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
568           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
569         } else {
570           $basefactor = 1;
571         }
572         $baseqty = $form->{"qty_$i"} * $basefactor;
573       } else {
574         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
575           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
576         } else {
577           $basefactor = 1;
578         }
579         $baseqty = $form->{"qty_$i"} * $basefactor;
580       }
581
582       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
583         (qw(partnumber description unit));
584
585       # undo discount formatting
586       $form->{"discount_$i"} =
587         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
588
589       my ($allocated, $taxrate) = (0, 0);
590       my $taxamount;
591
592       # keep entered selling price
593       my $fxsellprice =
594         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
595
596       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
597       $dec = length $dec;
598       my $decimalplaces = ($dec > 2) ? $dec : 2;
599
600       # deduct discount
601       my $discount =
602         $form->round_amount($fxsellprice * $form->{"discount_$i"},
603                             $decimalplaces);
604       $form->{"sellprice_$i"} = $fxsellprice - $discount;
605
606       # add tax rates
607       map { $taxrate += $form->{"${_}_rate"} } split / /,
608         $form->{"taxaccounts_$i"};
609
610       # round linetotal to 2 decimal places
611       $linetotal =
612         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
613
614       if ($form->{taxincluded}) {
615         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
616         $form->{"sellprice_$i"} =
617           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
618       } else {
619         $taxamount = $linetotal * $taxrate;
620       }
621
622       $netamount += $linetotal;
623
624       if ($taxamount != 0) {
625         map {
626           $form->{amount}{ $form->{id} }{$_} +=
627             $taxamount * $form->{"${_}_rate"} / $taxrate
628         } split / /, $form->{"taxaccounts_$i"};
629       }
630
631       # add amount to income, $form->{amount}{trans_id}{accno}
632       $amount =
633         $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
634
635       $linetotal =
636         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
637         $form->{exchangerate};
638       $linetotal = $form->round_amount($linetotal, 2);
639
640       # this is the difference from the inventory
641       $invoicediff += ($amount - $linetotal);
642
643       $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
644         $linetotal;
645
646       $lastincomeaccno = $form->{"income_accno_$i"};
647
648       # adjust and round sellprice
649       $form->{"sellprice_$i"} =
650         $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
651                             $decimalplaces);
652
653       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
654
655         # adjust parts onhand quantity
656
657         if ($form->{"assembly_$i"}) {
658
659           # do not update if assembly consists of all services
660           $query = qq|SELECT sum(p.inventory_accno_id)
661                       FROM parts p
662                       JOIN assembly a ON (a.parts_id = p.id)
663                       WHERE a.id = $form->{"id_$i"}|;
664           $sth = $dbh->prepare($query);
665           $sth->execute || $form->dberror($query);
666
667           if ($sth->fetchrow_array) {
668             $form->update_balance($dbh, "parts", "onhand",
669                                   qq|id = $form->{"id_$i"}|,
670                                   $baseqty * -1)
671               unless $form->{shipped};
672           }
673           $sth->finish;
674
675           # record assembly item as allocated
676           &process_assembly($dbh, $form, $form->{"id_$i"}, $baseqty);
677         } else {
678           $form->update_balance($dbh, "parts", "onhand",
679                                 qq|id = $form->{"id_$i"}|,
680                                 $baseqty * -1)
681             unless $form->{shipped};
682
683           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $baseqty, $basefactor, $i);
684         }
685       }
686
687       $project_id = 'NULL';
688       if ($form->{"projectnumber_$i"}) {
689         $project_id = $form->{"projectnumber_$i"};
690       }
691       $deliverydate =
692         ($form->{"deliverydate_$i"})
693         ? qq|'$form->{"deliverydate_$i"}'|
694         : "NULL";
695
696       # get pricegroup_id and save it
697       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_pg_$i"};
698       $pricegroup_id *= 1;
699       my $subtotal = $form->{"subtotal_$i"} * 1;
700
701       # save detail record in invoice table
702       $query = qq|INSERT INTO invoice (trans_id, parts_id, description,longdescription, qty,
703                   sellprice, fxsellprice, discount, allocated, assemblyitem,
704                   unit, deliverydate, project_id, serialnumber, pricegroup_id,
705                   ordnumber, transdate, cusordnumber, base_qty, subtotal)
706                   VALUES ($form->{id}, $form->{"id_$i"},
707                   '$form->{"description_$i"}', '$form->{"longdescription_$i"}', $form->{"qty_$i"},
708                   $form->{"sellprice_$i"}, $fxsellprice,
709                   $form->{"discount_$i"}, $allocated, 'f',
710                   '$form->{"unit_$i"}', $deliverydate, (SELECT id from project where projectnumber = '$project_id'),
711                   '$form->{"serialnumber_$i"}', '$pricegroup_id',
712                   '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}', $baseqty, '$subtotal')|;
713       $dbh->do($query) || $form->dberror($query);
714
715       if ($form->{lizenzen}) {
716         if ($form->{"licensenumber_$i"}) {
717           $query =
718             qq|SELECT i.id FROM invoice i WHERE i.trans_id=$form->{id} ORDER BY i.oid DESC LIMIT 1|;
719           $sth = $dbh->prepare($query);
720           $sth->execute || $form->dberror($query);
721
722           ($invoice_row_id) = $sth->fetchrow_array;
723           $sth->finish;
724
725           $query =
726             qq|INSERT INTO licenseinvoice (trans_id, license_id) VALUES ($invoice_row_id, $form->{"licensenumber_$i"})|;
727           $dbh->do($query) || $form->dberror($query);
728         }
729       }
730
731     }
732   }
733
734   $form->{datepaid} = $form->{invdate};
735
736   # total payments, don't move we need it here
737   for my $i (1 .. $form->{paidaccounts}) {
738     if ($form->{type} eq "credit_note") {
739       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
740     } else {
741       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
742     }
743     $form->{paid} += $form->{"paid_$i"};
744     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
745   }
746
747   my ($tax, $diff) = (0, 0);
748
749   $netamount = $form->round_amount($netamount, 2);
750
751   # figure out rounding errors for total amount vs netamount + taxes
752   if ($form->{taxincluded}) {
753
754     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
755     $diff += $amount - $netamount * $form->{exchangerate};
756     $netamount = $amount;
757
758     foreach my $item (split / /, $form->{taxaccounts}) {
759       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
760       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
761       $tax += $form->{amount}{ $form->{id} }{$item};
762       $netamount -= $form->{amount}{ $form->{id} }{$item};
763     }
764
765     $invoicediff += $diff;
766     ######## this only applies to tax included
767     if ($lastincomeaccno) {
768       $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
769     }
770
771   } else {
772     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
773     $diff      = $amount - $netamount * $form->{exchangerate};
774     $netamount = $amount;
775     foreach my $item (split / /, $form->{taxaccounts}) {
776       $form->{amount}{ $form->{id} }{$item} =
777         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
778       $amount =
779         $form->round_amount(
780                  $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
781                  2);
782       $diff +=
783         $amount - $form->{amount}{ $form->{id} }{$item} *
784         $form->{exchangerate};
785       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
786       $tax += $form->{amount}{ $form->{id} }{$item};
787     }
788   }
789
790   $form->{amount}{ $form->{id} }{ $form->{AR} } = $netamount + $tax;
791   $form->{paid} =
792     $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
793
794   # reverse AR
795   $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
796
797   # update exchangerate
798   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
799     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
800                                $form->{exchangerate}, 0);
801   }
802
803   foreach my $trans_id (keys %{ $form->{amount} }) {
804     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
805       next unless ($form->{expense_inventory} =~ /$accno/);
806       if (
807           ($form->{amount}{$trans_id}{$accno} =
808            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
809           ) != 0
810         ) {
811         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
812                     transdate, taxkey)
813                     VALUES ($trans_id, (SELECT c.id FROM chart c
814                                         WHERE c.accno = '$accno'),
815                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
816                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
817         $dbh->do($query) || $form->dberror($query);
818         $form->{amount}{$trans_id}{$accno} = 0;
819       }
820     }
821
822     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
823       if (
824           ($form->{amount}{$trans_id}{$accno} =
825            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
826           ) != 0
827         ) {
828         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
829                     transdate, taxkey)
830                     VALUES ($trans_id, (SELECT id FROM chart
831                                         WHERE accno = '$accno'),
832                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
833                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
834         $dbh->do($query) || $form->dberror($query);
835       }
836     }
837   }
838
839   # deduct payment differences from diff
840   for my $i (1 .. $form->{paidaccounts}) {
841     if ($form->{"paid_$i"} != 0) {
842       $amount =
843         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
844       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
845     }
846   }
847
848   # force AR entry if 0
849   #  $form->{amount}{$form->{id}}{$form->{AR}} = 1 if ($form->{amount}{$form->{id}}{$form->{AR}} == 0);
850
851   # record payments and offsetting AR
852   if (!$form->{storno}) {
853     for my $i (1 .. $form->{paidaccounts}) {
854   
855       if ($form->{"paid_$i"} != 0) {
856         my ($accno) = split /--/, $form->{"AR_paid_$i"};
857         $form->{"datepaid_$i"} = $form->{invdate}
858           unless ($form->{"datepaid_$i"});
859         $form->{datepaid} = $form->{"datepaid_$i"};
860   
861         $exchangerate = 0;
862   
863         if ($form->{currency} eq $form->{defaultcurrency}) {
864           $form->{"exchangerate_$i"} = 1;
865         } else {
866           $exchangerate =
867             $form->check_exchangerate($myconfig, $form->{currency},
868                                       $form->{"datepaid_$i"}, 'buy');
869   
870           $form->{"exchangerate_$i"} =
871             ($exchangerate)
872             ? $exchangerate
873             : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
874         }
875   
876         # record AR
877         $amount =
878           $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff,
879                               2);
880   
881         if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
882           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
883                       transdate)
884                       VALUES ($form->{id}, (SELECT c.id FROM chart c
885                                           WHERE c.accno = '$form->{AR}'),
886                       $amount, '$form->{"datepaid_$i"}')|;
887           $dbh->do($query) || $form->dberror($query);
888         }
889   
890         # record payment
891         $form->{"paid_$i"} *= -1;
892   
893         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
894                     source, memo)
895                     VALUES ($form->{id}, (SELECT c.id FROM chart c
896                                         WHERE c.accno = '$accno'),
897                     $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
898                     '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
899         $dbh->do($query) || $form->dberror($query);
900   
901         # exchangerate difference
902         $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
903           $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
904   
905         # gain/loss
906         $amount =
907           $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
908           $form->{"exchangerate_$i"};
909         if ($amount > 0) {
910           $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
911             $amount;
912         } else {
913           $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
914             $amount;
915         }
916   
917         $diff = 0;
918   
919         # update exchange rate
920         if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
921           $form->update_exchangerate($dbh, $form->{currency},
922                                     $form->{"datepaid_$i"},
923                                     $form->{"exchangerate_$i"}, 0);
924         }
925       }
926     }
927   }
928
929   # record exchange rate differences and gains/losses
930   foreach my $accno (keys %{ $form->{fx} }) {
931     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
932       if (
933           ($form->{fx}{$accno}{$transdate} =
934            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
935           ) != 0
936         ) {
937
938         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
939                     transdate, cleared, fx_transaction)
940                     VALUES ($form->{id},
941                            (SELECT c.id FROM chart c
942                             WHERE c.accno = '$accno'),
943                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
944         $dbh->do($query) || $form->dberror($query);
945       }
946     }
947   }
948
949   $amount = $netamount + $tax;
950
951   # set values which could be empty to 0
952   $form->{terms}       *= 1;
953   $form->{taxincluded} *= 1;
954   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
955   my $duedate  = ($form->{duedate}) ? qq|'$form->{duedate}'|  : "NULL";
956   my $deliverydate =
957     ($form->{deliverydate}) ? qq|'$form->{deliverydate}'| : "NULL";
958
959   # fill in subject if there is none
960   $form->{subject} = qq|$form->{label} $form->{invnumber}|
961     unless $form->{subject};
962
963   # if there is a message stuff it into the intnotes
964   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
965   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
966   my $now = scalar localtime;
967   $form->{intnotes} .= qq|\r
968 \r| if $form->{intnotes};
969
970   $form->{intnotes} .= qq|[email]\r
971 Date: $now
972 To: $form->{email}\r
973 $cc${bcc}Subject: $form->{subject}\r
974 \r
975 Message: $form->{message}\r| if $form->{message};
976
977   # save AR record
978   $query = qq|UPDATE ar set
979               invnumber = '$form->{invnumber}',
980               ordnumber = '$form->{ordnumber}',
981               quonumber = '$form->{quonumber}',
982               cusordnumber = '$form->{cusordnumber}',
983               transdate = '$form->{invdate}',
984               customer_id = $form->{customer_id},
985               amount = $amount,
986               netamount = $netamount,
987               paid = $form->{paid},
988               datepaid = $datepaid,
989               duedate = $duedate,
990               deliverydate = $deliverydate,
991               invoice = '1',
992               shippingpoint = '$form->{shippingpoint}',
993               shipvia = '$form->{shipvia}',
994               terms = $form->{terms},
995               notes = '$form->{notes}',
996               intnotes = '$form->{intnotes}',
997               taxincluded = '$form->{taxincluded}',
998               curr = '$form->{currency}',
999               department_id = $form->{department_id},
1000               payment_id = $form->{payment_id},
1001               type = '$form->{type}',
1002               language_id = $form->{language_id},
1003               taxzone_id = $form->{taxzone_id},
1004               shipto_id = $form->{shipto_id},
1005               delivery_customer_id = $form->{delivery_customer_id},
1006               delivery_vendor_id = $form->{delivery_vendor_id},
1007               employee_id = $form->{employee_id},
1008               storno = '$form->{storno}',
1009               cp_id = $form->{contact_id}
1010               WHERE id = $form->{id}
1011              |;
1012   $dbh->do($query) || $form->dberror($query);
1013
1014   if ($form->{storno}) {
1015     $query = qq| update ar set paid=paid+amount where id=$form->{storno_id}|;
1016     $dbh->do($query) || $form->dberror($query);
1017     $query = qq| update ar set storno='$form->{storno}' where id=$form->{storno_id}|;
1018     $dbh->do($query) || $form->dberror($query);
1019     $query = qq§ update ar set intnotes='Rechnung storniert am $form->{invdate} ' || intnotes where id=$form->{storno_id}§;
1020     $dbh->do($query) || $form->dberror($query);
1021
1022     $query = qq| update ar set paid=amount where id=$form->{id}|;
1023     $dbh->do($query) || $form->dberror($query);
1024   }
1025
1026   $form->{pago_total} = $amount;
1027
1028   # add shipto
1029   $form->{name} = $form->{customer};
1030   $form->{name} =~ s/--$form->{customer_id}//;
1031
1032   if (!$form->{shipto_id}) {
1033     $form->add_shipto($dbh, $form->{id}, "AR");
1034   }
1035
1036   # save printed, emailed and queued
1037   $form->save_status($dbh);
1038
1039   if ($form->{webdav}) {
1040     &webdav_folder($myconfig, $form);
1041   }
1042
1043   my $rc = $dbh->commit;
1044   $dbh->disconnect;
1045
1046   $main::lxdebug->leave_sub();
1047
1048   return $rc;
1049 }
1050
1051 sub post_payment {
1052   $main::lxdebug->enter_sub();
1053
1054   my ($self, $myconfig, $form, $locale) = @_;
1055
1056   # connect to database, turn off autocommit
1057   my $dbh = $form->dbconnect_noauto($myconfig);
1058
1059   $form->{datepaid} = $form->{invdate};
1060
1061   # total payments, don't move we need it here
1062   for my $i (1 .. $form->{paidaccounts}) {
1063     if ($form->{type} eq "credit_note") {
1064       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
1065     } else {
1066       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
1067     } 
1068     $form->{paid} += $form->{"paid_$i"};
1069     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
1070   }
1071
1072   $form->{exchangerate} =
1073       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
1074                               "buy");
1075
1076   # record payments and offsetting AR
1077   for my $i (1 .. $form->{paidaccounts}) {
1078
1079     if ($form->{"paid_$i"} != 0) {
1080       my ($accno) = split /--/, $form->{"AR_paid_$i"};
1081       $form->{"datepaid_$i"} = $form->{invdate}
1082         unless ($form->{"datepaid_$i"});
1083       $form->{datepaid} = $form->{"datepaid_$i"};
1084
1085       $exchangerate = 0;
1086       if (($form->{currency} eq $form->{defaultcurrency}) || ($form->{defaultcurrency} eq "")) {
1087         $form->{"exchangerate_$i"} = 1;
1088       } else {
1089         $exchangerate =
1090           $form->check_exchangerate($myconfig, $form->{currency},
1091                                     $form->{"datepaid_$i"}, 'buy');
1092
1093         $form->{"exchangerate_$i"} =
1094           ($exchangerate)
1095           ? $exchangerate
1096           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
1097       }
1098
1099       # record AR
1100       $amount =
1101         $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate"},
1102                             2);
1103
1104
1105       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1106                                       WHERE c.accno = '$form->{AR}') AND amount=$amount AND transdate='$form->{"datepaid_$i"}'|;
1107       $dbh->do($query) || $form->dberror($query);
1108
1109       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
1110                   transdate)
1111                   VALUES ($form->{id}, (SELECT c.id FROM chart c
1112                                       WHERE c.accno = '$form->{AR}'),
1113                   $amount, '$form->{"datepaid_$i"}')|;
1114       $dbh->do($query) || $form->dberror($query);
1115
1116
1117       # record payment
1118       $form->{"paid_$i"} *= -1;
1119
1120       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1121                                       WHERE c.accno = '$accno') AND amount=$form->{"paid_$i"} AND transdate='$form->{"datepaid_$i"}' AND source='$form->{"source_$i"}' AND memo='$form->{"memo_$i"}'|;
1122       $dbh->do($query) || $form->dberror($query);
1123
1124       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
1125                   source, memo)
1126                   VALUES ($form->{id}, (SELECT c.id FROM chart c
1127                                       WHERE c.accno = '$accno'),
1128                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
1129                   '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
1130       $dbh->do($query) || $form->dberror($query);
1131
1132
1133       # gain/loss
1134       $amount =
1135         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
1136         $form->{"exchangerate_$i"};
1137       if ($amount > 0) {
1138         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
1139           $amount;
1140       } else {
1141         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
1142           $amount;
1143       }
1144
1145       $diff = 0;
1146
1147       # update exchange rate
1148       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
1149         $form->update_exchangerate($dbh, $form->{currency},
1150                                    $form->{"datepaid_$i"},
1151                                    $form->{"exchangerate_$i"}, 0);
1152       }
1153     }
1154   }
1155
1156   # record exchange rate differences and gains/losses
1157   foreach my $accno (keys %{ $form->{fx} }) {
1158     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
1159       if (
1160           ($form->{fx}{$accno}{$transdate} =
1161            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
1162           ) != 0
1163         ) {
1164         $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1165                                         WHERE c.accno = '$accno') AND amount=$form->{fx}{$accno}{$transdate} AND transdate='$transdate' AND cleared='0' AND fx_transaction='1'|;
1166         $dbh->do($query) || $form->dberror($query);
1167         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
1168                     transdate, cleared, fx_transaction)
1169                     VALUES ($form->{id},
1170                            (SELECT c.id FROM chart c
1171                             WHERE c.accno = '$accno'),
1172                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
1173         $dbh->do($query) || $form->dberror($query);
1174       }
1175     }
1176   }
1177   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
1178
1179   # save AR record
1180   my $query = qq|UPDATE ar set
1181               paid = $form->{paid},
1182               datepaid = $datepaid
1183               WHERE id=$form->{id}|;
1184
1185   $dbh->do($query) || $form->dberror($query);
1186
1187   my $rc = $dbh->commit;
1188   $dbh->disconnect;
1189
1190   $main::lxdebug->leave_sub();
1191
1192   return $rc;
1193 }
1194
1195 sub process_assembly {
1196   $main::lxdebug->enter_sub();
1197
1198   my ($dbh, $form, $id, $totalqty) = @_;
1199
1200   my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
1201                  p.partnumber, p.description, p.unit,
1202                  p.inventory_accno_id, p.income_accno_id,
1203                  p.expense_accno_id
1204                  FROM assembly a
1205                  JOIN parts p ON (a.parts_id = p.id)
1206                  WHERE a.id = $id|;
1207   my $sth = $dbh->prepare($query);
1208   $sth->execute || $form->dberror($query);
1209
1210   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1211
1212     my $allocated = 0;
1213
1214     $ref->{inventory_accno_id} *= 1;
1215     $ref->{expense_accno_id}   *= 1;
1216
1217     map { $ref->{$_} =~ s/\'/\'\'/g } (qw(partnumber description unit));
1218
1219     # multiply by number of assemblies
1220     $ref->{qty} *= $totalqty;
1221
1222     if ($ref->{assembly}) {
1223       &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty});
1224       next;
1225     } else {
1226       if ($ref->{inventory_accno_id}) {
1227         $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty});
1228       }
1229     }
1230
1231     # save detail record for individual assembly item in invoice table
1232     $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
1233                 sellprice, fxsellprice, allocated, assemblyitem, unit)
1234                 VALUES
1235                 ($form->{id}, '$ref->{description}',
1236                 $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't',
1237                 '$ref->{unit}')|;
1238     $dbh->do($query) || $form->dberror($query);
1239
1240   }
1241
1242   $sth->finish;
1243
1244   $main::lxdebug->leave_sub();
1245 }
1246
1247 sub cogs {
1248   $main::lxdebug->enter_sub();
1249
1250   my ($dbh, $form, $id, $totalqty, $basefactor, $row) = @_;
1251   $form->{taxzone_id} *=1;
1252   my $transdate = ($form->{invdate}) ? "'$form->{invdate}'" : "current_date";
1253   my $query = qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice,
1254                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1255                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1256                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid
1257                   FROM invoice i, parts p
1258                   LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1259                   LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1260                   LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1261                   WHERE i.parts_id = p.id
1262                   AND i.parts_id = $id
1263                   AND (i.base_qty + i.allocated) < 0
1264                   ORDER BY trans_id|;
1265   my $sth = $dbh->prepare($query);
1266   $sth->execute || $form->dberror($query);
1267
1268   my $allocated = 0;
1269   my $qty;
1270
1271   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1272     if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
1273       $qty = $totalqty;
1274     }
1275
1276     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|,
1277                           $qty);
1278
1279     # total expenses and inventory
1280     # sellprice is the cost of the item
1281     $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / $basefactor, 2);
1282
1283     if (!$main::eur) {
1284       $ref->{expense_accno} = ($form->{"expense_accno_$row"}) ? $form->{"expense_accno_$row"} : $ref->{expense_accno};
1285       # add to expense
1286       $form->{amount}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
1287       $form->{expense_inventory} .= " " . $ref->{expense_accno};
1288       $ref->{inventory_accno} = ($form->{"inventory_accno_$row"}) ? $form->{"inventory_accno_$row"} : $ref->{inventory_accno};
1289       # deduct inventory
1290       $form->{amount}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
1291       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
1292     }
1293
1294     # add allocated
1295     $allocated += -$qty;
1296
1297     last if (($totalqty -= $qty) <= 0);
1298   }
1299
1300   $sth->finish;
1301
1302   $main::lxdebug->leave_sub();
1303
1304   return $allocated;
1305 }
1306
1307 sub reverse_invoice {
1308   $main::lxdebug->enter_sub();
1309
1310   my ($dbh, $form) = @_;
1311
1312   # reverse inventory items
1313   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
1314                  p.inventory_accno_id
1315                  FROM invoice i
1316                  JOIN parts p ON (i.parts_id = p.id)
1317                  WHERE i.trans_id = $form->{id}|;
1318   my $sth = $dbh->prepare($query);
1319   $sth->execute || $form->dberror($query);
1320
1321   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1322
1323     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1324
1325       # if the invoice item is not an assemblyitem adjust parts onhand
1326       if (!$ref->{assemblyitem}) {
1327
1328         # adjust onhand in parts table
1329         $form->update_balance($dbh, "parts", "onhand",
1330                               qq|id = $ref->{parts_id}|,
1331                               $ref->{qty});
1332       }
1333
1334       # loop if it is an assembly
1335       next if ($ref->{assembly});
1336
1337       # de-allocated purchases
1338       $query = qq|SELECT i.id, i.trans_id, i.allocated
1339                   FROM invoice i
1340                   WHERE i.parts_id = $ref->{parts_id}
1341                   AND i.allocated > 0
1342                   ORDER BY i.trans_id DESC|;
1343       my $sth = $dbh->prepare($query);
1344       $sth->execute || $form->dberror($query);
1345
1346       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
1347         $qty = $ref->{qty};
1348         if (($ref->{qty} - $inhref->{allocated}) > 0) {
1349           $qty = $inhref->{allocated};
1350         }
1351
1352         # update invoice
1353         $form->update_balance($dbh, "invoice", "allocated",
1354                               qq|id = $inhref->{id}|,
1355                               $qty * -1);
1356
1357         last if (($ref->{qty} -= $qty) <= 0);
1358       }
1359       $sth->finish;
1360     }
1361   }
1362
1363   $sth->finish;
1364
1365   # delete acc_trans
1366   $query = qq|DELETE FROM acc_trans
1367               WHERE trans_id = $form->{id}|;
1368   $dbh->do($query) || $form->dberror($query);
1369
1370   # delete invoice entries
1371   $query = qq|DELETE FROM invoice
1372               WHERE trans_id = $form->{id}|;
1373   $dbh->do($query) || $form->dberror($query);
1374
1375   if ($form->{lizenzen}) {
1376     $query = qq|DELETE FROM licenseinvoice
1377               WHERE trans_id in (SELECT id FROM invoice WHERE trans_id = $form->{id})|;
1378     $dbh->do($query) || $form->dberror($query);
1379   }
1380
1381   $query = qq|DELETE FROM shipto
1382               WHERE trans_id = $form->{id} AND module = 'AR'|;
1383   $dbh->do($query) || $form->dberror($query);
1384
1385   $main::lxdebug->leave_sub();
1386 }
1387
1388 sub delete_invoice {
1389   $main::lxdebug->enter_sub();
1390
1391   my ($self, $myconfig, $form, $spool) = @_;
1392
1393   # connect to database
1394   my $dbh = $form->dbconnect_noauto($myconfig);
1395
1396   &reverse_invoice($dbh, $form);
1397
1398   # delete AR record
1399   my $query = qq|DELETE FROM ar
1400                  WHERE id = $form->{id}|;
1401   $dbh->do($query) || $form->dberror($query);
1402
1403   # delete spool files
1404   $query = qq|SELECT s.spoolfile FROM status s
1405               WHERE s.trans_id = $form->{id}|;
1406   my $sth = $dbh->prepare($query);
1407   $sth->execute || $self->dberror($query);
1408
1409   my $spoolfile;
1410   my @spoolfiles = ();
1411
1412   while (($spoolfile) = $sth->fetchrow_array) {
1413     push @spoolfiles, $spoolfile;
1414   }
1415   $sth->finish;
1416
1417   # delete status entries
1418   $query = qq|DELETE FROM status
1419               WHERE trans_id = $form->{id}|;
1420   $dbh->do($query) || $form->dberror($query);
1421
1422   my $rc = $dbh->commit;
1423   $dbh->disconnect;
1424
1425   if ($rc) {
1426     foreach $spoolfile (@spoolfiles) {
1427       unlink "$spool/$spoolfile" if $spoolfile;
1428     }
1429   }
1430
1431   $main::lxdebug->leave_sub();
1432
1433   return $rc;
1434 }
1435
1436 sub retrieve_invoice {
1437   $main::lxdebug->enter_sub();
1438
1439   my ($self, $myconfig, $form) = @_;
1440
1441   # connect to database
1442   my $dbh = $form->dbconnect_noauto($myconfig);
1443
1444   my $query;
1445
1446   if ($form->{id}) {
1447
1448     # get default accounts and last invoice number
1449     $query = qq|SELECT (SELECT c.accno FROM chart c
1450                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1451                        (SELECT c.accno FROM chart c
1452                         WHERE d.income_accno_id = c.id) AS income_accno,
1453                        (SELECT c.accno FROM chart c
1454                         WHERE d.expense_accno_id = c.id) AS expense_accno,
1455                        (SELECT c.accno FROM chart c
1456                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1457                        (SELECT c.accno FROM chart c
1458                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
1459                 d.curr AS currencies
1460                 FROM defaults d|;
1461   } else {
1462     $query = qq|SELECT (SELECT c.accno FROM chart c
1463                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1464                        (SELECT c.accno FROM chart c
1465                         WHERE d.income_accno_id = c.id) AS income_accno,
1466                        (SELECT c.accno FROM chart c
1467                         WHERE d.expense_accno_id = c.id) AS expense_accno,
1468                        (SELECT c.accno FROM chart c
1469                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1470                        (SELECT c.accno FROM chart c
1471                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
1472                 d.curr AS currencies, current_date AS invdate
1473                 FROM defaults d|;
1474   }
1475   my $sth = $dbh->prepare($query);
1476   $sth->execute || $form->dberror($query);
1477
1478   my $ref = $sth->fetchrow_hashref(NAME_lc);
1479   map { $form->{$_} = $ref->{$_} } keys %$ref;
1480   $sth->finish;
1481
1482   if ($form->{id}) {
1483
1484     # retrieve invoice
1485     $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
1486                 a.transdate AS invdate, a.deliverydate, a.paid, a.storno, a.gldate,
1487                 a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes, a.taxzone_id,
1488                 a.duedate, a.taxincluded, a.curr AS currency, a.shipto_id, a.cp_id,
1489                 a.employee_id, e.name AS employee, a.payment_id, a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type
1490                 FROM ar a
1491                 LEFT JOIN employee e ON (e.id = a.employee_id)
1492                 WHERE a.id = $form->{id}|;
1493     $sth = $dbh->prepare($query);
1494     $sth->execute || $form->dberror($query);
1495
1496     $ref = $sth->fetchrow_hashref(NAME_lc);
1497     map { $form->{$_} = $ref->{$_} } keys %$ref;
1498     $sth->finish;
1499
1500     $form->{exchangerate} =
1501       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
1502                               "buy");
1503     # get shipto
1504     $query = qq|SELECT s.* FROM shipto s
1505                 WHERE s.trans_id = $form->{id} AND s.module = 'AR'|;
1506     $sth = $dbh->prepare($query);
1507     $sth->execute || $form->dberror($query);
1508
1509     $ref = $sth->fetchrow_hashref(NAME_lc);
1510     delete($ref->{id});
1511     map { $form->{$_} = $ref->{$_} } keys %$ref;
1512     $sth->finish;
1513
1514    if ($form->{delivery_customer_id}) {
1515       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
1516       $sth = $dbh->prepare($query);
1517       $sth->execute || $form->dberror($query);
1518       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
1519       $sth->finish;
1520     }
1521
1522     if ($form->{delivery_vendor_id}) {
1523       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
1524       $sth = $dbh->prepare($query);
1525       $sth->execute || $form->dberror($query);
1526       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
1527       $sth->finish;
1528     }
1529
1530     # get printed, emailed
1531     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
1532                 FROM status s
1533                 WHERE s.trans_id = $form->{id}|;
1534     $sth = $dbh->prepare($query);
1535     $sth->execute || $form->dberror($query);
1536
1537     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1538       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
1539       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
1540       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
1541         if $ref->{spoolfile};
1542     }
1543     $sth->finish;
1544     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
1545
1546     my $transdate =
1547       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
1548       $form->{invdate} ? $dbh->quote($form->{invdate}) :
1549       "current_date";
1550
1551     if (!$form->{taxzone_id}) {
1552       $form->{taxzone_id} = 0;
1553     }
1554     # retrieve individual items
1555     $query = qq|SELECT  
1556                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1557                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1558                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
1559                 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice,
1560                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
1561                 i.project_id, pr.projectnumber, i.serialnumber,
1562                 p.partnumber, p.assembly, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, i.id AS invoice_pos,
1563                 pg.partsgroup, i.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=i.pricegroup_id) as pricegroup,
1564                 i.ordnumber, i.transdate, i.cusordnumber, p.formel, i.subtotal
1565                 FROM invoice i
1566                 JOIN parts p ON (i.parts_id = p.id)
1567                 LEFT JOIN project pr ON (i.project_id = pr.id)
1568                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1569                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1570                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1571                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1572                 WHERE i.trans_id = $form->{id}
1573                 AND NOT i.assemblyitem = '1'
1574                 ORDER BY i.id|;
1575     $sth = $dbh->prepare($query);
1576
1577     $sth->execute || $form->dberror($query);
1578     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1579       if (!$ref->{"part_inventory_accno_id"}) {
1580         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
1581       }
1582       delete($ref->{"part_inventory_accno_id"});
1583
1584     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
1585       my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
1586       my $stw = $dbh->prepare($query);
1587       $stw->execute || $form->dberror($query);
1588       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
1589       $stw->finish;
1590     }
1591
1592     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
1593       my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
1594       my $stw = $dbh->prepare($query);
1595       $stw->execute || $form->dberror($query);
1596       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
1597       $stw->finish;
1598     }
1599
1600     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
1601       my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
1602       my $stw = $dbh->prepare($query);
1603       $stw->execute || $form->dberror($query);
1604       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
1605       $stw->finish;
1606     }
1607
1608       # get tax rates and description
1609       $accno_id =
1610         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1611     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1612               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
1613               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
1614               ORDER BY c.accno|;
1615       $stw = $dbh->prepare($query);
1616       $stw->execute || $form->dberror($query);
1617       $ref->{taxaccounts} = "";
1618       my $i=0;
1619       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1620
1621         #    if ($customertax{$ref->{accno}}) {
1622         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1623           $i++;
1624           $ptr->{accno} = $i;
1625         }
1626         $ref->{taxaccounts} .= "$ptr->{accno} ";
1627
1628         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1629           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1630           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1631           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1632           $form->{taxaccounts} .= "$ptr->{accno} ";
1633         }
1634
1635       }
1636
1637       if ($form->{lizenzen}) {
1638         $query = qq|SELECT l.licensenumber, l.id AS licenseid
1639                  FROM license l, licenseinvoice li
1640                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
1641         $stg = $dbh->prepare($query);
1642         $stg->execute || $form->dberror($query);
1643         ($licensenumber, $licenseid) = $stg->fetchrow_array();
1644         $ref->{lizenzen} =
1645           "<option value=\"$licenseid\">$licensenumber</option>";
1646         $stg->finish();
1647       }
1648       if ($form->{type} eq "credit_note") {
1649         $ref->{qty} *= -1;
1650       }
1651
1652       chop $ref->{taxaccounts};
1653       push @{ $form->{invoice_details} }, $ref;
1654       $stw->finish;
1655     }
1656     $sth->finish;
1657
1658     if ($form->{webdav}) {
1659       &webdav_folder($myconfig, $form);
1660     }
1661   }
1662
1663   my $rc = $dbh->commit;
1664   $dbh->disconnect;
1665
1666   $main::lxdebug->leave_sub();
1667
1668   return $rc;
1669 }
1670
1671 sub get_customer {
1672   $main::lxdebug->enter_sub();
1673
1674   my ($self, $myconfig, $form) = @_;
1675
1676   # connect to database
1677   my $dbh = $form->dbconnect($myconfig);
1678
1679   my $dateformat = $myconfig->{dateformat};
1680   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1681
1682   my $duedate =
1683     ($form->{invdate})
1684     ? "to_date('$form->{invdate}', '$dateformat')"
1685     : "current_date";
1686
1687   $form->{customer_id} *= 1;
1688
1689   # get customer
1690   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
1691                  c.email, c.cc, c.bcc, c.language_id, c.payment_id AS customer_payment_id,
1692                  c.street, c.zipcode, c.city, c.country,
1693                  $duedate + c.terms AS duedate, c.notes AS intnotes,
1694                  b.discount AS tradediscount, b.description AS business, c.klass as customer_klass, c.taxzone_id
1695                  FROM customer c
1696                  LEFT JOIN business b ON (b.id = c.business_id)
1697                  WHERE c.id = $form->{customer_id}|;
1698   my $sth = $dbh->prepare($query);
1699   $sth->execute || $form->dberror($query);
1700
1701   $ref = $sth->fetchrow_hashref(NAME_lc);
1702
1703   map { $form->{$_} = $ref->{$_} } keys %$ref;
1704   $sth->finish;
1705
1706   my $query = qq|SELECT sum(a.amount-a.paid) AS dunning_amount FROM ar a WHERE a.paid < a.amount AND a.customer_id=$form->{customer_id} AND a.dunning_id IS NOT NULL|;
1707   my $sth = $dbh->prepare($query);
1708
1709   $sth->execute || $form->dberror($query);
1710   
1711   $ref = $sth->fetchrow_hashref(NAME_lc);
1712
1713   map { $form->{$_} = $ref->{$_} } keys %$ref;
1714   $sth->finish;
1715
1716   #print(STDERR "DUNNING AMOUTN $form->{dunning_amount}\n");
1717
1718   my $query = qq|SELECT dnn.dunning_description AS max_dunning_level FROM dunning_config dnn WHERE id in (select dunning_id from ar WHERE paid < amount AND customer_id=$form->{customer_id} AND dunning_id IS NOT NULL) ORDER BY dunning_level DESC LIMIT 1|;
1719   my $sth = $dbh->prepare($query);
1720
1721   $sth->execute || $form->dberror($query);
1722
1723   $ref = $sth->fetchrow_hashref(NAME_lc);
1724
1725   map { $form->{$_} = $ref->{$_} } keys %$ref;
1726   $sth->finish;
1727   #print(STDERR "LEVEL $form->{max_dunning_level}\n");
1728
1729
1730   #check whether payment_terms are better than old payment_terms
1731   if (($form->{payment_id} ne "") && ($form->{customer_payment_id} ne "")) {
1732     my $query = qq|select (select ranking from payment_terms WHERE id = $form->{payment_id}), (select ranking from payment_terms WHERE id = $form->{customer_payment_id})|;
1733     my $stw = $dbh->prepare($query);
1734     $stw->execute || $form->dberror($query);
1735     ($old_ranking, $new_ranking) = $stw->fetchrow_array;
1736     $stw->finish;
1737     if ($new_ranking > $old_ranking) {
1738       $form->{payment_id} =$form->{customer_payment_id};
1739     }
1740   }
1741   if ($form->{payment_id} eq "") {
1742     $form->{payment_id} =$form->{customer_payment_id};
1743   }
1744
1745   $form->{creditremaining} = $form->{creditlimit};
1746   $query = qq|SELECT SUM(a.amount - a.paid)
1747               FROM ar a
1748               WHERE a.customer_id = $form->{customer_id}|;
1749   $sth = $dbh->prepare($query);
1750   $sth->execute || $form->dberror($query);
1751
1752   ($form->{creditremaining}) -= $sth->fetchrow_array;
1753
1754   $sth->finish;
1755
1756   $query = qq|SELECT o.amount,
1757                 (SELECT e.buy FROM exchangerate e
1758                  WHERE e.curr = o.curr
1759                  AND e.transdate = o.transdate)
1760               FROM oe o
1761               WHERE o.customer_id = $form->{customer_id}
1762               AND o.quotation = '0'
1763               AND o.closed = '0'|;
1764   $sth = $dbh->prepare($query);
1765   $sth->execute || $form->dberror($query);
1766
1767   while (my ($amount, $exch) = $sth->fetchrow_array) {
1768     $exch = 1 unless $exch;
1769     $form->{creditremaining} -= $amount * $exch;
1770   }
1771   $sth->finish;
1772
1773   $form->get_contacts($dbh, $form->{customer_id});
1774   $form->{cp_id} *= 1;
1775
1776   # get contact if selected
1777   if ($form->{cp_id}) {
1778     $form->get_contact($dbh, $form->{cp_id});
1779   }
1780
1781   # get shipto if we did not converted an order or invoice
1782   if (!$form->{shipto}) {
1783     map { delete $form->{$_} }
1784       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
1785
1786     $query = qq|SELECT s.* FROM shipto s
1787                 WHERE s.trans_id = $form->{customer_id} AND s.module = 'CT'|;
1788     $sth = $dbh->prepare($query);
1789     $sth->execute || $form->dberror($query);
1790
1791     $ref = $sth->fetchrow_hashref(NAME_lc);
1792     undef($ref->{id});
1793     map { $form->{$_} = $ref->{$_} } keys %$ref;
1794     $sth->finish;
1795   }
1796
1797   # get taxes we charge for this customer
1798   $query = qq|SELECT c.accno
1799               FROM chart c
1800               JOIN customertax ct ON (ct.chart_id = c.id)
1801               WHERE ct.customer_id = $form->{customer_id}|;
1802   $sth = $dbh->prepare($query);
1803   $sth->execute || $form->dberror($query);
1804
1805   my $customertax = ();
1806   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1807     $customertax{ $ref->{accno} } = 1;
1808   }
1809   $sth->finish;
1810
1811   # get shipping addresses
1812   $query = qq|SELECT s.shipto_id,s.shiptoname,s.shiptodepartment_1
1813               FROM shipto s
1814               WHERE s.trans_id = $form->{customer_id}|;
1815   $sth = $dbh->prepare($query);
1816   $sth->execute || $form->dberror($query);
1817
1818   my $customertax = ();
1819   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1820     push(@{ $form->{SHIPTO} }, $ref);
1821   }
1822   $sth->finish;
1823
1824   # setup last accounts used for this customer
1825   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
1826     $query = qq|SELECT c.accno, c.description, c.link, c.category
1827                 FROM chart c
1828                 JOIN acc_trans ac ON (ac.chart_id = c.id)
1829                 JOIN ar a ON (a.id = ac.trans_id)
1830                 WHERE a.customer_id = $form->{customer_id}
1831                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
1832                 AND a.id IN (SELECT max(a2.id) FROM ar a2
1833                              WHERE a2.customer_id = $form->{customer_id})|;
1834     $sth = $dbh->prepare($query);
1835     $sth->execute || $form->dberror($query);
1836
1837     my $i = 0;
1838     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1839       if ($ref->{category} eq 'I') {
1840         $i++;
1841         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
1842       }
1843       if ($ref->{category} eq 'A') {
1844         $form->{ARselected} = $form->{AR_1} =
1845           "$ref->{accno}--$ref->{description}";
1846       }
1847     }
1848     $sth->finish;
1849     $form->{rowcount} = $i if ($i && !$form->{type});
1850   }
1851
1852   $dbh->disconnect;
1853
1854   $main::lxdebug->leave_sub();
1855 }
1856
1857 sub retrieve_item {
1858   $main::lxdebug->enter_sub();
1859
1860   my ($self, $myconfig, $form) = @_;
1861
1862   # connect to database
1863   my $dbh = $form->dbconnect($myconfig);
1864
1865   my $i = $form->{rowcount};
1866
1867   my $where = "NOT p.obsolete = '1'";
1868
1869   if ($form->{"partnumber_$i"}) {
1870     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1871     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1872   }
1873   if ($form->{"description_$i"}) {
1874     my $description = $form->like(lc $form->{"description_$i"});
1875     $where .= " AND lower(p.description) LIKE '$description'";
1876   }
1877
1878   if ($form->{"partsgroup_$i"}) {
1879     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1880     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1881   }
1882
1883   if ($form->{"description_$i"}) {
1884     $where .= " ORDER BY p.description";
1885   } else {
1886     $where .= " ORDER BY p.partnumber";
1887   }
1888
1889   my $transdate;
1890   if ($form->{type} eq "invoice") {
1891     $transdate =
1892       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
1893       $form->{invdate} ? $dbh->quote($form->{invdate}) :
1894       "current_date";
1895   } else {
1896     $transdate =
1897       $form->{transdate} ? $dbh->quote($form->{transdate}) :
1898       "current_date";
1899   }
1900
1901   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1902                         p.listprice, p.inventory_accno_id,
1903                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1904                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1905                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
1906                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1907                  pg.partsgroup, p.formel, p.payment_id AS part_payment_id
1908                  FROM parts p
1909                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1910                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1911                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1912                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1913                  WHERE $where|;
1914   my $sth = $dbh->prepare($query);
1915   $sth->execute || $form->dberror($query);
1916
1917   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1918
1919     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1920     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1921     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1922     if (!$ref->{inventory_accno_id}) {
1923       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1924     }
1925     delete($ref->{inventory_accno_id});
1926
1927     #set expense_accno=inventory_accno if they are different => bilanz
1928
1929
1930     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
1931       my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
1932       my $stw = $dbh->prepare($query);
1933       $stw->execute || $form->dberror($query);
1934       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
1935       $stw->finish;
1936     }
1937
1938     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
1939       my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
1940       my $stw = $dbh->prepare($query);
1941       $stw->execute || $form->dberror($query);
1942       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
1943       $stw->finish;
1944     }
1945
1946     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
1947       my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
1948       my $stw = $dbh->prepare($query);
1949       $stw->execute || $form->dberror($query);
1950       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
1951       $stw->finish;
1952     }
1953
1954     #check whether payment_terms are better than old payment_terms
1955     if (($form->{payment_id} ne "") && ($ref->{part_payment_id} ne "")) {
1956       my $query = qq|select (select ranking from payment_terms WHERE id = $form->{payment_id}), (select ranking from payment_terms WHERE id = $ref->{part_payment_id})|;
1957       my $stw = $dbh->prepare($query);
1958       $stw->execute || $form->dberror($query);
1959       ($old_ranking, $new_ranking) = $stw->fetchrow_array;
1960       $stw->finish;
1961       if ($new_ranking <= $old_ranking) {
1962         $ref->{part_payment_id} = "";
1963       }
1964     }
1965
1966     # get tax rates and description
1967     $accno_id =
1968       ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1969     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1970               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
1971               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
1972               ORDER BY c.accno|;
1973     $stw = $dbh->prepare($query);
1974     $stw->execute || $form->dberror($query);
1975
1976     $ref->{taxaccounts} = "";
1977     my $i = 0;
1978     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1979
1980       #    if ($customertax{$ref->{accno}}) {
1981       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1982         $i++;
1983         $ptr->{accno} = $i;
1984       }
1985       $ref->{taxaccounts} .= "$ptr->{accno} ";
1986
1987       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1988         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1989         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1990         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1991         $form->{taxaccounts} .= "$ptr->{accno} ";
1992       }
1993
1994     }
1995
1996     $stw->finish;
1997     chop $ref->{taxaccounts};
1998     if ($form->{language_id}) {
1999       $query = qq|SELECT tr.translation, tr.longdescription
2000                 FROM translation tr
2001                 WHERE tr.language_id=$form->{language_id} AND tr.parts_id=$ref->{id}|;
2002       $stw = $dbh->prepare($query);
2003       $stw->execute || $form->dberror($query);
2004       my ($translation, $longdescription) = $stw->fetchrow_array();
2005       if ($translation ne "") {
2006         $ref->{description} = $translation;
2007         $ref->{longdescription} = $longdescription;
2008
2009       } else {
2010         $query = qq|SELECT tr.translation, tr.longdescription
2011                 FROM translation tr
2012                 WHERE tr.language_id in (select id from language where article_code=(select article_code from language where id = $form->{language_id})) AND tr.parts_id=$ref->{id} LIMIT 1|;
2013         $stg = $dbh->prepare($query);
2014         $stg->execute || $form->dberror($query);
2015         my ($translation) = $stg->fetchrow_array();
2016         if ($translation ne "") {
2017           $ref->{description} = $translation;
2018           $ref->{longdescription} = $longdescription;
2019         }
2020         $stg->finish;
2021       }
2022       $stw->finish;
2023     }
2024
2025     push @{ $form->{item_list} }, $ref;
2026
2027     if ($form->{lizenzen}) {
2028       if ($ref->{inventory_accno} > 0) {
2029         $query =
2030           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
2031         $stw = $dbh->prepare($query);
2032         $stw->execute || $form->dberror($query);
2033         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
2034           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
2035         }
2036         $stw->finish;
2037       }
2038     }
2039   }
2040   $sth->finish;
2041   $dbh->disconnect;
2042
2043   $main::lxdebug->leave_sub();
2044 }
2045
2046 ##########################
2047 # get pricegroups from database
2048 # build up selected pricegroup
2049 # if an exchange rate - change price
2050 # for each part
2051 #
2052 sub get_pricegroups_for_parts {
2053
2054   $main::lxdebug->enter_sub();
2055
2056   my ($self, $myconfig, $form) = @_;
2057
2058   my $dbh = $form->dbconnect($myconfig);
2059
2060   $form->{"PRICES"} = {};
2061
2062   my $i  = 1;
2063   my $id = 0;
2064   my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
2065   my $service_units = AM->retrieve_units($myconfig, $form, "service");
2066   my $all_units = AM->retrieve_units($myconfig, $form);
2067   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
2068     $form->{"PRICES"}{$i} = [];
2069
2070     $id = $form->{"id_$i"};
2071
2072     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
2073
2074       $id = $form->{"new_id_$i"};
2075     }
2076
2077     ($price, $selectedpricegroup_id) = split /--/,
2078       $form->{"sellprice_pg_$i"};
2079
2080     $pricegroup_old = $form->{"pricegroup_old_$i"};
2081     $form->{"new_pricegroup_$i"} = $selectedpricegroup_id;
2082     $form->{"old_pricegroup_$i"} = $pricegroup_old;
2083     $price_new = $form->{"price_new_$i"};
2084
2085     $price_old = $form->{"price_old_$i"};
2086     $query =
2087       qq|SELECT pricegroup_id, (SELECT p.sellprice from parts p where p.id = $id) as default_sellprice,(SELECT pg.pricegroup FROM pricegroup pg WHERE id=pricegroup_id) AS pricegroup, price, '' AS selected FROM prices WHERE parts_id = $id UNION SELECT 0 as pricegroup_id,(SELECT sellprice FROM parts WHERE id=$id) as default_sellprice,'' as pricegroup, (SELECT DISTINCT sellprice from parts where id=$id) as price, 'selected' AS selected from prices ORDER BY pricegroup|;
2088
2089     $pkq = $dbh->prepare($query);
2090     $pkq->execute || $form->dberror($query);
2091     if (!$form->{"unit_old_$i"}) {
2092       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
2093       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
2094       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
2095       $form->{"unit_old_$i"} = $form->{"unit_$i"};
2096     }
2097  
2098     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
2099     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
2100     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
2101
2102     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
2103     if (!$check_units->{$form->{"selected_unit_$i"}} ||
2104         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
2105          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
2106       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
2107       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
2108       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
2109       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
2110     }
2111     my $basefactor = 1;
2112     
2113     if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
2114       if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
2115           $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
2116         $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
2117           $all_units->{$form->{"unit_old_$i"}}->{"factor"};
2118       }
2119     }
2120     if (!$form->{"basefactor_$i"}) {
2121       $form->{"basefactor_$i"} = 1;
2122     }
2123     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
2124
2125       #       push @{ $form->{PRICES}{$id} }, $pkr;
2126       #push @{ $form->{PRICES}{$i} }, $pkr;
2127       $pkr->{id}       = $id;
2128       $pkr->{selected} = '';
2129
2130       # if there is an exchange rate change price
2131       if (($form->{exchangerate} * 1) != 0) {
2132
2133         $pkr->{price} /= $form->{exchangerate};
2134       }
2135
2136       $pkr->{price} *= $form->{"basefactor_$i"};
2137       
2138       $pkr->{price} *= $basefactor;
2139  
2140       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
2141
2142       if ($selectedpricegroup_id eq undef) {
2143         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
2144
2145           $pkr->{selected}  = ' selected';
2146
2147           # no customer pricesgroup set
2148           if ($pkr->{price} == $pkr->{default_sellprice}) {
2149
2150             $pkr->{price} = $form->{"sellprice_$i"};
2151
2152           } else {
2153
2154             $form->{"sellprice_$i"} = $pkr->{price};
2155           }
2156
2157         } else {
2158           if ($pkr->{price} == $pkr->{default_sellprice}) {
2159
2160             $pkr->{price}    = $form->{"sellprice_$i"};
2161             $pkr->{selected} = ' selected';
2162           }
2163         }
2164       }
2165
2166       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
2167         if ($selectedpricegroup_id ne $pricegroup_old) {
2168           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
2169             $pkr->{selected}  = ' selected';
2170           }
2171         } else {
2172           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
2173             if ($pkr->{pricegroup_id} == 0) {
2174               $pkr->{price}     = $form->{"sellprice_$i"};
2175               $pkr->{selected}  = ' selected';
2176             }
2177           } else {
2178             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
2179               $pkr->{selected}  = ' selected';
2180               if (    ($pkr->{pricegroup_id} == 0)
2181                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
2182
2183                 # $pkr->{price}                         = $form->{"sellprice_$i"};
2184               } else {
2185                 $pkr->{price} = $form->{"sellprice_$i"};
2186               }
2187             }
2188           }
2189         }
2190       }
2191       push @{ $form->{PRICES}{$i} }, $pkr;
2192
2193     }
2194     $form->{"basefactor_$i"} *= $basefactor;
2195
2196     $i++;
2197
2198     $pkq->finish;
2199   }
2200
2201   $dbh->disconnect;
2202
2203   $main::lxdebug->leave_sub();
2204 }
2205
2206 sub webdav_folder {
2207   $main::lxdebug->enter_sub();
2208
2209   my ($myconfig, $form) = @_;
2210
2211 SWITCH: {
2212     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
2213       if ($form->{vc} eq "customer");
2214     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
2215       if ($form->{vc} eq "vendor");
2216   }
2217
2218   if (!-d $path) {
2219     mkdir($path, 0770) or die "can't make directory $!\n";
2220   } else {
2221     if ($form->{id}) {
2222       @files = <$path/*>;
2223       foreach $file (@files) {
2224         $file =~ /\/([^\/]*)$/;
2225         $fname = $1;
2226         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
2227         $lxerp = $1;
2228         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
2229         $form->{WEBDAV}{$fname} = $link;
2230       }
2231     }
2232   }
2233
2234   $main::lxdebug->leave_sub();
2235 }
2236
2237 1;
2238