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