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