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