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