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