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