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