Merge von 788 aus unstable: Bugfix 260
[kivitendo-erp.git] / SL / AR.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Accounts Receivable module backend routines
32 #
33 #======================================================================
34
35 package AR;
36
37 use Data::Dumper;
38
39 sub post_transaction {
40   $main::lxdebug->enter_sub();
41
42   my ($self, $myconfig, $form) = @_;
43
44   my ($null, $taxrate, $amount, $tax, $diff);
45   my $exchangerate = 0;
46   my $i;
47
48   my $dbh = $form->dbconnect_noauto($myconfig);
49
50   if ($form->{currency} eq $form->{defaultcurrency}) {
51     $form->{exchangerate} = 1;
52   } else {
53     $exchangerate =
54       $form->check_exchangerate($myconfig, $form->{currency},
55                                 $form->{transdate}, 'buy');
56   }
57   for $i (1 .. $form->{rowcount}) {
58     $form->{AR_amounts}{"amount_$i"} =
59       (split(/--/, $form->{"AR_amount_$i"}))[0];
60   }
61   ($form->{AR_amounts}{receivables}) = split(/--/, $form->{ARselected});
62   ($form->{AR}{receivables})         = split(/--/, $form->{ARselected});
63
64   $form->{exchangerate} =
65     ($exchangerate)
66     ? $exchangerate
67     : $form->parse_amount($myconfig, $form->{exchangerate});
68
69   for $i (1 .. $form->{rowcount}) {
70
71     $form->{"amount_$i"} =
72       $form->round_amount($form->parse_amount($myconfig, $form->{"amount_$i"})
73                             * $form->{exchangerate},
74                           2);
75
76     $form->{netamount} += $form->{"amount_$i"};
77
78     # parse tax_$i for later
79     $form->{"tax_$i"} = $form->parse_amount($myconfig, $form->{"tax_$i"});
80   }
81
82   # this is for ar
83
84   $form->{amount} = $form->{netamount};
85
86   $form->{tax} = 0;
87   $form->{netamount} = 0;
88   $form->{total_tax} = 0;
89   # taxincluded doesn't make sense if there is no amount
90
91   $form->{taxincluded} = 0 if ($form->{amount} == 0);
92   for $i (1 .. $form->{rowcount}) {
93     ($form->{"taxkey_$i"}, $NULL) = split /--/, $form->{"taxchart_$i"};
94
95     $query =
96       qq| SELECT c.accno, t.rate FROM chart c, tax t where c.id=t.chart_id AND t.taxkey=$form->{"taxkey_$i"}|;
97     $sth = $dbh->prepare($query);
98     $sth->execute || $form->dberror($query);
99     ($form->{AR_amounts}{"tax_$i"}, $form->{"taxrate_$i"}) =
100       $sth->fetchrow_array;
101     $form->{AR_amounts}{"tax_$i"}{taxkey}    = $form->{"taxkey_$i"};
102     $form->{AR_amounts}{"amount_$i"}{taxkey} = $form->{"taxkey_$i"};
103
104     $sth->finish;
105     if (!$form->{"korrektur_$i"}) {
106       if ($form->{taxincluded} *= 1) {
107         $tax =
108           $form->{"amount_$i"} -
109           ($form->{"amount_$i"} / ($form->{"taxrate_$i"} + 1));
110         $amount = $form->{"amount_$i"} - $tax;
111         $form->{"amount_$i"} = $form->round_amount($amount, 2);
112         $diff += $amount - $form->{"amount_$i"};
113         $form->{"tax_$i"} = $form->round_amount($tax, 2);
114         $form->{netamount} += $form->{"amount_$i"};
115       } else {
116         $form->{"tax_$i"} = $form->{"amount_$i"} * $form->{"taxrate_$i"};
117         $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"} * $form->{exchangerate}, 2);
118         $form->{netamount} += $form->{"amount_$i"};
119       }
120     }
121     $form->{total_tax} += $form->{"tax_$i"};
122   }
123
124   # adjust paidaccounts if there is no date in the last row
125   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
126   $form->{paid} = 0;
127
128   # add payments
129   for $i (1 .. $form->{paidaccounts}) {
130     $form->{"paid_$i"} =
131       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
132                           2);
133
134     $form->{paid} += $form->{"paid_$i"};
135     $form->{datepaid} = $form->{"datepaid_$i"};
136
137   }
138
139   $form->{amount} = $form->{netamount} + $form->{total_tax};
140   $form->{paid}   =
141     $form->round_amount($form->{paid} * $form->{exchangerate}, 2);
142
143   my ($query, $sth, $null);
144
145   ($null, $form->{employee_id}) = split /--/, $form->{employee};
146   unless ($form->{employee_id}) {
147     $form->get_employee($dbh);
148   }
149
150   # if we have an id delete old records
151   if ($form->{id}) {
152
153     # delete detail records
154     $query = qq|DELETE FROM acc_trans WHERE trans_id = $form->{id}|;
155     $dbh->do($query) || $form->dberror($query);
156
157   } else {
158     my $uid = rand() . time;
159
160     $uid .= $form->{login};
161
162     $uid = substr($uid, 2, 75);
163
164     $query = qq|INSERT INTO ar (invnumber, employee_id)
165                 VALUES ('$uid', $form->{employee_id})|;
166     $dbh->do($query) || $form->dberror($query);
167
168     $query = qq|SELECT a.id FROM ar a
169                 WHERE a.invnumber = '$uid'|;
170     $sth = $dbh->prepare($query);
171     $sth->execute || $form->dberror($query);
172
173     ($form->{id}) = $sth->fetchrow_array;
174     $sth->finish;
175
176   }
177
178   # update department
179   ($null, $form->{department_id}) = split(/--/, $form->{department});
180   $form->{department_id} *= 1;
181
182   # escape '
183   map { $form->{$_} =~ s/\'/\'\'/g } qw(invnumber ordnumber notes);
184
185   # record last payment date in ar table
186   $form->{datepaid} = $form->{transdate} unless $form->{datepaid};
187   my $datepaid = ($form->{paid} != 0) ? qq|'$form->{datepaid}'| : 'NULL';
188
189   $query = qq|UPDATE ar set
190               invnumber = '$form->{invnumber}',
191               ordnumber = '$form->{ordnumber}',
192               transdate = '$form->{transdate}',
193               customer_id = $form->{customer_id},
194               taxincluded = '$form->{taxincluded}',
195               amount = $form->{amount},
196               duedate = '$form->{duedate}',
197               paid = $form->{paid},
198               datepaid = $datepaid,
199               netamount = $form->{netamount},
200               curr = '$form->{currency}',
201               notes = '$form->{notes}',
202               department_id = $form->{department_id},
203               employee_id = $form->{employee_id}
204               WHERE id = $form->{id}|;
205   $dbh->do($query) || $form->dberror($query);
206
207   # amount for AR account
208   $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
209
210   # update exchangerate
211   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
212     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
213                                $form->{exchangerate}, 0);
214   }
215
216   # add individual transactions for AR, amount and taxes
217   for $i (1 .. $form->{rowcount}) {
218     if ($form->{"amount_$i"} != 0) {
219       $project_id = 'NULL';
220       if ("amount_$i" =~ /amount_/) {
221         if ($form->{"project_id_$i"} && $form->{"projectnumber_$i"}) {
222           $project_id = $form->{"project_id_$i"};
223         }
224       }
225       if ("amount_$i" =~ /amount/) {
226         $taxkey = $form->{AR_amounts}{"amount_$i"}{taxkey};
227       }
228
229       # insert detail records in acc_trans
230       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
231                                          project_id, taxkey)
232                   VALUES ($form->{id}, (SELECT c.id FROM chart c
233                                         WHERE c.accno = '$form->{AR_amounts}{"amount_$i"}'),
234                   $form->{"amount_$i"}, '$form->{transdate}', $project_id, '$taxkey')|;
235       $dbh->do($query) || $form->dberror($query);
236       if ($form->{"tax_$i"} != 0) {
237
238         # insert detail records in acc_trans
239         $query =
240           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
241                                           project_id, taxkey)
242                     VALUES ($form->{id}, (SELECT c.id FROM chart c
243                                           WHERE c.accno = '$form->{AR_amounts}{"tax_$i"}'),
244                     $form->{"tax_$i"}, '$form->{transdate}', $project_id, '$taxkey')|;
245         $dbh->do($query) || $form->dberror($query);
246       }
247     }
248   }
249
250   # add recievables
251   $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
252                                       project_id)
253               VALUES ($form->{id}, (SELECT c.id FROM chart c
254                                     WHERE c.accno = '$form->{AR_amounts}{receivables}'),
255               $form->{receivables}, '$form->{transdate}', $project_id)|;
256   $dbh->do($query) || $form->dberror($query);
257
258   # add paid transactions
259   for my $i (1 .. $form->{paidaccounts}) {
260     if ($form->{"paid_$i"} != 0) {
261
262       $form->{"AR_paid_$i"} =~ s/\"//g;
263       ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
264       $form->{"datepaid_$i"} = $form->{transdate}
265         unless ($form->{"datepaid_$i"});
266
267       $exchangerate = 0;
268       if ($form->{currency} eq $form->{defaultcurrency}) {
269         $form->{"exchangerate_$i"} = 1;
270       } else {
271         $exchangerate =
272           $form->check_exchangerate($myconfig, $form->{currency},
273                                     $form->{"datepaid_$i"}, 'buy');
274
275         $form->{"exchangerate_$i"} =
276           ($exchangerate)
277           ? $exchangerate
278           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
279       }
280
281       # if there is no amount and invtotal is zero there is no exchangerate
282       if ($form->{amount} == 0 && $form->{netamount} == 0) {
283         $form->{exchangerate} = $form->{"exchangerate_$i"};
284       }
285
286       # receivables amount
287       $amount =
288         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
289
290       if ($form->{receivables} != 0) {
291
292         # add receivable
293         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
294                     transdate)
295                     VALUES ($form->{id},
296                            (SELECT c.id FROM chart c
297                             WHERE c.accno = '$form->{AR}{receivables}'),
298                     $amount, '$form->{"datepaid_$i"}')|;
299         $dbh->do($query) || $form->dberror($query);
300       }
301       $form->{receivables} = $amount;
302
303       $form->{"memo_$i"} =~ s/\'/\'\'/g;
304
305       if ($form->{"paid_$i"} != 0) {
306
307         # add payment
308         $amount = $form->{"paid_$i"} * -1;
309         $query  = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
310                     transdate, source, memo)
311                     VALUES ($form->{id},
312                            (SELECT c.id FROM chart c
313                             WHERE c.accno = '$form->{AR}{"paid_$i"}'),
314                     $amount, '$form->{"datepaid_$i"}',
315                     '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
316         $dbh->do($query) || $form->dberror($query);
317
318         # exchangerate difference for payment
319         $amount =
320           $form->round_amount(
321                     $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1,
322                     2);
323
324         if ($amount != 0) {
325           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
326                       transdate, fx_transaction, cleared)
327                       VALUES ($form->{id},
328                              (SELECT c.id FROM chart c
329                               WHERE c.accno = '$form->{AR}{"paid_$i"}'),
330                       $amount, '$form->{"datepaid_$i"}', '1', '0')|;
331           $dbh->do($query) || $form->dberror($query);
332         }
333
334         # exchangerate gain/loss
335         $amount =
336           $form->round_amount(
337                    $form->{"paid_$i"} *
338                      ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1,
339                    2);
340
341         if ($amount != 0) {
342           $accno =
343             ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
344           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
345                       transdate, fx_transaction, cleared)
346                       VALUES ($form->{id}, (SELECT c.id FROM chart c
347                                             WHERE c.accno = '$accno'),
348                       $amount, '$form->{"datepaid_$i"}', '1', '0')|;
349           $dbh->do($query) || $form->dberror($query);
350         }
351       }
352
353       # update exchangerate record
354       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
355         $form->update_exchangerate($dbh, $form->{currency},
356                                    $form->{"datepaid_$i"},
357                                    $form->{"exchangerate_$i"}, 0);
358       }
359     }
360   }
361
362   my $rc = $dbh->commit;
363   $dbh->disconnect;
364
365   $main::lxdebug->leave_sub();
366
367   return $rc;
368 }
369
370 sub delete_transaction {
371   $main::lxdebug->enter_sub();
372
373   my ($self, $myconfig, $form) = @_;
374
375   # connect to database, turn AutoCommit off
376   my $dbh = $form->dbconnect_noauto($myconfig);
377
378   my $query = qq|DELETE FROM ar WHERE id = $form->{id}|;
379   $dbh->do($query) || $form->dberror($query);
380
381   $query = qq|DELETE FROM acc_trans WHERE trans_id = $form->{id}|;
382   $dbh->do($query) || $form->dberror($query);
383
384   # commit
385   my $rc = $dbh->commit;
386   $dbh->disconnect;
387
388   $main::lxdebug->leave_sub();
389
390   return $rc;
391 }
392
393 sub ar_transactions {
394   $main::lxdebug->enter_sub();
395
396   my ($self, $myconfig, $form) = @_;
397
398   # connect to database
399   my $dbh = $form->dbconnect($myconfig);
400
401   my $query = qq|SELECT a.id, a.invnumber, a.ordnumber, a.transdate,
402                  a.duedate, a.netamount, a.amount, a.paid, c.name,
403                  a.invoice, a.datepaid, a.terms, a.notes, a.shipvia,
404                  a.shippingpoint,
405                  e.name AS employee
406                  FROM ar a
407               JOIN customer c ON (a.customer_id = c.id)
408               LEFT JOIN employee e ON (a.employee_id = e.id)|;
409
410   my $where = "1 = 1";
411   if ($form->{customer_id}) {
412     $where .= " AND a.customer_id = $form->{customer_id}";
413   } else {
414     if ($form->{customer}) {
415       my $customer = $form->like(lc $form->{customer});
416       $where .= " AND lower(c.name) LIKE '$customer'";
417     }
418   }
419   if ($form->{department}) {
420     my ($null, $department_id) = split /--/, $form->{department};
421     $where .= " AND a.department_id = $department_id";
422   }
423   if ($form->{invnumber}) {
424     my $invnumber = $form->like(lc $form->{invnumber});
425     $where .= " AND lower(a.invnumber) LIKE '$invnumber'";
426   }
427   if ($form->{ordnumber}) {
428     my $ordnumber = $form->like(lc $form->{ordnumber});
429     $where .= " AND lower(a.ordnumber) LIKE '$ordnumber'";
430   }
431   if ($form->{notes}) {
432     my $notes = $form->like(lc $form->{notes});
433     $where .= " AND lower(a.notes) LIKE '$notes'";
434   }
435
436   $where .= " AND a.transdate >= '$form->{transdatefrom}'"
437     if $form->{transdatefrom};
438   $where .= " AND a.transdate <= '$form->{transdateto}'"
439     if $form->{transdateto};
440   if ($form->{open} || $form->{closed}) {
441     unless ($form->{open} && $form->{closed}) {
442       $where .= " AND a.amount <> a.paid" if ($form->{open});
443       $where .= " AND a.amount = a.paid"  if ($form->{closed});
444     }
445   }
446
447   my @a = (transdate, invnumber, name);
448   push @a, "employee" if $form->{l_employee};
449   my $sortorder = join ', ', $form->sort_columns(@a);
450   $sortorder = $form->{sort} if $form->{sort};
451
452   $query .= "WHERE $where
453              ORDER by $sortorder";
454
455   my $sth = $dbh->prepare($query);
456   $sth->execute || $form->dberror($query);
457
458   while (my $ar = $sth->fetchrow_hashref(NAME_lc)) {
459     push @{ $form->{AR} }, $ar;
460   }
461
462   $sth->finish;
463   $dbh->disconnect;
464
465   $main::lxdebug->leave_sub();
466 }
467
468 1;
469