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