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