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