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