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