Uebernahme der kompletten Version, so wie sie Philip als "Demo-Version" gezeigt hat...
[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 ist
689       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_drag_$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 = "current_date";
1536     if($form->{invdate}) {
1537      $transdate = "'$form->{invdate}'";
1538     }
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.alu, 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       #set expense_accno=inventory_accno if they are different => bilanz
1574
1575
1576     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
1577       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}|;
1578       my $stw = $dbh->prepare($query);
1579       $stw->execute || $form->dberror($query);
1580       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
1581       $stw->finish;
1582     }
1583
1584     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
1585       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}|;
1586       my $stw = $dbh->prepare($query);
1587       $stw->execute || $form->dberror($query);
1588       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
1589       $stw->finish;
1590     }
1591
1592     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
1593       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}|;
1594       my $stw = $dbh->prepare($query);
1595       $stw->execute || $form->dberror($query);
1596       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
1597       $stw->finish;
1598     }
1599
1600       $vendor_accno =
1601         ($ref->{expense_accno} != $ref->{inventory_accno})
1602         ? $ref->{inventory_accno}
1603         : $ref->{expense_accno};
1604
1605       # get tax rates and description
1606       $accno_id =
1607         ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
1608       $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1609                  FROM tax t LEFT join chart c ON (c.id=t.chart_id)
1610                  WHERE t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
1611                  ORDER BY accno|;
1612       $stw = $dbh->prepare($query);
1613       $stw->execute || $form->dberror($query);
1614       $ref->{taxaccounts} = "";
1615       my $i=0;
1616       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1617
1618         #    if ($customertax{$ref->{accno}}) {
1619         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1620           $i++;
1621           $ptr->{accno} = $i;
1622         }
1623         $ref->{taxaccounts} .= "$ptr->{accno} ";
1624
1625         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1626           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1627           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1628           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1629           $form->{taxaccounts} .= "$ptr->{accno} ";
1630         }
1631
1632       }
1633
1634       if ($form->{lizenzen}) {
1635         $query = qq|SELECT l.licensenumber, l.id AS licenseid
1636                  FROM license l, licenseinvoice li
1637                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
1638         $stg = $dbh->prepare($query);
1639         $stg->execute || $form->dberror($query);
1640         ($licensenumber, $licenseid) = $stg->fetchrow_array();
1641         $ref->{lizenzen} =
1642           "<option value=\"$licenseid\">$licensenumber</option>";
1643         $stg->finish();
1644       }
1645       if ($form->{type} eq "credit_note") {
1646         $ref->{qty} *= -1;
1647       }
1648
1649       chop $ref->{taxaccounts};
1650       push @{ $form->{invoice_details} }, $ref;
1651       $stw->finish;
1652     }
1653     $sth->finish;
1654
1655     if ($form->{webdav}) {
1656       &webdav_folder($myconfig, $form);
1657     }
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   $form->get_contacts($dbh, $form->{customer_id});
1771   $form->{cp_id} *= 1;
1772
1773   # get contact if selected
1774   if ($form->{cp_id}) {
1775     $form->get_contact($dbh, $form->{cp_id});
1776   }
1777
1778   # get shipto if we did not converted an order or invoice
1779   if (!$form->{shipto}) {
1780     map { delete $form->{$_} }
1781       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
1782
1783     $query = qq|SELECT s.* FROM shipto s
1784                 WHERE s.trans_id = $form->{customer_id} AND s.module = 'CT'|;
1785     $sth = $dbh->prepare($query);
1786     $sth->execute || $form->dberror($query);
1787
1788     $ref = $sth->fetchrow_hashref(NAME_lc);
1789     undef($ref->{id});
1790     map { $form->{$_} = $ref->{$_} } keys %$ref;
1791     $sth->finish;
1792   }
1793
1794   # get taxes we charge for this customer
1795   $query = qq|SELECT c.accno
1796               FROM chart c
1797               JOIN customertax ct ON (ct.chart_id = c.id)
1798               WHERE ct.customer_id = $form->{customer_id}|;
1799   $sth = $dbh->prepare($query);
1800   $sth->execute || $form->dberror($query);
1801
1802   my $customertax = ();
1803   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1804     $customertax{ $ref->{accno} } = 1;
1805   }
1806   $sth->finish;
1807
1808   # get shipping addresses
1809   $query = qq|SELECT s.id,s.shiptoname
1810               FROM shipto s
1811               WHERE s.trans_id = $form->{customer_id}|;
1812   $sth = $dbh->prepare($query);
1813   $sth->execute || $form->dberror($query);
1814
1815   my $customertax = ();
1816   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1817     push(@{ $form->{SHIPTO} }, $ref);
1818   }
1819   $sth->finish;
1820
1821   # setup last accounts used for this customer
1822   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
1823     $query = qq|SELECT c.accno, c.description, c.link, c.category
1824                 FROM chart c
1825                 JOIN acc_trans ac ON (ac.chart_id = c.id)
1826                 JOIN ar a ON (a.id = ac.trans_id)
1827                 WHERE a.customer_id = $form->{customer_id}
1828                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
1829                 AND a.id IN (SELECT max(a2.id) FROM ar a2
1830                              WHERE a2.customer_id = $form->{customer_id})|;
1831     $sth = $dbh->prepare($query);
1832     $sth->execute || $form->dberror($query);
1833
1834     my $i = 0;
1835     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1836       if ($ref->{category} eq 'I') {
1837         $i++;
1838         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
1839       }
1840       if ($ref->{category} eq 'A') {
1841         $form->{ARselected} = $form->{AR_1} =
1842           "$ref->{accno}--$ref->{description}";
1843       }
1844     }
1845     $sth->finish;
1846     $form->{rowcount} = $i if ($i && !$form->{type});
1847   }
1848
1849   $dbh->disconnect;
1850
1851   $main::lxdebug->leave_sub();
1852 }
1853
1854 sub retrieve_item {
1855   $main::lxdebug->enter_sub();
1856
1857   my ($self, $myconfig, $form) = @_;
1858
1859   my $i = $form->{rowcount};
1860
1861   my $where = "NOT p.obsolete = '1'";
1862
1863   if ($form->{"partnumber_$i"}) {
1864     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1865     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1866   }
1867   if ($form->{"description_$i"}) {
1868     my $description = $form->like(lc $form->{"description_$i"});
1869     $where .= " AND lower(p.description) LIKE '$description'";
1870   }
1871
1872   if ($form->{"partsgroup_$i"}) {
1873     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1874     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1875   }
1876
1877   if ($form->{"description_$i"}) {
1878     $where .= " ORDER BY p.description";
1879   } else {
1880     $where .= " ORDER BY p.partnumber";
1881   }
1882
1883   my $transdate = "";
1884   if ($form->{type} eq "invoice") {
1885     $transdate = "'$form->{invdate}'";
1886   } elsif ($form->{type} eq "sales_order") {
1887     $transdate = "'$form->{transdate}'";
1888   } elsif ($form->{type} eq "sales_quotation") {
1889     $transdate = "'$form->{transdate}'";
1890   }
1891
1892   if ($transdate eq "") {
1893     $transdate = "current_date";
1894   }
1895
1896   # connect to database
1897   my $dbh = $form->dbconnect($myconfig);
1898
1899   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1900                         p.listprice, p.inventory_accno_id,
1901                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1902                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1903                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
1904                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1905                  pg.partsgroup, p.formel, p.alu, p.payment_id AS part_payment_id, adr.adr_description
1906                  FROM parts p
1907                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1908                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1909                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1910                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1911                  LEFT JOIN adr adr ON (adr.id = p.adr_id)
1912                  WHERE $where|;
1913   my $sth = $dbh->prepare($query);
1914   $sth->execute || $form->dberror($query);
1915
1916   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1917
1918     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1919     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1920     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1921     if (!$ref->{inventory_accno_id}) {
1922       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1923     }
1924     delete($ref->{inventory_accno_id});
1925
1926     #set expense_accno=inventory_accno if they are different => bilanz
1927
1928
1929     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
1930       my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
1931       my $stw = $dbh->prepare($query);
1932       $stw->execute || $form->dberror($query);
1933       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
1934       $stw->finish;
1935     }
1936
1937     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
1938       my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
1939       my $stw = $dbh->prepare($query);
1940       $stw->execute || $form->dberror($query);
1941       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
1942       $stw->finish;
1943     }
1944
1945     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
1946       my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
1947       my $stw = $dbh->prepare($query);
1948       $stw->execute || $form->dberror($query);
1949       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
1950       $stw->finish;
1951     }
1952
1953     #check whether payment_terms are better than old payment_terms
1954     if (($form->{payment_id} ne "") && ($ref->{part_payment_id} ne "")) {
1955       my $query = qq|select (select ranking from payment_terms WHERE id = $form->{payment_id}), (select ranking from payment_terms WHERE id = $ref->{part_payment_id})|;
1956       my $stw = $dbh->prepare($query);
1957       $stw->execute || $form->dberror($query);
1958       ($old_ranking, $new_ranking) = $stw->fetchrow_array;
1959       $stw->finish;
1960       if ($new_ranking <= $old_ranking) {
1961         $ref->{part_payment_id} = "";
1962       }
1963     }
1964
1965
1966     $vendor_accno =
1967       ($ref->{expense_accno} != $ref->{inventory_accno})
1968       ? $ref->{inventory_accno}
1969       : $ref->{expense_accno};
1970
1971     # get tax rates and description
1972     $accno_id =
1973       ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
1974     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1975               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
1976               WHERE t.taxkey in (SELECT c2.taxkey_id from chart c2 where c2.accno = '$accno_id')
1977               ORDER BY c.accno|;
1978     $stw = $dbh->prepare($query);
1979     $stw->execute || $form->dberror($query);
1980
1981     $ref->{taxaccounts} = "";
1982     my $i = 0;
1983     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1984
1985       #    if ($customertax{$ref->{accno}}) {
1986       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1987         $i++;
1988         $ptr->{accno} = $i;
1989       }
1990       $ref->{taxaccounts} .= "$ptr->{accno} ";
1991
1992       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1993         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1994         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1995         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1996         $form->{taxaccounts} .= "$ptr->{accno} ";
1997       }
1998
1999     }
2000
2001     $stw->finish;
2002     chop $ref->{taxaccounts};
2003     if ($form->{language_id}) {
2004       $query = qq|SELECT tr.translation, tr.longdescription
2005                 FROM translation tr
2006                 WHERE tr.language_id=$form->{language_id} AND tr.parts_id=$ref->{id}|;
2007       $stw = $dbh->prepare($query);
2008       $stw->execute || $form->dberror($query);
2009       my ($translation, $longdescription) = $stw->fetchrow_array();
2010       if ($translation ne "") {
2011         $ref->{description} = $translation;
2012         $ref->{longdescription} = $longdescription;
2013
2014       } else {
2015         $query = qq|SELECT tr.translation, tr.longdescription
2016                 FROM translation tr
2017                 WHERE tr.language_id in (select id from language where article_code=(select article_code from language where id = $form->{language_id})) AND tr.parts_id=$ref->{id} LIMIT 1|;
2018         $stg = $dbh->prepare($query);
2019         $stg->execute || $form->dberror($query);
2020         my ($translation) = $stg->fetchrow_array();
2021         if ($translation ne "") {
2022           $ref->{description} = $translation;
2023           $ref->{longdescription} = $longdescription;
2024         }
2025         $stg->finish;
2026       }
2027       $stw->finish;
2028     }
2029
2030     push @{ $form->{item_list} }, $ref;
2031
2032     if ($form->{lizenzen}) {
2033       if ($ref->{inventory_accno} > 0) {
2034         $query =
2035           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
2036         $stw = $dbh->prepare($query);
2037         $stw->execute || $form->dberror($query);
2038         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
2039           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
2040         }
2041         $stw->finish;
2042       }
2043     }
2044   }
2045   $sth->finish;
2046   $dbh->disconnect;
2047
2048   $main::lxdebug->leave_sub();
2049 }
2050
2051 ##########################
2052 # get pricegroups from database
2053 # build up selected pricegroup
2054 # if an exchange rate - change price
2055 # for each part
2056 #
2057 sub get_pricegroups_for_parts {
2058
2059   $main::lxdebug->enter_sub();
2060
2061   my ($self, $myconfig, $form) = @_;
2062
2063   my $dbh = $form->dbconnect($myconfig);
2064
2065   my $i  = 1;
2066   my $id = 0;
2067   my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
2068   my $service_units = AM->retrieve_units($myconfig, $form, "service");
2069   my $all_units = AM->retrieve_units($myconfig, $form);
2070   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
2071
2072     $id = $form->{"id_$i"};
2073
2074     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
2075
2076       $id = $form->{"new_id_$i"};
2077     }
2078
2079     ($price, $selectedpricegroup_id) = split /--/,
2080       $form->{"sellprice_drag_$i"};
2081
2082     $pricegroup_old = $form->{"pricegroup_old_$i"};
2083     $form->{"new_pricegroup_$i"} = $selectedpricegroup_id;
2084     $form->{"old_pricegroup_$i"} = $pricegroup_old;
2085     $price_new = $form->{"price_new_$i"};
2086
2087     $price_old = $form->{"price_old_$i"};
2088     $query =
2089       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|;
2090
2091     $pkq = $dbh->prepare($query);
2092     $pkq->execute || $form->dberror($query);
2093     if (!$form->{"unit_old_$i"}) {
2094       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
2095       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
2096       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
2097       $form->{"unit_old_$i"} = $form->{"unit_$i"};
2098     }
2099  
2100     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
2101     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
2102     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
2103
2104     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
2105     if (!$check_units->{$form->{"selected_unit_$i"}} ||
2106         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
2107          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
2108       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
2109       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
2110       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
2111       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
2112     }
2113     my $basefactor = 1;
2114     
2115     if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
2116       if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
2117           $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
2118         $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
2119           $all_units->{$form->{"unit_old_$i"}}->{"factor"};
2120       }
2121     }
2122     if (!$form->{"basefactor_$i"}) {
2123       $form->{"basefactor_$i"} = 1;
2124     }
2125     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
2126
2127       #       push @{ $form->{PRICES}{$id} }, $pkr;
2128       #push @{ $form->{PRICES}{$i} }, $pkr;
2129       $pkr->{id}       = $id;
2130       $pkr->{selected} = '';
2131
2132       # if there is an exchange rate change price
2133       if (($form->{exchangerate} * 1) != 0) {
2134
2135         $pkr->{price} /= $form->{exchangerate};
2136       }
2137
2138       $pkr->{price} *= $form->{"basefactor_$i"};
2139       
2140       $pkr->{price} *= $basefactor;
2141  
2142       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
2143
2144       if ($selectedpricegroup_id eq undef) {
2145         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
2146
2147           $pkr->{selected}  = ' selected';
2148
2149           # no customer pricesgroup set
2150           if ($pkr->{price} == $pkr->{default_sellprice}) {
2151
2152             $pkr->{price} = $form->{"sellprice_$i"};
2153
2154           } else {
2155
2156             $form->{"sellprice_$i"} = $pkr->{price};
2157           }
2158
2159         } else {
2160           if ($pkr->{price} == $pkr->{default_sellprice}) {
2161
2162             $pkr->{price}    = $form->{"sellprice_$i"};
2163             $pkr->{selected} = ' selected';
2164           }
2165         }
2166       }
2167
2168       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
2169         if ($selectedpricegroup_id ne $pricegroup_old) {
2170           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
2171             $pkr->{selected}  = ' selected';
2172           }
2173         } else {
2174           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
2175             if ($pkr->{pricegroup_id} == 0) {
2176               $pkr->{price}     = $form->{"sellprice_$i"};
2177               $pkr->{selected}  = ' selected';
2178             }
2179           } else {
2180             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
2181               $pkr->{selected}  = ' selected';
2182               if (    ($pkr->{pricegroup_id} == 0)
2183                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
2184
2185                 # $pkr->{price}                         = $form->{"sellprice_$i"};
2186                   } else {
2187                 $pkr->{price} = $form->{"sellprice_$i"};
2188               }
2189             }
2190           }
2191         }
2192       }
2193       push @{ $form->{PRICES}{$i} }, $pkr;
2194
2195     }
2196     $form->{"basefactor_$i"} *= $basefactor;
2197
2198     $i++;
2199
2200     $pkq->finish;
2201   }
2202
2203   $dbh->disconnect;
2204
2205   $main::lxdebug->leave_sub();
2206 }
2207
2208 sub webdav_folder {
2209   $main::lxdebug->enter_sub();
2210
2211   my ($myconfig, $form) = @_;
2212
2213 SWITCH: {
2214     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
2215       if ($form->{vc} eq "customer");
2216     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
2217       if ($form->{vc} eq "vendor");
2218   }
2219
2220   if (!-d $path) {
2221     mkdir($path, 0770) or die "can't make directory $!\n";
2222   } else {
2223     if ($form->{id}) {
2224       @files = <$path/*>;
2225       foreach $file (@files) {
2226         $file =~ /\/([^\/]*)$/;
2227         $fname = $1;
2228         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
2229         $lxerp = $1;
2230         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
2231         $form->{WEBDAV}{$fname} = $link;
2232       }
2233     }
2234   }
2235
2236   $main::lxdebug->leave_sub();
2237 }
2238
2239 1;
2240