04144ff70bafb642b526b363e67682d3a0a59db0
[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
39 sub invoice_details {
40   $main::lxdebug->enter_sub();
41
42   my ($self, $myconfig, $form, $locale) = @_;
43
44   $form->{duedate} = $form->{invdate} unless ($form->{duedate});
45
46   # connect to database
47   my $dbh = $form->dbconnect($myconfig);
48
49   my $query = qq|SELECT date '$form->{duedate}' - date '$form->{invdate}'
50                  AS terms
51                  FROM defaults|;
52   my $sth = $dbh->prepare($query);
53   $sth->execute || $form->dberror($query);
54
55   ($form->{terms}) = $sth->fetchrow_array;
56   $sth->finish;
57
58   my $tax = 0;
59   my $item;
60   my $i;
61   my @partsgroup = ();
62   my $partsgroup;
63   my %oid = ('Pg'     => 'oid',
64              'Oracle' => 'rowid');
65
66   # sort items by partsgroup
67   for $i (1 .. $form->{rowcount}) {
68     $partsgroup = "";
69     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
70       $form->format_string("partsgroup_$i");
71       $partsgroup = $form->{"partsgroup_$i"};
72     }
73     push @partsgroup, [$i, $partsgroup];
74   }
75
76   my $sameitem = "";
77   my @taxaccounts;
78   my %taxaccounts;
79   my %taxbase;
80   my $taxrate;
81   my $taxamount;
82   my $taxbase;
83   my $taxdiff;
84
85   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
86     $i = $item->[0];
87
88     if ($item->[1] ne $sameitem) {
89       push(@{ $form->{description} }, qq|$item->[1]|);
90       $sameitem = $item->[1];
91
92       map { push(@{ $form->{$_} }, "") }
93         qw(runningnumber number serialnumber bin partnotes qty unit deliverydate sellprice listprice netprice discount linetotal);
94     }
95
96     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
97
98     if ($form->{"qty_$i"} != 0) {
99
100       # add number, description and qty to $form->{number}, ....
101       push(@{ $form->{runningnumber} }, $i);
102       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
103       push(@{ $form->{serialnumber} },  qq|$form->{"serialnumber_$i"}|);
104       push(@{ $form->{bin} },           qq|$form->{"bin_$i"}|);
105       push(@{ $form->{"partnotes"} },   qq|$form->{"partnotes_$i"}|);
106       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
107       push(@{ $form->{qty} },
108            $form->format_amount($myconfig, $form->{"qty_$i"}));
109       push(@{ $form->{unit} },         qq|$form->{"unit_$i"}|);
110       push(@{ $form->{deliverydate_oe} }, qq|$form->{"deliverydate_$i"}|);
111
112       push(@{ $form->{sellprice} }, $form->{"sellprice_$i"});
113       push(@{ $form->{ordnumber_oe} }, qq|$form->{"ordnumber_$i"}|);
114       push(@{ $form->{transdate_oe} }, qq|$form->{"transdate_$i"}|);
115
116       if ($form->{lizenzen}) {
117         if ($form->{"licensenumber_$i"}) {
118           $query =
119             qq|SELECT l.licensenumber, l.validuntil FROM license l WHERE l.id = $form->{"licensenumber_$i"}|;
120           $sth = $dbh->prepare($query);
121           $sth->execute || $form->dberror($query);
122
123           ($licensenumber, $validuntil) = $sth->fetchrow_array;
124           push(@{ $form->{licensenumber} }, $licensenumber);
125           push(@{ $form->{validuntil} },
126                $locale->date($myconfig, $validuntil, 0));
127           $sth->finish;
128         } else {
129           push(@{ $form->{licensenumber} }, "");
130           push(@{ $form->{validuntil} },    "");
131         }
132       }
133
134       # listprice
135       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
136
137       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
138       my ($dec) = ($sellprice =~ /\.(\d+)/);
139       $dec = length $dec;
140       my $decimalplaces = ($dec > 2) ? $dec : 2;
141
142       my $i_discount = $form->round_amount($sellprice * 
143                                            $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100, $decimalplaces);
144
145       my $discount = $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
146
147       # keep a netprice as well, (sellprice - discount)
148       $form->{"netprice_$i"} = $sellprice - $i_discount;
149
150       push(@{ $form->{netprice} },
151            ($form->{"netprice_$i"} != 0)
152            ? $form->format_amount(
153                                  $myconfig, $form->{"netprice_$i"},
154                                  $decimalplaces
155              )
156            : " ");
157
158       my $linetotal =
159         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
160
161       $discount =
162         ($discount != 0)
163         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
164         : " ";
165       $linetotal = ($linetotal != 0) ? $linetotal : " ";
166
167       push(@{ $form->{discount} }, $discount);
168       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
169
170       $form->{total} += $linetotal;
171
172       push(@{ $form->{linetotal} },
173            $form->format_amount($myconfig, $linetotal, 2));
174
175       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
176       $taxrate     = 0;
177       $taxdiff     = 0;
178
179       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
180
181       if ($form->{taxincluded}) {
182
183         # calculate tax
184         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
185         $taxbase = $linetotal - $taxamount;
186       } else {
187         $taxamount = $linetotal * $taxrate;
188         $taxbase   = $linetotal;
189       }
190
191       if ($form->round_amount($taxrate, 7) == 0) {
192         if ($form->{taxincluded}) {
193           foreach $item (@taxaccounts) {
194             $taxamount =
195               $form->round_amount($linetotal * $form->{"${item}_rate"} /
196                                     (1 + abs($form->{"${item}_rate"})),
197                                   2);
198
199             $taxaccounts{$item} += $taxamount;
200             $taxdiff            += $taxamount;
201
202             $taxbase{$item} += $taxbase;
203           }
204           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
205         } else {
206           foreach $item (@taxaccounts) {
207             $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
208             $taxbase{$item}     += $taxbase;
209           }
210         }
211       } else {
212         foreach $item (@taxaccounts) {
213           $taxaccounts{$item} +=
214             $taxamount * $form->{"${item}_rate"} / $taxrate;
215           $taxbase{$item} += $taxbase;
216         }
217       }
218       $tax_rate = $taxrate * 100;
219       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
220       if ($form->{"assembly_$i"}) {
221         $sameitem = "";
222
223         # get parts and push them onto the stack
224         my $sortorder = "";
225         if ($form->{groupitems}) {
226           $sortorder =
227             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
228         } else {
229           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
230         }
231
232         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
233                     pg.partsgroup
234                     FROM assembly a
235                     JOIN parts p ON (a.parts_id = p.id)
236                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
237                     WHERE a.bom = '1'
238                     AND a.id = '$form->{"id_$i"}'
239                     $sortorder|;
240         $sth = $dbh->prepare($query);
241         $sth->execute || $form->dberror($query);
242
243         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
244           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
245             map { push(@{ $form->{$_} }, "") }
246               qw(runningnumber number serialnumber unit qty bin sellprice listprice netprice discount linetotal);
247             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
248             push(@{ $form->{description} }, $sameitem);
249           }
250
251           map { $form->{"a_$_"} = $ref->{$_} } qw(partnumber description);
252           $form->format_string("a_partnumber", "a_description");
253
254           push(@{ $form->{description} },
255                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
256                  )
257                  . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
258           map { push(@{ $form->{$_} }, "") }
259             qw(number unit qty runningnumber serialnumber bin sellprice listprice netprice discount linetotal);
260
261         }
262         $sth->finish;
263       }
264     }
265   }
266
267   foreach my $item (sort keys %taxaccounts) {
268     if ($form->round_amount($taxaccounts{$item}, 2) != 0) {
269       push(@{ $form->{taxbase} },
270            $form->format_amount($myconfig, $taxbase{$item}, 2));
271
272       $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
273
274       push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
275       push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
276       push(@{ $form->{taxrate} },
277            $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
278       push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
279     }
280   }
281
282   for my $i (1 .. $form->{paidaccounts}) {
283     if ($form->{"paid_$i"}) {
284       push(@{ $form->{payment} }, $form->{"paid_$i"});
285       my ($accno, $description) = split /--/, $form->{"AR_paid_$i"};
286       push(@{ $form->{paymentaccount} }, $description);
287       push(@{ $form->{paymentdate} },    $form->{"datepaid_$i"});
288       push(@{ $form->{paymentsource} },  $form->{"source_$i"});
289
290       $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
291     }
292   }
293
294   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
295   $form->{invtotal} =
296     ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
297   $form->{total} =
298     $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
299   $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
300
301   $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
302
303   # myconfig variables
304   map { $form->{$_} = $myconfig->{$_} }
305     (qw(company address tel fax signature businessnumber));
306   $form->{username} = $myconfig->{name};
307
308   $dbh->disconnect;
309
310   $main::lxdebug->leave_sub();
311 }
312
313 sub project_description {
314   $main::lxdebug->enter_sub();
315
316   my ($self, $dbh, $id) = @_;
317
318   my $query = qq|SELECT p.description
319                  FROM project p
320                  WHERE p.id = $id|;
321   my $sth = $dbh->prepare($query);
322   $sth->execute || $form->dberror($query);
323
324   ($_) = $sth->fetchrow_array;
325
326   $sth->finish;
327
328   $main::lxdebug->leave_sub();
329
330   return $_;
331 }
332
333 sub customer_details {
334   $main::lxdebug->enter_sub();
335
336   my ($self, $myconfig, $form) = @_;
337
338   # connect to database
339   my $dbh = $form->dbconnect($myconfig);
340
341   # get contact id, set it if nessessary
342   ($null, $form->{cp_id}) = split /--/, $form->{contact};
343
344   $contact = "";
345   if ($form->{cp_id}) {
346     $contact = "and cp.cp_id = $form->{cp_id}";
347   }
348
349   # get rest for the customer
350   my $query = qq|SELECT ct.*, cp.*, ct.notes as customernotes
351                  FROM customer ct
352                  LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
353                  WHERE ct.id = $form->{customer_id} $contact order by cp.cp_id limit 1|;
354   my $sth = $dbh->prepare($query);
355   $sth->execute || $form->dberror($query);
356
357   $ref = $sth->fetchrow_hashref(NAME_lc);
358
359   # remove id and taxincluded before copy back
360   delete @$ref{qw(id taxincluded)};
361   map { $form->{$_} = $ref->{$_} } keys %$ref;
362
363   $sth->finish;
364   $dbh->disconnect;
365
366   $main::lxdebug->leave_sub();
367 }
368
369 sub post_invoice {
370   $main::lxdebug->enter_sub();
371
372   my ($self, $myconfig, $form) = @_;
373
374   # connect to database, turn off autocommit
375   my $dbh = $form->dbconnect_noauto($myconfig);
376
377   my ($query, $sth, $null, $project_id, $deliverydate);
378   my $exchangerate = 0;
379
380   ($null, $form->{employee_id}) = split /--/, $form->{employee};
381   unless ($form->{employee_id}) {
382     $form->get_employee($dbh);
383   }
384
385   ($null, $form->{contact_id}) = split /--/, $form->{contact};
386   $form->{contact_id} *= 1;
387
388   ($null, $form->{department_id}) = split(/--/, $form->{department});
389   $form->{department_id} *= 1;
390
391   if ($form->{id}) {
392
393     &reverse_invoice($dbh, $form);
394
395   } else {
396     my $uid = rand() . time;
397
398     $uid .= $form->{login};
399
400     $uid = substr($uid, 2, 75);
401
402     $query = qq|INSERT INTO ar (invnumber, employee_id)
403                 VALUES ('$uid', $form->{employee_id})|;
404     $dbh->do($query) || $form->dberror($query);
405
406     $query = qq|SELECT a.id FROM ar a
407                 WHERE a.invnumber = '$uid'|;
408     $sth = $dbh->prepare($query);
409     $sth->execute || $form->dberror($query);
410
411     ($form->{id}) = $sth->fetchrow_array;
412     $sth->finish;
413   }
414
415   map { $form->{$_} =~ s/\'/\'\'/g }
416     (qw(invnumber shippingpoint shipvia notes intnotes message));
417
418   my ($netamount, $invoicediff) = (0, 0);
419   my ($amount, $linetotal, $lastincomeaccno);
420
421   if ($form->{currency} eq $form->{defaultcurrency}) {
422     $form->{exchangerate} = 1;
423   } else {
424     $exchangerate =
425       $form->check_exchangerate($myconfig, $form->{currency},
426                                 $form->{transdate}, 'buy');
427   }
428
429   $form->{exchangerate} =
430     ($exchangerate)
431     ? $exchangerate
432     : $form->parse_amount($myconfig, $form->{exchangerate});
433
434   $form->{expense_inventory} = "";
435
436   foreach my $i (1 .. $form->{rowcount}) {
437     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
438
439     if ($form->{"qty_$i"} != 0) {
440
441       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
442         (qw(partnumber description unit));
443
444       # undo discount formatting
445       $form->{"discount_$i"} =
446         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
447
448       my ($allocated, $taxrate) = (0, 0);
449       my $taxamount;
450
451       # keep entered selling price
452       my $fxsellprice =
453         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
454
455       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
456       $dec = length $dec;
457       my $decimalplaces = ($dec > 2) ? $dec : 2;
458
459       # deduct discount
460       my $discount =
461         $form->round_amount($fxsellprice * $form->{"discount_$i"},
462                             $decimalplaces);
463       $form->{"sellprice_$i"} = $fxsellprice - $discount;
464
465       # add tax rates
466       map { $taxrate += $form->{"${_}_rate"} } split / /,
467         $form->{"taxaccounts_$i"};
468
469       # round linetotal to 2 decimal places
470       $linetotal =
471         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
472
473       if ($form->{taxincluded}) {
474         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
475         $form->{"sellprice_$i"} =
476           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
477       } else {
478         $taxamount = $linetotal * $taxrate;
479       }
480
481       $netamount += $linetotal;
482
483       if ($taxamount != 0) {
484         map {
485           $form->{amount}{ $form->{id} }{$_} +=
486             $taxamount * $form->{"${_}_rate"} / $taxrate
487         } split / /, $form->{"taxaccounts_$i"};
488       }
489
490       # add amount to income, $form->{amount}{trans_id}{accno}
491       $amount =
492         $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
493
494       $linetotal =
495         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
496         $form->{exchangerate};
497       $linetotal = $form->round_amount($linetotal, 2);
498
499       # this is the difference from the inventory
500       $invoicediff += ($amount - $linetotal);
501
502       $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
503         $linetotal;
504
505       $lastincomeaccno = $form->{"income_accno_$i"};
506
507       # adjust and round sellprice
508       $form->{"sellprice_$i"} =
509         $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
510                             $decimalplaces);
511
512       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
513
514         # adjust parts onhand quantity
515
516         if ($form->{"assembly_$i"}) {
517
518           # do not update if assembly consists of all services
519           $query = qq|SELECT sum(p.inventory_accno_id)
520                       FROM parts p
521                       JOIN assembly a ON (a.parts_id = p.id)
522                       WHERE a.id = $form->{"id_$i"}|;
523           $sth = $dbh->prepare($query);
524           $sth->execute || $form->dberror($query);
525
526           if ($sth->fetchrow_array) {
527             $form->update_balance($dbh, "parts", "onhand",
528                                   qq|id = $form->{"id_$i"}|,
529                                   $form->{"qty_$i"} * -1)
530               unless $form->{shipped};
531           }
532           $sth->finish;
533
534           # record assembly item as allocated
535           &process_assembly($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
536         } else {
537           $form->update_balance($dbh, "parts", "onhand",
538                                 qq|id = $form->{"id_$i"}|,
539                                 $form->{"qty_$i"} * -1)
540             unless $form->{shipped};
541
542           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
543         }
544       }
545
546       $project_id = 'NULL';
547       if ($form->{"projectnumber_$i"}) {
548         $project_id = $form->{"projectnumber_$i"};
549       }
550       $deliverydate =
551         ($form->{"deliverydate_$i"})
552         ? qq|'$form->{"deliverydate_$i"}'|
553         : "NULL";
554
555       # get pricegroup_id and save ist
556       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_drag_$i"};
557       $pricegroup_id *= 1;
558
559       # save detail record in invoice table
560       $query = qq|INSERT INTO invoice (trans_id, parts_id, description, qty,
561                   sellprice, fxsellprice, discount, allocated, assemblyitem,
562                   unit, deliverydate, project_id, serialnumber, pricegroup_id,
563                   ordnumber, transdate, cusordnumber)
564                   VALUES ($form->{id}, $form->{"id_$i"},
565                   '$form->{"description_$i"}', $form->{"qty_$i"},
566                   $form->{"sellprice_$i"}, $fxsellprice,
567                   $form->{"discount_$i"}, $allocated, 'f',
568                   '$form->{"unit_$i"}', $deliverydate, (SELECT id from project where projectnumber = '$project_id'),
569                   '$form->{"serialnumber_$i"}', '$pricegroup_id',
570                   '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}')|;
571       $dbh->do($query) || $form->dberror($query);
572
573       if ($form->{lizenzen}) {
574         if ($form->{"licensenumber_$i"}) {
575           $query =
576             qq|SELECT i.id FROM invoice i WHERE i.trans_id=$form->{id} ORDER BY i.oid DESC LIMIT 1|;
577           $sth = $dbh->prepare($query);
578           $sth->execute || $form->dberror($query);
579
580           ($invoice_row_id) = $sth->fetchrow_array;
581           $sth->finish;
582
583           $query =
584             qq|INSERT INTO licenseinvoice (trans_id, license_id) VALUES ($invoice_row_id, $form->{"licensenumber_$i"})|;
585           $dbh->do($query) || $form->dberror($query);
586         }
587       }
588
589     }
590   }
591
592   $form->{datepaid} = $form->{invdate};
593
594   # total payments, don't move we need it here
595   for my $i (1 .. $form->{paidaccounts}) {
596     $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
597     $form->{paid} += $form->{"paid_$i"};
598     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
599   }
600
601   my ($tax, $diff) = (0, 0);
602
603   $netamount = $form->round_amount($netamount, 2);
604
605   # figure out rounding errors for total amount vs netamount + taxes
606   if ($form->{taxincluded}) {
607
608     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
609     $diff += $amount - $netamount * $form->{exchangerate};
610     $netamount = $amount;
611
612     foreach my $item (split / /, $form->{taxaccounts}) {
613       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
614       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
615       $tax += $form->{amount}{ $form->{id} }{$item};
616       $netamount -= $form->{amount}{ $form->{id} }{$item};
617     }
618
619     $invoicediff += $diff;
620     ######## this only applies to tax included
621     if ($lastincomeaccno) {
622       $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
623     }
624
625   } else {
626     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
627     $diff      = $amount - $netamount * $form->{exchangerate};
628     $netamount = $amount;
629     foreach my $item (split / /, $form->{taxaccounts}) {
630       $form->{amount}{ $form->{id} }{$item} =
631         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
632       $amount =
633         $form->round_amount(
634                  $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
635                  2);
636       $diff +=
637         $amount - $form->{amount}{ $form->{id} }{$item} *
638         $form->{exchangerate};
639       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
640       $tax += $form->{amount}{ $form->{id} }{$item};
641     }
642   }
643
644   $form->{amount}{ $form->{id} }{ $form->{AR} } = $netamount + $tax;
645   $form->{paid} =
646     $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
647
648   # reverse AR
649   $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
650
651   # update exchangerate
652   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
653     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
654                                $form->{exchangerate}, 0);
655   }
656
657   foreach my $trans_id (keys %{ $form->{amount} }) {
658     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
659       next unless ($form->{expense_inventory} =~ /$accno/);
660       if (
661           ($form->{amount}{$trans_id}{$accno} =
662            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
663           ) != 0
664         ) {
665         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
666                     transdate, taxkey)
667                     VALUES ($trans_id, (SELECT c.id FROM chart c
668                                         WHERE c.accno = '$accno'),
669                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
670                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
671         $dbh->do($query) || $form->dberror($query);
672         $form->{amount}{$trans_id}{$accno} = 0;
673       }
674     }
675
676     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
677       if (
678           ($form->{amount}{$trans_id}{$accno} =
679            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
680           ) != 0
681         ) {
682         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
683                     transdate, taxkey)
684                     VALUES ($trans_id, (SELECT id FROM chart
685                                         WHERE accno = '$accno'),
686                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
687                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
688         $dbh->do($query) || $form->dberror($query);
689       }
690     }
691   }
692
693   # deduct payment differences from diff
694   for my $i (1 .. $form->{paidaccounts}) {
695     if ($form->{"paid_$i"} != 0) {
696       $amount =
697         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
698       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
699     }
700   }
701
702   # force AR entry if 0
703   #  $form->{amount}{$form->{id}}{$form->{AR}} = 1 if ($form->{amount}{$form->{id}}{$form->{AR}} == 0);
704
705   # record payments and offsetting AR
706   for my $i (1 .. $form->{paidaccounts}) {
707
708     if ($form->{"paid_$i"} != 0) {
709       my ($accno) = split /--/, $form->{"AR_paid_$i"};
710       $form->{"datepaid_$i"} = $form->{invdate}
711         unless ($form->{"datepaid_$i"});
712       $form->{datepaid} = $form->{"datepaid_$i"};
713
714       $exchangerate = 0;
715
716       if ($form->{currency} eq $form->{defaultcurrency}) {
717         $form->{"exchangerate_$i"} = 1;
718       } else {
719         $exchangerate =
720           $form->check_exchangerate($myconfig, $form->{currency},
721                                     $form->{"datepaid_$i"}, 'buy');
722
723         $form->{"exchangerate_$i"} =
724           ($exchangerate)
725           ? $exchangerate
726           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
727       }
728
729       # record AR
730       $amount =
731         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff,
732                             2);
733
734       if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
735         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
736                     transdate)
737                     VALUES ($form->{id}, (SELECT c.id FROM chart c
738                                         WHERE c.accno = '$form->{AR}'),
739                     $amount, '$form->{"datepaid_$i"}')|;
740         $dbh->do($query) || $form->dberror($query);
741       }
742
743       # record payment
744       $form->{"paid_$i"} *= -1;
745
746       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
747                   source, memo)
748                   VALUES ($form->{id}, (SELECT c.id FROM chart c
749                                       WHERE c.accno = '$accno'),
750                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
751                   '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
752       $dbh->do($query) || $form->dberror($query);
753
754       # exchangerate difference
755       $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
756         $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
757
758       # gain/loss
759       $amount =
760         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
761         $form->{"exchangerate_$i"};
762       if ($amount > 0) {
763         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
764           $amount;
765       } else {
766         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
767           $amount;
768       }
769
770       $diff = 0;
771
772       # update exchange rate
773       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
774         $form->update_exchangerate($dbh, $form->{currency},
775                                    $form->{"datepaid_$i"},
776                                    $form->{"exchangerate_$i"}, 0);
777       }
778     }
779   }
780
781   # record exchange rate differences and gains/losses
782   foreach my $accno (keys %{ $form->{fx} }) {
783     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
784       if (
785           ($form->{fx}{$accno}{$transdate} =
786            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
787           ) != 0
788         ) {
789
790         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
791                     transdate, cleared, fx_transaction)
792                     VALUES ($form->{id},
793                            (SELECT c.id FROM chart c
794                             WHERE c.accno = '$accno'),
795                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
796         $dbh->do($query) || $form->dberror($query);
797       }
798     }
799   }
800
801   $amount = $netamount + $tax;
802
803   # set values which could be empty to 0
804   $form->{terms}       *= 1;
805   $form->{taxincluded} *= 1;
806   my $datepaid     = ($form->{paid})         ? qq|'$form->{datepaid}'| : "NULL";
807   my $duedate      = ($form->{duedate})      ? qq|'$form->{duedate}'|  : "NULL";
808   my $deliverydate = ($form->{deliverydate}) ? qq|'$form->{deliverydate}'| : "NULL";
809
810   # fill in subject if there is none
811   $form->{subject} = qq|$form->{label} $form->{invnumber}|
812     unless $form->{subject};
813
814   # if there is a message stuff it into the intnotes
815   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
816   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
817   my $now = scalar localtime;
818   $form->{intnotes} .= qq|\r
819 \r| if $form->{intnotes};
820
821   $form->{intnotes} .= qq|[email]\r
822 Date: $now
823 To: $form->{email}\r
824 $cc${bcc}Subject: $form->{subject}\r
825 \r
826 Message: $form->{message}\r| if $form->{message};
827
828   # save AR record
829   $query = qq|UPDATE ar set
830               invnumber = '$form->{invnumber}',
831               ordnumber = '$form->{ordnumber}',
832               quonumber = '$form->{quonumber}',
833               cusordnumber = '$form->{cusordnumber}',
834               transdate = '$form->{invdate}',
835               customer_id = $form->{customer_id},
836               amount = $amount,
837               netamount = $netamount,
838               paid = $form->{paid},
839               datepaid = $datepaid,
840               duedate = $duedate,
841               deliverydate = $deliverydate,
842               invoice = '1',
843               shippingpoint = '$form->{shippingpoint}',
844               shipvia = '$form->{shipvia}',
845               terms = $form->{terms},
846               notes = '$form->{notes}',
847               intnotes = '$form->{intnotes}',
848               taxincluded = '$form->{taxincluded}',
849               curr = '$form->{currency}',
850               department_id = $form->{department_id},
851               employee_id = $form->{employee_id},
852               cp_id = $form->{contact_id}
853               WHERE id = $form->{id}
854              |;
855   $dbh->do($query) || $form->dberror($query);
856
857   $form->{pago_total} = $amount;
858
859   # add shipto
860   $form->{name} = $form->{customer};
861   $form->{name} =~ s/--$form->{customer_id}//;
862   $form->add_shipto($dbh, $form->{id});
863
864   # save printed, emailed and queued
865   $form->save_status($dbh);
866
867   if ($form->{webdav}) {
868     &webdav_folder($myconfig, $form);
869   }
870
871   my $rc = $dbh->commit;
872   $dbh->disconnect;
873
874   $main::lxdebug->leave_sub();
875
876   return $rc;
877 }
878
879 sub process_assembly {
880   $main::lxdebug->enter_sub();
881
882   my ($dbh, $form, $id, $totalqty) = @_;
883
884   my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
885                  p.partnumber, p.description, p.unit,
886                  p.inventory_accno_id, p.income_accno_id,
887                  p.expense_accno_id
888                  FROM assembly a
889                  JOIN parts p ON (a.parts_id = p.id)
890                  WHERE a.id = $id|;
891   my $sth = $dbh->prepare($query);
892   $sth->execute || $form->dberror($query);
893
894   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
895
896     my $allocated = 0;
897
898     $ref->{inventory_accno_id} *= 1;
899     $ref->{expense_accno_id}   *= 1;
900
901     map { $ref->{$_} =~ s/\'/\'\'/g } (qw(partnumber description unit));
902
903     # multiply by number of assemblies
904     $ref->{qty} *= $totalqty;
905
906     if ($ref->{assembly}) {
907       &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty});
908       next;
909     } else {
910       if ($ref->{inventory_accno_id}) {
911         $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty});
912       }
913     }
914
915     # save detail record for individual assembly item in invoice table
916     $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
917                 sellprice, fxsellprice, allocated, assemblyitem, unit)
918                 VALUES
919                 ($form->{id}, '$ref->{description}',
920                 $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't',
921                 '$ref->{unit}')|;
922     $dbh->do($query) || $form->dberror($query);
923
924   }
925
926   $sth->finish;
927
928   $main::lxdebug->leave_sub();
929 }
930
931 sub cogs {
932   $main::lxdebug->enter_sub();
933
934   my ($dbh, $form, $id, $totalqty) = @_;
935
936   my $query = qq|SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
937                    (SELECT c.accno FROM chart c
938                     WHERE p.inventory_accno_id = c.id) AS inventory_accno,
939                    (SELECT c.accno FROM chart c
940                     WHERE p.expense_accno_id = c.id) AS expense_accno
941                   FROM invoice i, parts p
942                   WHERE i.parts_id = p.id
943                   AND i.parts_id = $id
944                   AND (i.qty + i.allocated) < 0
945                   ORDER BY trans_id|;
946   my $sth = $dbh->prepare($query);
947   $sth->execute || $form->dberror($query);
948
949   my $allocated = 0;
950   my $qty;
951
952   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
953     if (($qty = (($ref->{qty} * -1) - $ref->{allocated})) > $totalqty) {
954       $qty = $totalqty;
955     }
956
957     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|,
958                           $qty);
959
960     # total expenses and inventory
961     # sellprice is the cost of the item
962     $linetotal = $form->round_amount($ref->{sellprice} * $qty, 2);
963
964     if (!$eur) {
965
966       # add to expense
967       $form->{amount}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
968       $form->{expense_inventory} .= " " . $ref->{expense_accno};
969
970       # deduct inventory
971       $form->{amount}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
972       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
973     }
974
975     # add allocated
976     $allocated += -$qty;
977
978     last if (($totalqty -= $qty) <= 0);
979   }
980
981   $sth->finish;
982
983   $main::lxdebug->leave_sub();
984
985   return $allocated;
986 }
987
988 sub reverse_invoice {
989   $main::lxdebug->enter_sub();
990
991   my ($dbh, $form) = @_;
992
993   # reverse inventory items
994   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
995                  p.inventory_accno_id
996                  FROM invoice i
997                  JOIN parts p ON (i.parts_id = p.id)
998                  WHERE i.trans_id = $form->{id}|;
999   my $sth = $dbh->prepare($query);
1000   $sth->execute || $form->dberror($query);
1001
1002   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1003
1004     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1005
1006       # if the invoice item is not an assemblyitem adjust parts onhand
1007       if (!$ref->{assemblyitem}) {
1008
1009         # adjust onhand in parts table
1010         $form->update_balance($dbh, "parts", "onhand",
1011                               qq|id = $ref->{parts_id}|,
1012                               $ref->{qty});
1013       }
1014
1015       # loop if it is an assembly
1016       next if ($ref->{assembly});
1017
1018       # de-allocated purchases
1019       $query = qq|SELECT i.id, i.trans_id, i.allocated
1020                   FROM invoice i
1021                   WHERE i.parts_id = $ref->{parts_id}
1022                   AND i.allocated > 0
1023                   ORDER BY i.trans_id DESC|;
1024       my $sth = $dbh->prepare($query);
1025       $sth->execute || $form->dberror($query);
1026
1027       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
1028         $qty = $ref->{qty};
1029         if (($ref->{qty} - $inhref->{allocated}) > 0) {
1030           $qty = $inhref->{allocated};
1031         }
1032
1033         # update invoice
1034         $form->update_balance($dbh, "invoice", "allocated",
1035                               qq|id = $inhref->{id}|,
1036                               $qty * -1);
1037
1038         last if (($ref->{qty} -= $qty) <= 0);
1039       }
1040       $sth->finish;
1041     }
1042   }
1043
1044   $sth->finish;
1045
1046   # delete acc_trans
1047   $query = qq|DELETE FROM acc_trans
1048               WHERE trans_id = $form->{id}|;
1049   $dbh->do($query) || $form->dberror($query);
1050
1051   # delete invoice entries
1052   $query = qq|DELETE FROM invoice
1053               WHERE trans_id = $form->{id}|;
1054   $dbh->do($query) || $form->dberror($query);
1055
1056   if ($form->{lizenzen}) {
1057     $query = qq|DELETE FROM licenseinvoice
1058               WHERE trans_id in (SELECT id FROM invoice WHERE trans_id = $form->{id})|;
1059     $dbh->do($query) || $form->dberror($query);
1060   }
1061
1062   $query = qq|DELETE FROM shipto
1063               WHERE trans_id = $form->{id}|;
1064   $dbh->do($query) || $form->dberror($query);
1065
1066   $main::lxdebug->leave_sub();
1067 }
1068
1069 sub delete_invoice {
1070   $main::lxdebug->enter_sub();
1071
1072   my ($self, $myconfig, $form, $spool) = @_;
1073
1074   # connect to database
1075   my $dbh = $form->dbconnect_noauto($myconfig);
1076
1077   &reverse_invoice($dbh, $form);
1078
1079   # delete AR record
1080   my $query = qq|DELETE FROM ar
1081                  WHERE id = $form->{id}|;
1082   $dbh->do($query) || $form->dberror($query);
1083
1084   # delete spool files
1085   $query = qq|SELECT s.spoolfile FROM status s
1086               WHERE s.trans_id = $form->{id}|;
1087   my $sth = $dbh->prepare($query);
1088   $sth->execute || $self->dberror($query);
1089
1090   my $spoolfile;
1091   my @spoolfiles = ();
1092
1093   while (($spoolfile) = $sth->fetchrow_array) {
1094     push @spoolfiles, $spoolfile;
1095   }
1096   $sth->finish;
1097
1098   # delete status entries
1099   $query = qq|DELETE FROM status
1100               WHERE trans_id = $form->{id}|;
1101   $dbh->do($query) || $form->dberror($query);
1102
1103   my $rc = $dbh->commit;
1104   $dbh->disconnect;
1105
1106   if ($rc) {
1107     foreach $spoolfile (@spoolfiles) {
1108       unlink "$spool/$spoolfile" if $spoolfile;
1109     }
1110   }
1111
1112   $main::lxdebug->leave_sub();
1113
1114   return $rc;
1115 }
1116
1117 sub retrieve_invoice {
1118   $main::lxdebug->enter_sub();
1119
1120   my ($self, $myconfig, $form) = @_;
1121
1122   # connect to database
1123   my $dbh = $form->dbconnect_noauto($myconfig);
1124
1125   my $query;
1126
1127   if ($form->{id}) {
1128
1129     # get default accounts and last invoice number
1130     $query = qq|SELECT (SELECT c.accno FROM chart c
1131                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1132                        (SELECT c.accno FROM chart c
1133                         WHERE d.income_accno_id = c.id) AS income_accno,
1134                        (SELECT c.accno FROM chart c
1135                         WHERE d.expense_accno_id = c.id) AS expense_accno,
1136                        (SELECT c.accno FROM chart c
1137                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1138                        (SELECT c.accno FROM chart c
1139                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
1140                 d.curr AS currencies
1141                 FROM defaults d|;
1142   } else {
1143     $query = qq|SELECT (SELECT c.accno FROM chart c
1144                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1145                        (SELECT c.accno FROM chart c
1146                         WHERE d.income_accno_id = c.id) AS income_accno,
1147                        (SELECT c.accno FROM chart c
1148                         WHERE d.expense_accno_id = c.id) AS expense_accno,
1149                        (SELECT c.accno FROM chart c
1150                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1151                        (SELECT c.accno FROM chart c
1152                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
1153                 d.curr AS currencies, current_date AS invdate
1154                 FROM defaults d|;
1155   }
1156   my $sth = $dbh->prepare($query);
1157   $sth->execute || $form->dberror($query);
1158
1159   my $ref = $sth->fetchrow_hashref(NAME_lc);
1160   map { $form->{$_} = $ref->{$_} } keys %$ref;
1161   $sth->finish;
1162
1163   if ($form->{id}) {
1164
1165     # retrieve invoice
1166     $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
1167                 a.transdate AS invdate, a.deliverydate, a.paid,
1168                 a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes,
1169                 a.duedate, a.taxincluded, a.curr AS currency,
1170                 a.employee_id, e.name AS employee
1171                 FROM ar a
1172                 LEFT JOIN employee e ON (e.id = a.employee_id)
1173                 WHERE a.id = $form->{id}|;
1174     $sth = $dbh->prepare($query);
1175     $sth->execute || $form->dberror($query);
1176
1177     $ref = $sth->fetchrow_hashref(NAME_lc);
1178     map { $form->{$_} = $ref->{$_} } keys %$ref;
1179     $sth->finish;
1180
1181     $form->{exchangerate} =
1182       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
1183                               "buy");
1184
1185     # get shipto
1186     $query = qq|SELECT s.* FROM shipto s
1187                 WHERE s.trans_id = $form->{id}|;
1188     $sth = $dbh->prepare($query);
1189     $sth->execute || $form->dberror($query);
1190
1191     $ref = $sth->fetchrow_hashref(NAME_lc);
1192     map { $form->{$_} = $ref->{$_} } keys %$ref;
1193     $sth->finish;
1194
1195     # get printed, emailed
1196     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
1197                 FROM status s
1198                 WHERE s.trans_id = $form->{id}|;
1199     $sth = $dbh->prepare($query);
1200     $sth->execute || $form->dberror($query);
1201
1202     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1203       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
1204       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
1205       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
1206         if $ref->{spoolfile};
1207     }
1208     $sth->finish;
1209     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
1210
1211     # retrieve individual items
1212     $query = qq|SELECT (SELECT c.accno FROM chart c
1213                        WHERE p.inventory_accno_id = c.id)
1214                        AS inventory_accno,
1215                        (SELECT c.accno FROM chart c
1216                        WHERE p.income_accno_id = c.id)
1217                        AS income_accno,
1218                        (SELECT c.accno FROM chart c
1219                        WHERE p.expense_accno_id = c.id)
1220                        AS expense_accno,
1221                 i.description, i.qty, i.fxsellprice AS sellprice,
1222                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
1223                 i.project_id, pr.projectnumber, i.serialnumber,
1224                 p.partnumber, p.assembly, p.bin, p.notes AS partnotes, i.id AS invoice_pos,
1225                 pg.partsgroup, i.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=i.pricegroup_id) as pricegroup,
1226                 i.ordnumber, i.transdate, i.cusordnumber
1227                 FROM invoice i
1228                 JOIN parts p ON (i.parts_id = p.id)
1229                 LEFT JOIN project pr ON (i.project_id = pr.id)
1230                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1231                 WHERE i.trans_id = $form->{id}
1232                 AND NOT i.assemblyitem = '1'
1233                 ORDER BY i.id|;
1234     $sth = $dbh->prepare($query);
1235     $sth->execute || $form->dberror($query);
1236     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1237
1238       #set expense_accno=inventory_accno if they are different => bilanz
1239       $vendor_accno =
1240         ($ref->{expense_accno} != $ref->{inventory_accno})
1241         ? $ref->{inventory_accno}
1242         : $ref->{expense_accno};
1243
1244       # get tax rates and description
1245       $accno_id =
1246         ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
1247       $query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
1248                  FROM chart c, tax t
1249                  WHERE c.id=t.chart_id AND t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
1250                  ORDER BY accno|;
1251       $stw = $dbh->prepare($query);
1252       $stw->execute || $form->dberror($query);
1253       $ref->{taxaccounts} = "";
1254       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1255
1256         #    if ($customertax{$ref->{accno}}) {
1257         $ref->{taxaccounts} .= "$ptr->{accno} ";
1258         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1259           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1260           $form->{"$ptr->{accno}_description"} = $ptr->{description};
1261           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1262           $form->{taxaccounts} .= "$ptr->{accno} ";
1263         }
1264
1265       }
1266
1267       if ($form->{lizenzen}) {
1268         $query = qq|SELECT l.licensenumber, l.id AS licenseid
1269                  FROM license l, licenseinvoice li
1270                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
1271         $stg = $dbh->prepare($query);
1272         $stg->execute || $form->dberror($query);
1273         ($licensenumber, $licenseid) = $stg->fetchrow_array();
1274         $ref->{lizenzen} =
1275           "<option value=\"$licenseid\">$licensenumber</option>";
1276         $stg->finish();
1277       }
1278
1279       chop $ref->{taxaccounts};
1280       push @{ $form->{invoice_details} }, $ref;
1281       $stw->finish;
1282     }
1283     $sth->finish;
1284
1285     if ($form->{webdav}) {
1286       &webdav_folder($myconfig, $form);
1287     }
1288   }
1289
1290   my $rc = $dbh->commit;
1291   $dbh->disconnect;
1292
1293   $main::lxdebug->leave_sub();
1294
1295   return $rc;
1296 }
1297
1298 sub get_customer {
1299   $main::lxdebug->enter_sub();
1300
1301   my ($self, $myconfig, $form) = @_;
1302
1303   # connect to database
1304   my $dbh = $form->dbconnect($myconfig);
1305
1306   my $dateformat = $myconfig->{dateformat};
1307   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1308
1309   my $duedate =
1310     ($form->{invdate})
1311     ? "to_date('$form->{invdate}', '$dateformat')"
1312     : "current_date";
1313
1314   $form->{customer_id} *= 1;
1315
1316   # get customer
1317   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
1318                  c.email, c.cc, c.bcc, c.language,
1319                  c.street, c.zipcode, c.city, c.country,
1320                  $duedate + c.terms AS duedate, c.notes AS intnotes,
1321                  b.discount AS tradediscount, b.description AS business, c.klass as customer_klass
1322                  FROM customer c
1323                  LEFT JOIN business b ON (b.id = c.business_id)
1324                  WHERE c.id = $form->{customer_id}|;
1325   my $sth = $dbh->prepare($query);
1326   $sth->execute || $form->dberror($query);
1327
1328   $ref = $sth->fetchrow_hashref(NAME_lc);
1329
1330   map { $form->{$_} = $ref->{$_} } keys %$ref;
1331   $sth->finish;
1332
1333   $form->{creditremaining} = $form->{creditlimit};
1334   $query = qq|SELECT SUM(a.amount - a.paid)
1335               FROM ar a
1336               WHERE a.customer_id = $form->{customer_id}|;
1337   $sth = $dbh->prepare($query);
1338   $sth->execute || $form->dberror($query);
1339
1340   ($form->{creditremaining}) -= $sth->fetchrow_array;
1341
1342   $sth->finish;
1343
1344   $query = qq|SELECT o.amount,
1345                 (SELECT e.buy FROM exchangerate e
1346                  WHERE e.curr = o.curr
1347                  AND e.transdate = o.transdate)
1348               FROM oe o
1349               WHERE o.customer_id = $form->{customer_id}
1350               AND o.quotation = '0'
1351               AND o.closed = '0'|;
1352   $sth = $dbh->prepare($query);
1353   $sth->execute || $form->dberror($query);
1354
1355   while (my ($amount, $exch) = $sth->fetchrow_array) {
1356     $exch = 1 unless $exch;
1357     $form->{creditremaining} -= $amount * $exch;
1358   }
1359   $sth->finish;
1360
1361   $form->get_contacts($dbh, $form->{customer_id});
1362   ($null, $form->{cp_id}) = split /--/, $form->{contact};
1363
1364   # get contact if selected
1365   if ($form->{contact} ne "--" && $form->{contact} ne "") {
1366     $form->get_contact($dbh, $form->{cp_id});
1367   }
1368
1369   # get shipto if we did not converted an order or invoice
1370   if (!$form->{shipto}) {
1371     map { delete $form->{$_} }
1372       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
1373
1374     $query = qq|SELECT s.* FROM shipto s
1375                 WHERE s.trans_id = $form->{customer_id}|;
1376     $sth = $dbh->prepare($query);
1377     $sth->execute || $form->dberror($query);
1378
1379     $ref = $sth->fetchrow_hashref(NAME_lc);
1380     map { $form->{$_} = $ref->{$_} } keys %$ref;
1381     $sth->finish;
1382   }
1383
1384   # get taxes we charge for this customer
1385   $query = qq|SELECT c.accno
1386               FROM chart c
1387               JOIN customertax ct ON (ct.chart_id = c.id)
1388               WHERE ct.customer_id = $form->{customer_id}|;
1389   $sth = $dbh->prepare($query);
1390   $sth->execute || $form->dberror($query);
1391
1392   my $customertax = ();
1393   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1394     $customertax{ $ref->{accno} } = 1;
1395   }
1396   $sth->finish;
1397
1398   # setup last accounts used for this customer
1399   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
1400     $query = qq|SELECT c.accno, c.description, c.link, c.category
1401                 FROM chart c
1402                 JOIN acc_trans ac ON (ac.chart_id = c.id)
1403                 JOIN ar a ON (a.id = ac.trans_id)
1404                 WHERE a.customer_id = $form->{customer_id}
1405                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
1406                 AND a.id IN (SELECT max(a2.id) FROM ar a2
1407                              WHERE a2.customer_id = $form->{customer_id})|;
1408     $sth = $dbh->prepare($query);
1409     $sth->execute || $form->dberror($query);
1410
1411     my $i = 0;
1412     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1413       if ($ref->{category} eq 'I') {
1414         $i++;
1415         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
1416       }
1417       if ($ref->{category} eq 'A') {
1418         $form->{ARselected} = $form->{AR_1} =
1419           "$ref->{accno}--$ref->{description}";
1420       }
1421     }
1422     $sth->finish;
1423     $form->{rowcount} = $i if ($i && !$form->{type});
1424   }
1425
1426   $dbh->disconnect;
1427
1428   $main::lxdebug->leave_sub();
1429 }
1430
1431 sub retrieve_item {
1432   $main::lxdebug->enter_sub();
1433
1434   my ($self, $myconfig, $form) = @_;
1435
1436   my $i = $form->{rowcount};
1437
1438   my $where = "NOT p.obsolete = '1'";
1439
1440   if ($form->{"partnumber_$i"}) {
1441     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1442     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1443   }
1444   if ($form->{"description_$i"}) {
1445     my $description = $form->like(lc $form->{"description_$i"});
1446     $where .= " AND lower(p.description) LIKE '$description'";
1447   }
1448
1449   if ($form->{"partsgroup_$i"}) {
1450     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1451     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1452   }
1453
1454   if ($form->{"description_$i"}) {
1455     $where .= " ORDER BY p.description";
1456   } else {
1457     $where .= " ORDER BY p.partnumber";
1458   }
1459
1460   # connect to database
1461   my $dbh = $form->dbconnect($myconfig);
1462
1463   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1464                         p.listprice,
1465                         c1.accno AS inventory_accno,
1466                         c2.accno AS income_accno,
1467                         c3.accno AS expense_accno,
1468                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes,
1469                  pg.partsgroup
1470                  FROM parts p
1471                  LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
1472                  LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
1473                  LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
1474                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1475                  WHERE $where|;
1476   my $sth = $dbh->prepare($query);
1477   $sth->execute || $form->dberror($query);
1478
1479   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1480
1481     #set expense_accno=inventory_accno if they are different => bilanz
1482     $vendor_accno =
1483       ($ref->{expense_accno} != $ref->{inventory_accno})
1484       ? $ref->{inventory_accno}
1485       : $ref->{expense_accno};
1486
1487     # get tax rates and description
1488     $accno_id =
1489       ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
1490     $query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
1491               FROM chart c, tax t
1492               WHERE c.id=t.chart_id AND t.taxkey in (SELECT c2.taxkey_id from chart c2 where c2.accno = '$accno_id')
1493               ORDER BY c.accno|;
1494     $stw = $dbh->prepare($query);
1495     $stw->execute || $form->dberror($query);
1496
1497     $ref->{taxaccounts} = "";
1498     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1499
1500       #    if ($customertax{$ref->{accno}}) {
1501       $ref->{taxaccounts} .= "$ptr->{accno} ";
1502       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1503         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1504         $form->{"$ptr->{accno}_description"} = $ptr->{description};
1505         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1506         $form->{taxaccounts} .= "$ptr->{accno} ";
1507       }
1508
1509     }
1510
1511     $stw->finish;
1512     chop $ref->{taxaccounts};
1513
1514     push @{ $form->{item_list} }, $ref;
1515
1516     if ($form->{lizenzen}) {
1517       if ($ref->{inventory_accno} > 0) {
1518         $query =
1519           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
1520         $stw = $dbh->prepare($query);
1521         $stw->execute || $form->dberror($query);
1522         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1523           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
1524         }
1525         $stw->finish;
1526       }
1527     }
1528   }
1529   $sth->finish;
1530   $dbh->disconnect;
1531
1532   $main::lxdebug->leave_sub();
1533 }
1534
1535 ##########################
1536 # get pricegroups from database
1537 # build up selected pricegroup
1538 # if an exchange rate - change price
1539 # for each part
1540 #
1541 sub get_pricegroups_for_parts {
1542
1543   $main::lxdebug->enter_sub();
1544
1545   my ($self, $myconfig, $form) = @_;
1546
1547   my $dbh = $form->dbconnect($myconfig);
1548
1549   my $i  = 1;
1550   my $id = 0;
1551
1552   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
1553
1554     $id = $form->{"id_$i"};
1555
1556     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
1557
1558       $id = $form->{"new_id_$i"};
1559     }
1560
1561     ($price, $selectedpricegroup_id) = split /--/,
1562       $form->{"sellprice_drag_$i"};
1563
1564     $pricegroup_old = $form->{"pricegroup_old_$i"};
1565
1566     $price_new = $form->{"price_new_$i"};
1567
1568     $price_old = $form->{"price_old_$i"};
1569
1570     $query =
1571       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|;
1572
1573     $pkq = $dbh->prepare($query);
1574     $pkq->execute || $form->dberror($query);
1575     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
1576
1577       #       push @{ $form->{PRICES}{$id} }, $pkr;
1578       push @{ $form->{PRICES}{$i} }, $pkr;
1579       $pkr->{id}       = $id;
1580       $pkr->{selected} = '';
1581
1582       # if there is an exchange rate change price
1583       if (($form->{exchangerate} * 1) != 0) {
1584
1585         $pkr->{price} /= $form->{exchangerate};
1586       }
1587       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
1588
1589       if ($selectedpricegroup_id eq undef) {
1590         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
1591
1592           $pkr->{selected}  = ' selected';
1593           $last->{selected} = '';
1594
1595           # no customer pricesgroup set
1596           if ($pkr->{price} == $pkr->{default_sellprice}) {
1597
1598             $pkr->{price} = $form->{"sellprice_$i"};
1599
1600           } else {
1601
1602             $form->{"sellprice_$i"} = $pkr->{price};
1603           }
1604
1605         } else {
1606           if ($pkr->{price} == $pkr->{default_sellprice}) {
1607
1608             $pkr->{price}    = $form->{"sellprice_$i"};
1609             $pkr->{selected} = ' selected';
1610           }
1611         }
1612       }
1613       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
1614         if ($selectedpricegroup_id ne $pricegroup_old) {
1615           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
1616             if ($price_new != $form->{"sellprice_$i"}) {
1617             } else {
1618               $pkr->{selected}  = ' selected';
1619               $last->{selected} = '';
1620             }
1621           }
1622         } else {
1623           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
1624             if ($pkr->{pricegroup_id} == 0) {
1625               $pkr->{price}     = $form->{"sellprice_$i"};
1626               $pkr->{selected}  = ' selected';
1627               $last->{selected} = '';
1628             }
1629           } else {
1630             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
1631               $pkr->{selected}  = ' selected';
1632               $last->{selected} = '';
1633               if (    ($pkr->{pricegroup_id} == 0)
1634                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
1635
1636                 # $pkr->{price}                         = $form->{"sellprice_$i"};
1637                   } else {
1638                 $pkr->{price} = $form->{"sellprice_$i"};
1639               }
1640             }
1641           }
1642         }
1643       }
1644     }
1645     $i++;
1646
1647     $pkq->finish;
1648   }
1649
1650   $dbh->disconnect;
1651
1652   $main::lxdebug->leave_sub();
1653 }
1654
1655 sub webdav_folder {
1656   $main::lxdebug->enter_sub();
1657
1658   my ($myconfig, $form) = @_;
1659
1660 SWITCH: {
1661     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
1662       if ($form->{vc} eq "customer");
1663     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
1664       if ($form->{vc} eq "vendor");
1665   }
1666
1667   if (!-d $path) {
1668     mkdir($path, 0770) or die "can't make directory $!\n";
1669   } else {
1670     if ($form->{id}) {
1671       @files = <$path/*>;
1672       foreach $file (@files) {
1673         $file =~ /\/([^\/]*)$/;
1674         $fname = $1;
1675         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
1676         $lxerp = $1;
1677         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
1678         $form->{WEBDAV}{$fname} = $link;
1679       }
1680     }
1681   }
1682
1683   $main::lxdebug->leave_sub();
1684 }
1685
1686 1;
1687