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