This commit was generated by cvs2svn to compensate for changes in r2526,
[freeside.git] / sql-ledger / SL / IS.pm
1 #=====================================================================
2 # SQL-Ledger Accounting
3 # Copyright (C) 1998-2002
4 #
5 #  Author: Dieter Simader
6 #   Email: dsimader@sql-ledger.org
7 #     Web: http://www.sql-ledger.org
8 #
9 #  Contributors:
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->{invdate} 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->{invdate}'
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   my $tax = 0;
50   my $item;
51   my $i;
52   my @partsgroup = ();
53   my $partsgroup;
54   my %oid = ( 'Pg' => 'oid',
55               'Oracle' => 'rowid' );
56   
57   # sort items by partsgroup
58   for $i (1 .. $form->{rowcount}) {
59     $partsgroup = "";
60     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
61       $form->format_string("partsgroup_$i");
62       $partsgroup = $form->{"partsgroup_$i"};
63     }
64     push @partsgroup, [ $i, $partsgroup ];
65   }
66   
67   my $sameitem = "";
68   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
69     $i = $item->[0];
70
71     if ($item->[1] ne $sameitem) {
72       push(@{ $form->{description} }, qq|$item->[1]|);
73       $sameitem = $item->[1];
74
75       map { push(@{ $form->{$_} }, "") } qw(runningnumber number bin qty unit deliverydate sellprice listprice netprice discount linetotal);
76     }
77     
78     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
79     
80     if ($form->{"qty_$i"} != 0) {
81
82       # add number, description and qty to $form->{number}, ....
83       push(@{ $form->{runningnumber} }, $i);
84       push(@{ $form->{number} }, qq|$form->{"partnumber_$i"}|);
85       push(@{ $form->{bin} }, qq|$form->{"bin_$i"}|);
86       push(@{ $form->{description} }, qq|$form->{"description_$i"}|);
87       push(@{ $form->{qty} }, $form->format_amount($myconfig, $form->{"qty_$i"}));
88       push(@{ $form->{unit} }, qq|$form->{"unit_$i"}|);
89       push(@{ $form->{deliverydate} }, qq|$form->{"deliverydate_$i"}|);
90       
91       push(@{ $form->{sellprice} }, $form->{"sellprice_$i"});
92       
93       # listprice
94       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
95
96       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
97       my ($dec) = ($sellprice =~ /\.(\d+)/);
98       $dec = length $dec;
99       my $decimalplaces = ($dec > 2) ? $dec : 2;
100       
101       my $discount = $form->round_amount($sellprice * $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100, $decimalplaces);
102       
103       # keep a netprice as well, (sellprice - discount)
104       $form->{"netprice_$i"} = $sellprice - $discount;
105       push(@{ $form->{netprice} }, ($form->{"netprice_$i"} != 0) ? $form->format_amount($myconfig, $form->{"netprice_$i"}, $decimalplaces) : " ");
106
107       
108       my $linetotal = $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
109
110       $discount = ($discount != 0) ? $form->format_amount($myconfig, $discount * -1, $decimalplaces) : " ";
111       $linetotal = ($linetotal != 0) ? $linetotal : " ";
112       
113       push(@{ $form->{discount} }, $discount);
114
115       $form->{total} += $linetotal;
116
117       push(@{ $form->{linetotal} }, $form->format_amount($myconfig, $linetotal, 2));
118       
119       my $taxrate = 0;
120       my ($taxamount, $taxbase);
121       
122       map { $taxrate += $form->{"${_}_rate"} } split / /, $form->{"taxaccounts_$i"};
123
124       if ($form->{taxincluded}) {
125         # calculate tax
126         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
127         $taxbase = $linetotal - $taxamount;
128       } else {
129         $taxamount = $linetotal * $taxrate;
130         $taxbase = $linetotal;
131       }
132       
133       if ($taxamount != 0) {
134         foreach my $item (split / /, $form->{"taxaccounts_$i"}) {
135           $taxaccounts{$item} += $taxamount * $form->{"${item}_rate"} / $taxrate;
136           $taxbase{$item} += $taxbase;
137         }
138       }
139
140       if ($form->{"assembly_$i"}) {
141         $sameitem = "";
142         
143         # get parts and push them onto the stack
144         my $sortorder = "";
145         if ($form->{groupitems}) { 
146           $sortorder = qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
147         } else {
148           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
149         }
150         
151         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
152                     pg.partsgroup
153                     FROM assembly a
154                     JOIN parts p ON (a.parts_id = p.id)
155                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
156                     WHERE a.bom = '1'
157                     AND a.id = '$form->{"id_$i"}'
158                     $sortorder|;
159         $sth = $dbh->prepare($query);
160         $sth->execute || $form->dberror($query);
161
162         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
163           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
164             map { push(@{ $form->{$_} }, "") } qw(runningnumber number unit qty bin sellprice listprice netprice discount linetotal);
165             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
166             push(@{ $form->{description} }, $sameitem);
167           }
168             
169           push(@{ $form->{number} }, qq|$ref->{partnumber}|);
170           push(@{ $form->{description} }, qq|$ref->{description}|);
171           push(@{ $form->{unit} }, qq|$ref->{unit}|);
172           push(@{ $form->{qty} }, $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}));
173
174           map { push(@{ $form->{$_} }, "") } qw(runningnumber bin sellprice listprice netprice discount linetotal);
175           
176         }
177         $sth->finish;
178       }
179       
180     }
181   }
182
183
184   foreach my $item (sort keys %taxaccounts) {
185     if ($form->round_amount($taxaccounts{$item}, 2) != 0) {
186       push(@{ $form->{taxbase} }, $form->format_amount($myconfig, $taxbase{$item}, 2));
187       
188       $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
189       
190       push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount));
191       push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
192       push(@{ $form->{taxrate} }, $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
193       push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
194     }
195   }
196     
197
198   for my $i (1 .. $form->{paidaccounts}) {
199     if ($form->{"paid_$i"}) {
200       push(@{ $form->{payment} }, $form->{"paid_$i"});
201       my ($accno, $description) = split /--/, $form->{"AR_paid_$i"};
202       push(@{ $form->{paymentaccount} }, $description); 
203       push(@{ $form->{paymentdate} }, $form->{"datepaid_$i"});
204       push(@{ $form->{paymentsource} }, $form->{"source_$i"});
205
206       $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
207     }
208   }
209   
210   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
211   $form->{invtotal} = ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
212   $form->{total} = $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
213   $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
214
215   $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
216
217   # myconfig variables
218   map { $form->{$_} = $myconfig->{$_} } (qw(company address tel fax signature businessnumber));
219   $form->{username} = $myconfig->{name};
220
221   $dbh->disconnect;
222   
223 }
224
225
226 sub project_description {
227   my ($self, $dbh, $id) = @_;
228
229   my $query = qq|SELECT description
230                  FROM project
231                  WHERE id = $id|;
232   my $sth = $dbh->prepare($query);
233   $sth->execute || $form->dberror($query);
234
235   ($_) = $sth->fetchrow_array;
236
237   $sth->finish;
238
239   $_;
240
241 }
242
243
244 sub customer_details {
245   my ($self, $myconfig, $form) = @_;
246   
247   # connect to database
248   my $dbh = $form->dbconnect($myconfig);
249   
250   # get rest for the customer
251   my $query = qq|SELECT customernumber, name, addr1, addr2, addr3, addr4,
252                  phone as customerphone, fax as customerfax, contact
253                  FROM customer
254                  WHERE id = $form->{customer_id}|;
255   my $sth = $dbh->prepare($query);
256   $sth->execute || $form->dberror($query);
257
258   $ref = $sth->fetchrow_hashref(NAME_lc);
259   map { $form->{$_} = $ref->{$_} } keys %$ref;
260
261   $sth->finish;
262   $dbh->disconnect;
263
264 }
265
266
267 sub post_invoice {
268   my ($self, $myconfig, $form) = @_;
269   
270   # connect to database, turn off autocommit
271   my $dbh = $form->dbconnect_noauto($myconfig);
272
273   my ($query, $sth, $null, $project_id, $deliverydate);
274   my $exchangerate = 0;
275  
276   if ($form->{id}) {
277
278     &reverse_invoice($dbh, $form);
279
280   } else {
281     my $uid = time;
282     $uid .= $form->{login};
283     
284     $query = qq|INSERT INTO ar (invnumber, employee_id)
285                 VALUES ('$uid', (SELECT id FROM employee
286                                  WHERE login = '$form->{login}') )|;
287     $dbh->do($query) || $form->dberror($query);
288
289     $query = qq|SELECT id FROM ar
290                 WHERE invnumber = '$uid'|;
291     $sth = $dbh->prepare($query);
292     $sth->execute || $form->dberror($query);
293
294     ($form->{id}) = $sth->fetchrow_array;
295     $sth->finish;
296   }
297
298
299   map { $form->{$_} =~ s/'/''/g } (qw(invnumber shippingpoint notes message));
300
301   my ($netamount, $invoicediff) = (0, 0);
302   my ($amount, $linetotal, $lastincomeaccno);
303
304   if ($form->{currency} eq $form->{defaultcurrency}) {
305     $form->{exchangerate} = 1;
306   } else {
307     $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
308   }
309
310   $form->{exchangerate} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{exchangerate});
311   
312
313   foreach my $i (1 .. $form->{rowcount}) {
314     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
315     
316     if ($form->{"qty_$i"} != 0) {
317
318       map { $form->{"${_}_$i"} =~ s/'/''/g } (qw(partnumber description unit));
319       
320       # undo discount formatting
321       $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
322
323       my ($allocated, $taxrate) = (0, 0);
324       my $taxamount;
325       
326       # keep entered selling price
327       my $fxsellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
328       
329       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
330       $dec = length $dec;
331       my $decimalplaces = ($dec > 2) ? $dec : 2;
332       
333       # deduct discount
334       my $discount = $form->round_amount($fxsellprice * $form->{"discount_$i"}, $decimalplaces);
335       $form->{"sellprice_$i"} = $fxsellprice - $discount;
336       
337       # add tax rates
338       map { $taxrate += $form->{"${_}_rate"} } split / /, $form->{"taxaccounts_$i"};
339
340       # round linetotal to 2 decimal places
341       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
342       
343       if ($form->{taxincluded}) {
344         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
345         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
346       } else {
347         $taxamount = $linetotal * $taxrate;
348       }
349
350       $netamount += $linetotal;
351       
352       if ($taxamount != 0) {
353         map { $form->{amount}{$form->{id}}{$_} += $taxamount * $form->{"${_}_rate"} / $taxrate } split / /, $form->{"taxaccounts_$i"};
354       }
355     
356     
357       # add amount to income, $form->{amount}{trans_id}{accno}
358       $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
359       
360       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
361       $linetotal = $form->round_amount($linetotal, 2);
362       
363       # this is the difference from the inventory
364       $invoicediff += ($amount - $linetotal);
365                       
366       $form->{amount}{$form->{id}}{$form->{"income_accno_$i"}} += $linetotal;
367       
368       $lastincomeaccno = $form->{"income_accno_$i"};
369       
370
371       # adjust and round sellprice
372       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
373       
374       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
375         # adjust parts onhand quantity
376
377         if ($form->{"assembly_$i"}) {
378           # do not update if assembly consists of all services
379           $query = qq|SELECT sum(p.inventory_accno_id)
380                       FROM parts p, assembly a
381                       WHERE a.parts_id = p.id
382                       AND a.id = $form->{"id_$i"}|;
383           $sth = $dbh->prepare($query);
384           $sth->execute || $form->dberror($query);
385
386           if ($sth->fetchrow_array) {
387             $form->update_balance($dbh,
388                                   "parts",
389                                   "onhand",
390                                   qq|id = $form->{"id_$i"}|,
391                                   $form->{"qty_$i"} * -1);
392           }
393           $sth->finish;
394            
395           # record assembly item as allocated
396           &process_assembly($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
397         } else {
398           $form->update_balance($dbh,
399                                 "parts",
400                                 "onhand",
401                                 qq|id = $form->{"id_$i"}|,
402                                 $form->{"qty_$i"} * -1);
403           
404           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
405         }
406       }
407
408       $project_id = 'NULL';
409       if ($form->{"project_id_$i"}) {
410         $project_id = $form->{"project_id_$i"};
411       }
412       $deliverydate = ($form->{"deliverydate_$i"}) ? qq|'$form->{"deliverydate_$i"}'| : "NULL";
413
414       # save detail record in invoice table
415       $query = qq|INSERT INTO invoice (trans_id, parts_id, description, qty,
416                   sellprice, fxsellprice, discount, allocated, assemblyitem,
417                   unit, deliverydate, project_id)
418                   VALUES ($form->{id}, $form->{"id_$i"},
419                   '$form->{"description_$i"}', $form->{"qty_$i"},
420                   $form->{"sellprice_$i"}, $fxsellprice,
421                   $form->{"discount_$i"}, $allocated, 'f',
422                   '$form->{"unit_$i"}', $deliverydate, $project_id)|;
423       $dbh->do($query) || $form->dberror($query);
424
425     }
426   }
427
428
429   $form->{datepaid} = $form->{invdate};
430   
431   # total payments, don't move we need it here
432   for my $i (1 .. $form->{paidaccounts}) {
433     $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
434     $form->{paid} += $form->{"paid_$i"};
435     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
436   }
437   
438   my ($tax, $diff) = (0, 0);
439   
440   $netamount = $form->round_amount($netamount, 2);
441   
442   # figure out rounding errors for total amount vs netamount + taxes
443   if ($form->{taxincluded}) {
444     
445     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
446     $diff += $amount - $netamount * $form->{exchangerate};
447     $netamount = $amount;
448     
449     foreach my $item (split / /, $form->{taxaccounts}) {
450       $amount = $form->{amount}{$form->{id}}{$item} * $form->{exchangerate};
451       $form->{amount}{$form->{id}}{$item} = $form->round_amount($amount, 2);
452       $tax += $form->{amount}{$form->{id}}{$item};
453       $netamount -= $form->{amount}{$form->{id}}{$item};
454     }
455
456     $invoicediff += $diff;
457     ######## this only applies to tax included
458     if ($lastincomeaccno) {
459       $form->{amount}{$form->{id}}{$lastincomeaccno} += $invoicediff;
460     }
461
462   } else {
463     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
464     $diff = $amount - $netamount * $form->{exchangerate};
465     $netamount = $amount;
466     foreach my $item (split / /, $form->{taxaccounts}) {
467       $form->{amount}{$form->{id}}{$item} = $form->round_amount($form->{amount}{$form->{id}}{$item}, 2);
468       $amount = $form->round_amount($form->{amount}{$form->{id}}{$item} * $form->{exchangerate}, 2);
469       $diff += $amount - $form->{amount}{$form->{id}}{$item} * $form->{exchangerate};
470       $form->{amount}{$form->{id}}{$item} = $form->round_amount($amount, 2);
471       $tax += $form->{amount}{$form->{id}}{$item};
472     }
473   }
474
475   
476   $form->{amount}{$form->{id}}{$form->{AR}} = $netamount + $tax;
477
478   if ($form->{paid} != 0) {
479     $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
480   }
481   
482   # reverse AR
483   $form->{amount}{$form->{id}}{$form->{AR}} *= -1;
484
485
486   # update exchangerate
487   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
488     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, $form->{exchangerate}, 0);
489   }
490     
491   foreach my $trans_id (keys %{$form->{amount}}) {
492     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
493       if (($form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)) != 0) {
494         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
495                     transdate)
496                     VALUES ($trans_id, (SELECT id FROM chart
497                                         WHERE accno = '$accno'),
498                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}')|;
499         $dbh->do($query) || $form->dberror($query);
500       }
501     }
502   }
503
504   # deduct payment differences from diff
505   for my $i (1 .. $form->{paidaccounts}) {
506     if ($form->{"paid_$i"} != 0) {
507       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
508       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
509     }
510   }
511
512   # force AR entry if 0
513   $form->{amount}{$form->{id}}{$form->{AR}} = 1 if ($form->{amount}{$form->{id}}{$form->{AR}} == 0);
514   
515   # record payments and offsetting AR
516   for my $i (1 .. $form->{paidaccounts}) {
517     
518     if ($form->{"paid_$i"} != 0) {
519       my ($accno) = split /--/, $form->{"AR_paid_$i"};
520       $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
521       $form->{datepaid} = $form->{"datepaid_$i"};
522       
523       # record AR
524       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff, 2);
525
526       if ($form->{amount}{$form->{id}}{$form->{AR}} != 0) {
527         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
528                     transdate)
529                     VALUES ($form->{id}, (SELECT id FROM chart
530                                         WHERE accno = '$form->{AR}'),
531                     $amount, '$form->{"datepaid_$i"}')|;
532         $dbh->do($query) || $form->dberror($query);
533       }
534
535       # record payment
536       $form->{"paid_$i"} *= -1;
537
538       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
539                   source)
540                   VALUES ($form->{id}, (SELECT id FROM chart
541                                       WHERE accno = '$accno'),
542                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
543                   '$form->{"source_$i"}')|;
544       $dbh->do($query) || $form->dberror($query);
545
546       
547       $exchangerate = 0;
548       
549       if ($form->{currency} eq $form->{defaultcurrency}) {
550         $form->{"exchangerate_$i"} = 1;
551       } else {
552         $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
553         
554         $form->{"exchangerate_$i"} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
555       }
556       
557       
558       # exchangerate difference
559       $form->{fx}{$accno}{$form->{"datepaid_$i"}} += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
560
561       
562       # gain/loss
563       $amount = $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} * $form->{"exchangerate_$i"};
564       if ($amount > 0) {
565         $form->{fx}{$form->{fxgain_accno}}{$form->{"datepaid_$i"}} += $amount;
566       } else {
567         $form->{fx}{$form->{fxloss_accno}}{$form->{"datepaid_$i"}} += $amount;
568       }
569
570       $diff = 0;
571
572       # update exchange rate
573       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
574         $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0);
575       }
576     }
577   }
578
579   
580   # record exchange rate differences and gains/losses
581   foreach my $accno (keys %{$form->{fx}}) {
582     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
583       if (($form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2)) != 0) {
584
585         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
586                     transdate, cleared, fx_transaction)
587                     VALUES ($form->{id},
588                            (SELECT id FROM chart
589                             WHERE accno = '$accno'),
590                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
591         $dbh->do($query) || $form->dberror($query);
592       }
593     }
594   }
595  
596
597   $amount = $netamount + $tax;
598   
599   # set values which could be empty to 0
600   $form->{terms} *= 1;
601   $form->{taxincluded} *= 1;
602   my $datepaid = ($form->{paid}) ? qq|'$form->{datepaid}'| : "NULL";
603   my $duedate = ($form->{duedate}) ? qq|'$form->{duedate}'| : "NULL";
604
605   # fill in subject if there is none
606   $form->{subject} = qq|$form->{label} $form->{invnumber}| unless $form->{subject};
607   # if there is a message stuff it into the notes
608   my $cc = "Cc: $form->{cc}\\r\n" if $form->{cc};
609   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
610   $form->{notes} .= qq|\r
611 \r
612 [email]\r
613 To: $form->{email}\r
614 $cc${bcc}Subject: $form->{subject}\r
615 \r
616 Message: $form->{message}\r| if $form->{message};
617
618   # save AR record
619   $query = qq|UPDATE ar set
620               invnumber = '$form->{invnumber}',
621               ordnumber = '$form->{ordnumber}',
622               transdate = '$form->{invdate}',
623               customer_id = $form->{customer_id},
624               amount = $amount,
625               netamount = $netamount,
626               paid = $form->{paid},
627               datepaid = $datepaid,
628               duedate = $duedate,
629               invoice = '1',
630               shippingpoint = '$form->{shippingpoint}',
631               terms = $form->{terms},
632               notes = '$form->{notes}',
633               taxincluded = '$form->{taxincluded}',
634               curr = '$form->{currency}'
635               WHERE id = $form->{id}
636              |;
637   $dbh->do($query) || $form->dberror($query);
638
639   # add shipto
640   $form->{name} = $form->{customer};
641   $form->{name} =~ s/--$form->{customer_id}//;
642   $form->add_shipto($dbh, $form->{id});
643
644   my $rc = $dbh->commit;
645   $dbh->disconnect;
646
647   $rc;
648   
649 }
650
651
652 sub process_assembly {
653   my ($dbh, $form, $id, $totalqty) = @_;
654
655   my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
656                  p.partnumber, p.description, p.unit,
657                  p.inventory_accno_id, p.income_accno_id,
658                  p.expense_accno_id
659                  FROM assembly a, parts p
660                  WHERE a.parts_id = p.id
661                  AND a.id = $id|;
662   my $sth = $dbh->prepare($query);
663   $sth->execute || $form->dberror($query);
664
665   
666   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
667
668     my $allocated = 0;
669     
670     $ref->{inventory_accno_id} *= 1;
671     $ref->{expense_accno_id} *= 1;
672
673     map { $ref->{$_} =~ s/'/''/g } (qw(partnumber description unit));
674     
675     # multiply by number of assemblies
676     $ref->{qty} *= $totalqty;
677     
678     if ($ref->{assembly}) {
679       &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty});
680       next;
681     } else {
682       if ($ref->{inventory_accno_id}) {
683         $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty});
684       }
685     }
686
687     # save detail record for individual assembly item in invoice table
688     $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
689                 sellprice, fxsellprice, allocated, assemblyitem, unit)
690                 VALUES
691                 ($form->{id}, '$ref->{description}',
692                 $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't',
693                 '$ref->{unit}')|;
694     $dbh->do($query) || $form->dberror($query);
695          
696   }
697
698   $sth->finish;
699
700 }
701
702
703 sub cogs {
704   my ($dbh, $form, $id, $totalqty) = @_;
705     
706   my $query = qq|SELECT i.id, i.trans_id, i.qty, i.allocated, i.sellprice,
707                         (SELECT c.accno FROM chart c
708                          WHERE p.inventory_accno_id = c.id)
709                          AS inventory_accno,
710                         (SELECT c.accno FROM chart c
711                          WHERE p.expense_accno_id = c.id)
712                          AS expense_accno
713                   FROM invoice i, parts p
714                   WHERE i.parts_id = p.id
715                   AND i.parts_id = $id
716                   AND (i.qty + i.allocated) < 0
717                   ORDER BY trans_id|;
718   my $sth = $dbh->prepare($query);
719   $sth->execute || $form->dberror($query);
720
721   my $allocated = 0;
722   my $qty;
723   
724   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
725     if (($qty = (($ref->{qty} * -1) - $ref->{allocated})) > $totalqty) {
726       $qty = $totalqty;
727     }
728     
729     $form->update_balance($dbh,
730                           "invoice",
731                           "allocated",
732                           qq|id = $ref->{id}|,
733                           $qty);
734
735     # total expenses and inventory
736     # sellprice is the cost of the item
737     $linetotal = $form->round_amount($ref->{sellprice} * $qty, 2);
738     
739     # add to expense
740     $form->{amount}{$form->{id}}{$ref->{expense_accno}} += -$linetotal;
741
742     # deduct inventory
743     $form->{amount}{$form->{id}}{$ref->{inventory_accno}} -= -$linetotal;
744
745     # add allocated
746     $allocated += -$qty;
747     
748     last if (($totalqty -= $qty) <= 0);
749   }
750
751   $sth->finish;
752
753   $allocated;
754   
755 }
756
757
758
759 sub reverse_invoice {
760   my ($dbh, $form) = @_;
761   
762   # reverse inventory items
763   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
764                  p.inventory_accno_id
765                  FROM invoice i, parts p
766                  WHERE i.parts_id = p.id
767                  AND i.trans_id = $form->{id}|;
768   my $sth = $dbh->prepare($query);
769   $sth->execute || $form->dberror($query);
770
771   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
772
773     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
774
775       # if the invoice item is not an assemblyitem adjust parts onhand
776       unless ($ref->{assemblyitem}) {
777         # adjust onhand in parts table
778         $form->update_balance($dbh,
779                               "parts",
780                               "onhand",
781                               qq|id = $ref->{parts_id}|,
782                               $ref->{qty});
783       }
784
785       # loop if it is an assembly
786       next if ($ref->{assembly});
787       
788       # de-allocated purchases
789       $query = qq|SELECT id, trans_id, allocated
790                   FROM invoice
791                   WHERE parts_id = $ref->{parts_id}
792                   AND allocated > 0
793                   ORDER BY trans_id DESC|;
794       my $sth = $dbh->prepare($query);
795       $sth->execute || $form->dberror($query);
796
797       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
798         $qty = $ref->{qty};
799         if (($ref->{qty} - $inhref->{allocated}) > 0) {
800           $qty = $inhref->{allocated};
801         }
802         
803         # update invoice
804         $form->update_balance($dbh,
805                               "invoice",
806                               "allocated",
807                               qq|id = $inhref->{id}|,
808                               $qty * -1);
809
810         last if (($ref->{qty} -= $qty) <= 0);
811       }
812       $sth->finish;
813     }
814   }
815   
816   $sth->finish;
817   
818   # delete acc_trans
819   $query = qq|DELETE FROM acc_trans
820               WHERE trans_id = $form->{id}|;
821   $dbh->do($query) || $form->dberror($query);
822  
823   # delete invoice entries
824   $query = qq|DELETE FROM invoice
825               WHERE trans_id = $form->{id}|;
826   $dbh->do($query) || $form->dberror($query);
827
828   $query = qq|DELETE FROM shipto
829               WHERE trans_id = $form->{id}|;
830   $dbh->do($query) || $form->dberror($query);
831
832 }
833
834
835
836 sub delete_invoice {
837   my ($self, $myconfig, $form) = @_;
838
839   # connect to database
840   my $dbh = $form->dbconnect_noauto($myconfig);
841
842   # check for other foreign currency transactions
843   $form->delete_exchangerate($dbh) if ($form->{currency} ne $form->{defaultcurrency});
844  
845   &reverse_invoice($dbh, $form);
846   
847   # delete AR record
848   my $query = qq|DELETE FROM ar
849                  WHERE id = $form->{id}|;
850   $dbh->do($query) || $form->dberror($query);
851
852   my $rc = $dbh->commit;
853   $dbh->disconnect;
854   
855   $rc;
856   
857 }
858
859
860
861 sub retrieve_invoice {
862   my ($self, $myconfig, $form) = @_;
863   
864   # connect to database
865   my $dbh = $form->dbconnect_noauto($myconfig);
866
867   my $query;
868   
869   if ($form->{id}) {
870     # get default accounts and last invoice number
871     $query = qq|SELECT (SELECT c.accno FROM chart c
872                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
873                        (SELECT c.accno FROM chart c
874                         WHERE d.income_accno_id = c.id) AS income_accno,
875                        (SELECT c.accno FROM chart c
876                         WHERE d.expense_accno_id = c.id) AS expense_accno,
877                        (SELECT c.accno FROM chart c
878                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
879                        (SELECT c.accno FROM chart c
880                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
881                 d.curr AS currencies
882                 FROM defaults d|;
883   } else {
884     $query = qq|SELECT (SELECT c.accno FROM chart c
885                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
886                        (SELECT c.accno FROM chart c
887                         WHERE d.income_accno_id = c.id) AS income_accno,
888                        (SELECT c.accno FROM chart c
889                         WHERE d.expense_accno_id = c.id) AS expense_accno,
890                        (SELECT c.accno FROM chart c
891                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
892                        (SELECT c.accno FROM chart c
893                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
894                 d.invnumber, d.curr AS currencies, current_date AS invdate
895                 FROM defaults d|;
896   }
897   my $sth = $dbh->prepare($query);
898   $sth->execute || $form->dberror($query);
899
900   my $ref = $sth->fetchrow_hashref(NAME_lc);
901   map { $form->{$_} = $ref->{$_} } keys %$ref;
902   $sth->finish;
903
904   
905   if ($form->{id}) {
906     
907     # retrieve invoice
908     $query = qq|SELECT a.invnumber, a.ordnumber, a.transdate AS invdate, a.paid,
909                 a.shippingpoint, a.terms, a.notes, a.duedate, a.taxincluded,
910                 a.curr AS currency, (SELECT e.name FROM employee e
911                                      WHERE e.id = a.employee_id) AS employee
912                 FROM ar a
913                 WHERE a.id = $form->{id}|;
914     $sth = $dbh->prepare($query);
915     $sth->execute || $form->dberror($query);
916
917     $ref = $sth->fetchrow_hashref(NAME_lc);
918     map { $form->{$_} = $ref->{$_} } keys %$ref;
919     $sth->finish;
920
921     $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "buy");
922
923     # get shipto
924     $query = qq|SELECT * FROM shipto
925                 WHERE trans_id = $form->{id}|;
926     $sth = $dbh->prepare($query);
927     $sth->execute || $form->dberror($query);
928
929     $ref = $sth->fetchrow_hashref(NAME_lc);
930     map { $form->{$_} = $ref->{$_} } keys %$ref;
931     $sth->finish;
932     
933     # retrieve individual items
934     $query = qq|SELECT c1.accno AS inventory_accno,
935                        c2.accno AS income_accno,
936                        c3.accno AS expense_accno,
937                 i.description, i.qty, i.fxsellprice AS sellprice,
938                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
939                 pr.projectnumber,
940                 i.project_id,
941                 p.partnumber, p.assembly, p.bin,
942                 pg.partsgroup
943                 FROM invoice i
944                 JOIN parts p ON (i.parts_id = p.id)
945                 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
946                 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
947                 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
948                 LEFT JOIN project pr ON (i.project_id = pr.id)
949                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
950                 WHERE i.trans_id = $form->{id}
951                 AND NOT i.assemblyitem = '1'
952                 ORDER BY i.id|;
953     $sth = $dbh->prepare($query);
954     $sth->execute || $form->dberror($query);
955
956     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
957       # get taxes
958       $query = qq|SELECT c.accno
959                   FROM chart c, partstax pt
960                   WHERE pt.chart_id = c.id
961                   AND pt.parts_id = $ref->{id}|;
962       my $sth = $dbh->prepare($query);
963       $sth->execute || $form->dberror($query);
964
965       $ref->{taxaccounts} = "";
966       my $taxrate = 0;
967       
968       while (my $ptref = $sth->fetchrow_hashref(NAME_lc)) {
969         $ref->{taxaccounts} .= "$ptref->{accno} ";
970         $taxrate += $form->{"$ptref->{accno}_rate"};
971       }
972       $sth->finish;
973       chop $ref->{taxaccounts};
974
975       push @{ $form->{invoice_details} }, $ref;
976     }
977     $sth->finish;
978
979   } else {
980
981     $form->{shippingpoint} = $myconfig->{shippingpoint} unless $form->{shippingpoint};
982
983     # up invoice number by 1
984     $form->{invnumber}++;
985
986     # save the new number
987     $query = qq|UPDATE defaults
988                 SET invnumber = '$form->{invnumber}'|;
989     $dbh->do($query) || $form->dberror($query);
990
991     $form->get_employee($dbh);
992
993   }
994
995
996   my $rc = $dbh->commit;
997   $dbh->disconnect;
998   
999   $rc;
1000
1001 }
1002
1003
1004 sub get_customer {
1005   my ($self, $myconfig, $form) = @_;
1006   
1007   # connect to database
1008   my $dbh = $form->dbconnect($myconfig);
1009
1010   my $dateformat = $myconfig->{dateformat};
1011   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1012
1013   my $duedate = ($form->{invdate}) ? "to_date('$form->{invdate}', '$dateformat')" : "current_date";
1014
1015   $form->{customer_id} *= 1;
1016   # get customer
1017   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
1018                  c.email, c.cc, c.bcc, c.taxincluded,
1019                  c.addr1, c.addr2, c.addr3, c.addr4,
1020                  $duedate + c.terms AS duedate
1021                  FROM customer c
1022                  WHERE c.id = $form->{customer_id}|;
1023   my $sth = $dbh->prepare($query);
1024   $sth->execute || $form->dberror($query);
1025
1026   $ref = $sth->fetchrow_hashref(NAME_lc);
1027
1028   map { $form->{$_} = $ref->{$_} } keys %$ref;
1029   $sth->finish;
1030   
1031   $form->{creditremaining} = $form->{creditlimit};
1032   $query = qq|SELECT SUM(amount - paid)
1033               FROM ar
1034               WHERE customer_id = $form->{customer_id}|;
1035   $sth = $dbh->prepare($query);
1036   $sth->execute || $form->dberror($query);
1037
1038   ($form->{creditremaining}) -= $sth->fetchrow_array;
1039
1040   $sth->finish;
1041   
1042   $query = qq|SELECT o.amount,
1043                 (SELECT e.buy FROM exchangerate e
1044                  WHERE e.curr = o.curr
1045                  AND e.transdate = o.transdate)
1046               FROM oe o
1047               WHERE o.customer_id = $form->{customer_id}
1048               AND o.closed = '0'|;
1049   $sth = $dbh->prepare($query);
1050   $sth->execute || $form->dberror($query);
1051
1052   while (my ($amount, $exch) = $sth->fetchrow_array) {
1053     $exch = 1 unless $exch;
1054     $form->{creditremaining} -= $amount * $exch;
1055   }
1056   $sth->finish;
1057
1058
1059   # get shipto if we did not converted an order or invoice
1060   if (!$form->{shipto}) {
1061     map { delete $form->{$_} } qw(shiptoname shiptoaddr1 shiptoaddr2 shiptoaddr3 shiptoaddr4 shiptocontact shiptophone shiptofax shiptoemail);
1062
1063     $query = qq|SELECT * FROM shipto
1064                 WHERE trans_id = $form->{customer_id}|;
1065     $sth = $dbh->prepare($query);
1066     $sth->execute || $form->dberror($query);
1067
1068     $ref = $sth->fetchrow_hashref(NAME_lc);
1069     map { $form->{$_} = $ref->{$_} } keys %$ref;
1070     $sth->finish;
1071   }
1072       
1073   # get taxes we charge for this customer
1074   $query = qq|SELECT c.accno
1075               FROM chart c, customertax ct
1076               WHERE ct.chart_id = c.id
1077               AND ct.customer_id = $form->{customer_id}|;
1078   $sth = $dbh->prepare($query);
1079   $sth->execute || $form->dberror($query);
1080   
1081   my $customertax = ();
1082   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1083     $customertax{$ref->{accno}} = 1;
1084   }
1085   $sth->finish;
1086     
1087   # get tax rates and description
1088   $query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
1089               FROM chart c, tax t
1090               WHERE c.id = t.chart_id
1091               AND c.link LIKE '%CT_tax%'
1092               ORDER BY accno|;
1093   $sth = $dbh->prepare($query);
1094   $sth->execute || $form->dberror($query);
1095
1096   $form->{taxaccounts} = "";
1097   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1098     if ($customertax{$ref->{accno}}) {
1099       $form->{"$ref->{accno}_rate"} = $ref->{rate};
1100       $form->{"$ref->{accno}_description"} = $ref->{description};
1101       $form->{"$ref->{accno}_taxnumber"} = $ref->{taxnumber};
1102       $form->{taxaccounts} .= "$ref->{accno} ";
1103     }
1104   }
1105   $sth->finish;
1106   chop $form->{taxaccounts};
1107
1108   # setup last accounts used for this customer
1109   if (!$form->{id} && $form->{type} !~ /_order/) {
1110     $query = qq|SELECT c.accno, c.description, c.link, c.category
1111                 FROM chart c
1112                 JOIN acc_trans ac ON (ac.chart_id = c.id)
1113                 JOIN ar a ON (a.id = ac.trans_id)
1114                 WHERE a.customer_id = $form->{customer_id}
1115                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
1116                 AND a.id IN (SELECT max(id) FROM ar
1117                              WHERE customer_id = $form->{customer_id})|;
1118     $sth = $dbh->prepare($query);
1119     $sth->execute || $form->dberror($query);
1120
1121     my $i = 0;
1122     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1123       if ($ref->{category} eq 'I') {
1124         $i++;
1125         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
1126       }
1127       if ($ref->{category} eq 'A') {
1128         $form->{AR} = $form->{AR_1} = "$ref->{accno}--$ref->{description}";
1129       }
1130     }
1131     $sth->finish;
1132     $form->{rowcount} = $i if ($i && !$form->{type});
1133   }
1134   
1135   $dbh->disconnect;
1136
1137 }
1138
1139
1140
1141 sub retrieve_item {
1142   my ($self, $myconfig, $form) = @_;
1143
1144   my $i = $form->{rowcount};
1145   my $var;
1146   my $where = "NOT obsolete = '1'";
1147
1148   if ($form->{"partnumber_$i"}) {
1149     $var = $form->like(lc $form->{"partnumber_$i"});
1150     $where .= " AND lower(p.partnumber) LIKE '$var'";
1151   }
1152   if ($form->{"description_$i"}) {
1153     $var = $form->like(lc $form->{"description_$i"});
1154     $where .= " AND lower(p.description) LIKE '$var'";
1155   }
1156
1157   if ($form->{"partsgroup_$i"}) {
1158     $var = $form->like(lc $form->{"partsgroup_$i"});
1159     $where .= " AND lower(pg.partsgroup) LIKE '$var'";
1160   }
1161
1162   if ($form->{"description_$i"}) {
1163     $where .= " ORDER BY description";
1164   } else {
1165     $where .= " ORDER BY partnumber";
1166   }
1167   
1168   # connect to database
1169   my $dbh = $form->dbconnect($myconfig);
1170
1171   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1172                         p.listprice,
1173                         c1.accno AS inventory_accno,
1174                         c2.accno AS income_accno,
1175                         c3.accno AS expense_accno,
1176                  p.unit, p.assembly, p.bin, p.onhand, p.makemodel,
1177                  pg.partsgroup
1178                  FROM parts p
1179                  LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
1180                  LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
1181                  LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
1182                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1183                  WHERE $where|;
1184   my $sth = $dbh->prepare($query);
1185   $sth->execute || $form->dberror($query);
1186
1187   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1188
1189     # get taxes for part
1190     $query = qq|SELECT c.accno
1191                 FROM chart c
1192                 JOIN partstax pt ON (c.id = pt.chart_id)
1193                 WHERE pt.parts_id = $ref->{id}|;
1194     my $sth = $dbh->prepare($query);
1195     $sth->execute || $form->dberror($query);
1196
1197     $ref->{taxaccounts} = "";
1198     while (my $ptref = $sth->fetchrow_hashref(NAME_lc)) {
1199       $ref->{taxaccounts} .= "$ptref->{accno} ";
1200     }
1201     $sth->finish;
1202     chop $ref->{taxaccounts};
1203
1204     # get makemodel
1205     if ($ref->{makemodel}) {
1206       $query = qq|SELECT name
1207                   FROM makemodel
1208                   WHERE parts_id = $ref->{id}|;
1209       $sth = $dbh->prepare($query);
1210       $sth->execute || $form->dberror($query);
1211       
1212       $ref->{makemodel} = "";
1213       while (my $ptref = $sth->fetchrow_hashref(NAME_lc)) {
1214         $ref->{makemodel} .= "$ptref->{name}:";
1215       }
1216       $sth->finish;
1217       chop $ref->{makemodel};
1218     }
1219
1220     push @{ $form->{item_list} }, $ref;
1221
1222   }
1223   
1224   $sth->finish;
1225   $dbh->disconnect;
1226   
1227 }
1228
1229
1230 1;
1231