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