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