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