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