Merge von 765,768 aus unstable: Bugfix 242 Punkt 3/4
[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
88   # taxincluded doesn't make sense if there is no amount
89
90   $form->{taxincluded} = 0 if ($form->{amount} == 0);
91   for $i (1 .. $form->{rowcount}) {
92     ($form->{"taxkey_$i"}, $NULL) = split /--/, $form->{"taxchart_$i"};
93
94     $query =
95       qq| SELECT c.accno, t.rate FROM chart c, tax t where c.id=t.chart_id AND t.taxkey=$form->{"taxkey_$i"}|;
96     $sth = $dbh->prepare($query);
97     $sth->execute || $form->dberror($query);
98     ($form->{AR_amounts}{"tax_$i"}, $form->{"taxrate_$i"}) =
99       $sth->fetchrow_array;
100     $form->{AR_amounts}{"tax_$i"}{taxkey}    = $form->{"taxkey_$i"};
101     $form->{AR_amounts}{"amount_$i"}{taxkey} = $form->{"taxkey_$i"};
102
103     $sth->finish;
104     if (!$form->{"korrektur_$i"}) {
105       if ($form->{taxincluded} *= 1) {
106         $tax =
107           $form->{"amount_$i"} -
108           ($form->{"amount_$i"} / ($form->{"taxrate_$i"} + 1));
109         $amount = $form->{"amount_$i"} - $tax;
110         $form->{"amount_$i"} = $form->round_amount($amount, 2);
111         $diff += $amount - $form->{"amount_$i"};
112         $form->{"tax_$i"} = $form->round_amount($tax, 2);
113         $form->{netamount} += $form->{"amount_$i"};
114       } else {
115         $form->{"tax_$i"} = $form->{"amount_$i"} * $form->{"taxrate_$i"};
116         $form->{"tax_$i"} =
117           $form->round_amount($form->{"tax_$i"} * $form->{exchangerate}, 2);
118       }
119     }
120     $form->{total_tax} += $form->{"tax_$i"};
121   }
122
123   # adjust paidaccounts if there is no date in the last row
124   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
125   $form->{paid} = 0;
126
127   # add payments
128   for $i (1 .. $form->{paidaccounts}) {
129     $form->{"paid_$i"} =
130       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
131                           2);
132
133     $form->{paid} += $form->{"paid_$i"};
134     $form->{datepaid} = $form->{"datepaid_$i"};
135
136   }
137
138   $form->{amount} = $form->{netamount} + $form->{total_tax};
139   $form->{paid}   =
140     $form->round_amount($form->{paid} * $form->{exchangerate}, 2);
141
142   my ($query, $sth, $null);
143
144   ($null, $form->{employee_id}) = split /--/, $form->{employee};
145   unless ($form->{employee_id}) {
146     $form->get_employee($dbh);
147   }
148
149   # if we have an id delete old records
150   if ($form->{id}) {
151
152     # delete detail records
153     $query = qq|DELETE FROM acc_trans WHERE trans_id = $form->{id}|;
154     $dbh->do($query) || $form->dberror($query);
155
156   } else {
157     my $uid = rand() . time;
158
159     $uid .= $form->{login};
160
161     $uid = substr($uid, 2, 75);
162
163     $query = qq|INSERT INTO ar (invnumber, employee_id)
164                 VALUES ('$uid', $form->{employee_id})|;
165     $dbh->do($query) || $form->dberror($query);
166
167     $query = qq|SELECT a.id FROM ar a
168                 WHERE a.invnumber = '$uid'|;
169     $sth = $dbh->prepare($query);
170     $sth->execute || $form->dberror($query);
171
172     ($form->{id}) = $sth->fetchrow_array;
173     $sth->finish;
174
175   }
176
177   # update department
178   ($null, $form->{department_id}) = split(/--/, $form->{department});
179   $form->{department_id} *= 1;
180
181   # escape '
182   map { $form->{$_} =~ s/\'/\'\'/g } qw(invnumber ordnumber notes);
183
184   # record last payment date in ar table
185   $form->{datepaid} = $form->{transdate} unless $form->{datepaid};
186   my $datepaid = ($form->{paid} != 0) ? qq|'$form->{datepaid}'| : 'NULL';
187
188   $query = qq|UPDATE ar set
189               invnumber = '$form->{invnumber}',
190               ordnumber = '$form->{ordnumber}',
191               transdate = '$form->{transdate}',
192               customer_id = $form->{customer_id},
193               taxincluded = '$form->{taxincluded}',
194               amount = $form->{amount},
195               duedate = '$form->{duedate}',
196               paid = $form->{paid},
197               datepaid = $datepaid,
198               netamount = $form->{netamount},
199               curr = '$form->{currency}',
200               notes = '$form->{notes}',
201               department_id = $form->{department_id},
202               employee_id = $form->{employee_id}
203               WHERE id = $form->{id}|;
204   $dbh->do($query) || $form->dberror($query);
205
206   # amount for AR account
207   $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
208
209   # update exchangerate
210   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
211     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
212                                $form->{exchangerate}, 0);
213   }
214
215   # add individual transactions for AR, amount and taxes
216   for $i (1 .. $form->{rowcount}) {
217     if ($form->{"amount_$i"} != 0) {
218       $project_id = 'NULL';
219       if ("amount_$i" =~ /amount_/) {
220         if ($form->{"project_id_$i"} && $form->{"projectnumber_$i"}) {
221           $project_id = $form->{"project_id_$i"};
222         }
223       }
224       if ("amount_$i" =~ /amount/) {
225         $taxkey = $form->{AR_amounts}{"amount_$i"}{taxkey};
226       }
227
228       # insert detail records in acc_trans
229       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
230                                          project_id, taxkey)
231                   VALUES ($form->{id}, (SELECT c.id FROM chart c
232                                         WHERE c.accno = '$form->{AR_amounts}{"amount_$i"}'),
233                   $form->{"amount_$i"}, '$form->{transdate}', $project_id, '$taxkey')|;
234       $dbh->do($query) || $form->dberror($query);
235       if ($form->{"tax_$i"} != 0) {
236
237         # insert detail records in acc_trans
238         $query =
239           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
240                                           project_id, taxkey)
241                     VALUES ($form->{id}, (SELECT c.id FROM chart c
242                                           WHERE c.accno = '$form->{AR_amounts}{"tax_$i"}'),
243                     $form->{"tax_$i"}, '$form->{transdate}', $project_id, '$taxkey')|;
244         $dbh->do($query) || $form->dberror($query);
245       }
246     }
247   }
248
249   # add recievables
250   $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
251                                       project_id)
252               VALUES ($form->{id}, (SELECT c.id FROM chart c
253                                     WHERE c.accno = '$form->{AR_amounts}{receivables}'),
254               $form->{receivables}, '$form->{transdate}', $project_id)|;
255   $dbh->do($query) || $form->dberror($query);
256
257   # add paid transactions
258   for my $i (1 .. $form->{paidaccounts}) {
259     if ($form->{"paid_$i"} != 0) {
260
261       $form->{"AR_paid_$i"} =~ s/\"//g;
262       ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
263       $form->{"datepaid_$i"} = $form->{transdate}
264         unless ($form->{"datepaid_$i"});
265
266       $exchangerate = 0;
267       if ($form->{currency} eq $form->{defaultcurrency}) {
268         $form->{"exchangerate_$i"} = 1;
269       } else {
270         $exchangerate =
271           $form->check_exchangerate($myconfig, $form->{currency},
272                                     $form->{"datepaid_$i"}, 'buy');
273
274         $form->{"exchangerate_$i"} =
275           ($exchangerate)
276           ? $exchangerate
277           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
278       }
279
280       # if there is no amount and invtotal is zero there is no exchangerate
281       if ($form->{amount} == 0 && $form->{netamount} == 0) {
282         $form->{exchangerate} = $form->{"exchangerate_$i"};
283       }
284
285       # receivables amount
286       $amount =
287         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
288
289       if ($form->{receivables} != 0) {
290
291         # add receivable
292         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
293                     transdate)
294                     VALUES ($form->{id},
295                            (SELECT c.id FROM chart c
296                             WHERE c.accno = '$form->{AR}{receivables}'),
297                     $amount, '$form->{"datepaid_$i"}')|;
298         $dbh->do($query) || $form->dberror($query);
299       }
300       $form->{receivables} = $amount;
301
302       $form->{"memo_$i"} =~ s/\'/\'\'/g;
303
304       if ($form->{"paid_$i"} != 0) {
305
306         # add payment
307         $amount = $form->{"paid_$i"} * -1;
308         $query  = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
309                     transdate, source, memo)
310                     VALUES ($form->{id},
311                            (SELECT c.id FROM chart c
312                             WHERE c.accno = '$form->{AR}{"paid_$i"}'),
313                     $amount, '$form->{"datepaid_$i"}',
314                     '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
315         $dbh->do($query) || $form->dberror($query);
316
317         # exchangerate difference for payment
318         $amount =
319           $form->round_amount(
320                     $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1,
321                     2);
322
323         if ($amount != 0) {
324           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
325                       transdate, fx_transaction, cleared)
326                       VALUES ($form->{id},
327                              (SELECT c.id FROM chart c
328                               WHERE c.accno = '$form->{AR}{"paid_$i"}'),
329                       $amount, '$form->{"datepaid_$i"}', '1', '0')|;
330           $dbh->do($query) || $form->dberror($query);
331         }
332
333         # exchangerate gain/loss
334         $amount =
335           $form->round_amount(
336                    $form->{"paid_$i"} *
337                      ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1,
338                    2);
339
340         if ($amount != 0) {
341           $accno =
342             ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
343           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
344                       transdate, fx_transaction, cleared)
345                       VALUES ($form->{id}, (SELECT c.id FROM chart c
346                                             WHERE c.accno = '$accno'),
347                       $amount, '$form->{"datepaid_$i"}', '1', '0')|;
348           $dbh->do($query) || $form->dberror($query);
349         }
350       }
351
352       # update exchangerate record
353       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
354         $form->update_exchangerate($dbh, $form->{currency},
355                                    $form->{"datepaid_$i"},
356                                    $form->{"exchangerate_$i"}, 0);
357       }
358     }
359   }
360
361   my $rc = $dbh->commit;
362   $dbh->disconnect;
363
364   $main::lxdebug->leave_sub();
365
366   return $rc;
367 }
368
369 sub delete_transaction {
370   $main::lxdebug->enter_sub();
371
372   my ($self, $myconfig, $form) = @_;
373
374   # connect to database, turn AutoCommit off
375   my $dbh = $form->dbconnect_noauto($myconfig);
376
377   my $query = qq|DELETE FROM ar WHERE id = $form->{id}|;
378   $dbh->do($query) || $form->dberror($query);
379
380   $query = qq|DELETE FROM acc_trans WHERE trans_id = $form->{id}|;
381   $dbh->do($query) || $form->dberror($query);
382
383   # commit
384   my $rc = $dbh->commit;
385   $dbh->disconnect;
386
387   $main::lxdebug->leave_sub();
388
389   return $rc;
390 }
391
392 sub ar_transactions {
393   $main::lxdebug->enter_sub();
394
395   my ($self, $myconfig, $form) = @_;
396
397   # connect to database
398   my $dbh = $form->dbconnect($myconfig);
399
400   my $query = qq|SELECT a.id, a.invnumber, a.ordnumber, a.transdate,
401                  a.duedate, a.netamount, a.amount, a.paid, c.name,
402                  a.invoice, a.datepaid, a.terms, a.notes, a.shipvia,
403                  a.shippingpoint,
404                  e.name AS employee
405                  FROM ar a
406               JOIN customer c ON (a.customer_id = c.id)
407               LEFT JOIN employee e ON (a.employee_id = e.id)|;
408
409   my $where = "1 = 1";
410   if ($form->{customer_id}) {
411     $where .= " AND a.customer_id = $form->{customer_id}";
412   } else {
413     if ($form->{customer}) {
414       my $customer = $form->like(lc $form->{customer});
415       $where .= " AND lower(c.name) LIKE '$customer'";
416     }
417   }
418   if ($form->{department}) {
419     my ($null, $department_id) = split /--/, $form->{department};
420     $where .= " AND a.department_id = $department_id";
421   }
422   if ($form->{invnumber}) {
423     my $invnumber = $form->like(lc $form->{invnumber});
424     $where .= " AND lower(a.invnumber) LIKE '$invnumber'";
425   }
426   if ($form->{ordnumber}) {
427     my $ordnumber = $form->like(lc $form->{ordnumber});
428     $where .= " AND lower(a.ordnumber) LIKE '$ordnumber'";
429   }
430   if ($form->{notes}) {
431     my $notes = $form->like(lc $form->{notes});
432     $where .= " AND lower(a.notes) LIKE '$notes'";
433   }
434
435   $where .= " AND a.transdate >= '$form->{transdatefrom}'"
436     if $form->{transdatefrom};
437   $where .= " AND a.transdate <= '$form->{transdateto}'"
438     if $form->{transdateto};
439   if ($form->{open} || $form->{closed}) {
440     unless ($form->{open} && $form->{closed}) {
441       $where .= " AND a.amount <> a.paid" if ($form->{open});
442       $where .= " AND a.amount = a.paid"  if ($form->{closed});
443     }
444   }
445
446   my @a = (transdate, invnumber, name);
447   push @a, "employee" if $form->{l_employee};
448   my $sortorder = join ', ', $form->sort_columns(@a);
449   $sortorder = $form->{sort} if $form->{sort};
450
451   $query .= "WHERE $where
452              ORDER by $sortorder";
453
454   my $sth = $dbh->prepare($query);
455   $sth->execute || $form->dberror($query);
456
457   while (my $ar = $sth->fetchrow_hashref(NAME_lc)) {
458     push @{ $form->{AR} }, $ar;
459   }
460
461   $sth->finish;
462   $dbh->disconnect;
463
464   $main::lxdebug->leave_sub();
465 }
466
467 1;
468