Sortieren nach Vorgangsbezeichnung ermöglichen. Fix für Bug 749.
[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 use SL::DBUtils;
39 use SL::MoreCommon;
40
41 our (%myconfig, $form);
42
43 sub post_transaction {
44   $main::lxdebug->enter_sub();
45
46   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
47
48   my ($query, $sth, $null, $taxrate, $amount, $tax);
49   my $exchangerate = 0;
50   my $i;
51
52   my @values;
53
54   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
55   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
56
57   # set exchangerate
58   $form->{exchangerate} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
59       ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy') ||
60         $form->parse_amount($myconfig, $form->{exchangerate}) );
61
62   # get the charts selected
63   map { ($form->{AR_amounts}{"amount_$_"}) = split /--/, $form->{"AR_amount_$_"} } 1 .. $form->{rowcount};
64
65   $form->{AR_amounts}{receivables} = $form->{ARselected};
66   $form->{AR}{receivables}         = $form->{ARselected};
67
68   # parsing
69   for $i (1 .. $form->{rowcount}) {
70     $form->{"amount_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"amount_$i"}) * $form->{exchangerate}, 2);
71     $form->{amount}     += $form->{"amount_$i"};
72     $form->{"tax_$i"}    = $form->parse_amount($myconfig, $form->{"tax_$i"});
73   }
74
75   # this is for ar
76   $form->{tax}       = 0;
77   $form->{netamount} = 0;
78   $form->{total_tax} = 0;
79
80   # taxincluded doesn't make sense if there is no amount
81   $form->{taxincluded} = 0 unless $form->{amount};
82
83   for $i (1 .. $form->{rowcount}) {
84     ($form->{"tax_id_$i"}) = split /--/, $form->{"taxchart_$i"};
85
86     $query = qq|SELECT c.accno, t.taxkey, t.rate FROM tax t LEFT JOIN chart c ON (c.id = t.chart_id) WHERE t.id = ? ORDER BY c.accno|;
87     ($form->{AR_amounts}{"tax_$i"}, $form->{"taxkey_$i"}, $form->{"taxrate_$i"}) = selectrow_query($form, $dbh, $query, $form->{"tax_id_$i"});
88
89     $form->{AR_amounts}{"tax_$i"}{taxkey}     = $form->{"taxkey_$i"};
90     $form->{AR_amounts}{"amounts_$i"}{taxkey} = $form->{"taxkey_$i"};
91
92     if ($form->{taxincluded} *= 1) {
93       $tax = $form->{"korrektur_$i"}
94         ? $form->{"tax_$i"}
95         : $form->{"amount_$i"} - ($form->{"amount_$i"} / ($form->{"taxrate_$i"} + 1)); # should be same as taxrate * amount / (taxrate + 1)
96       $form->{"amount_$i"} = $form->round_amount($form->{"amount_$i"} - $tax, 2);
97       $form->{"tax_$i"}    = $form->round_amount($tax, 2);
98     } else {
99       $form->{"tax_$i"}    = $form->{"amount_$i"} * $form->{"taxrate_$i"} unless $form->{"korrektur_$i"};
100       $form->{"tax_$i"}    = $form->round_amount($form->{"tax_$i"} * $form->{exchangerate}, 2);
101     }
102     $form->{netamount}  += $form->{"amount_$i"};
103     $form->{total_tax}  += $form->{"tax_$i"};
104   }
105
106   # adjust paidaccounts if there is no date in the last row
107   # this does not apply to stornos, where the paid field is set manually
108   unless ($form->{storno}) {
109     $form->{paidaccounts}-- unless $form->{"datepaid_$form->{paidaccounts}"};
110     $form->{paid} = 0;
111
112     # add payments
113     for $i (1 .. $form->{paidaccounts}) {
114       $form->{"paid_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}), 2);
115       $form->{paid}     += $form->{"paid_$i"};
116       $form->{datepaid}  = $form->{"datepaid_$i"};
117     }
118
119     $form->{amount} = $form->{netamount} + $form->{total_tax};
120   }
121   $form->{paid}   = $form->round_amount($form->{paid} * ($form->{exchangerate} || 1), 2);
122
123   ($null, $form->{employee_id}) = split /--/, $form->{employee};
124
125   $form->get_employee($dbh) unless $form->{employee_id};
126
127   # if we have an id delete old records else make one
128   if (!$payments_only) {
129     if ($form->{id}) {
130       # delete detail records
131       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
132       do_query($form, $dbh, $query, $form->{id});
133
134     } else {
135       $query = qq|SELECT nextval('glid')|;
136       ($form->{id}) = selectrow_query($form, $dbh, $query);
137       $query = qq|INSERT INTO ar (id, invnumber, employee_id) VALUES (?, 'dummy', ?)|;
138       do_query($form, $dbh, $query, $form->{id}, $form->{employee_id});
139       $form->{invnumber} = $form->update_defaults($myconfig, "invnumber", $dbh) unless $form->{invnumber};
140     }
141   }
142
143   # update department
144   ($null, $form->{department_id}) = split(/--/, $form->{department});
145   $form->{department_id} *= 1;
146
147   # record last payment date in ar table
148   $form->{datepaid} ||= $form->{transdate} ;
149   my $datepaid = ($form->{paid} != 0) ? $form->{datepaid} : undef;
150
151   # amount for AR account
152   $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
153
154   # update exchangerate
155   $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0)
156     if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
157
158   if (!$payments_only) {
159     $query =
160       qq|UPDATE ar set
161            invnumber = ?, ordnumber = ?, transdate = ?, customer_id = ?,
162            taxincluded = ?, amount = ?, duedate = ?, paid = ?, datepaid = ?,
163            netamount = ?, curr = ?, notes = ?, department_id = ?,
164            employee_id = ?, storno = ?, storno_id = ?
165          WHERE id = ?|;
166     my @values = ($form->{invnumber}, $form->{ordnumber}, conv_date($form->{transdate}), conv_i($form->{customer_id}), $form->{taxincluded} ? 't' : 'f', $form->{amount},
167                   conv_date($form->{duedate}), $form->{paid}, conv_date($datepaid), $form->{netamount}, $form->{currency}, $form->{notes}, conv_i($form->{department_id}),
168                   conv_i($form->{employee_id}), $form->{storno} ? 't' : 'f', $form->{storno_id}, conv_i($form->{id}));
169     do_query($form, $dbh, $query, @values);
170
171     # add individual transactions for AR, amount and taxes
172     for $i (1 .. $form->{rowcount}) {
173       if ($form->{"amount_$i"} != 0) {
174         my $project_id = conv_i($form->{"project_id_$i"});
175         $taxkey = $form->{AR_amounts}{"amounts_$i"}{taxkey};
176
177         # insert detail records in acc_trans
178         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey)
179                      VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?)|;
180         @values = (conv_i($form->{id}), conv_i($form->{AR_amounts}{"amount_$i"}), conv_i($form->{"amount_$i"}), conv_date($form->{transdate}), $project_id, conv_i($taxkey));
181         do_query($form, $dbh, $query, @values);
182
183         if ($form->{"tax_$i"} != 0) {
184           # insert detail records in acc_trans
185           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey)
186                        VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?)|;
187           @values = (conv_i($form->{id}), conv_i($form->{AR_amounts}{"tax_$i"}), conv_i($form->{"tax_$i"}), conv_date($form->{transdate}), $project_id, conv_i($taxkey));
188           do_query($form, $dbh, $query, @values);
189         }
190       }
191     }
192
193     # add recievables
194     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey)
195                  VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
196     @values = (conv_i($form->{id}), $form->{AR_amounts}{receivables}, conv_i($form->{receivables}), conv_date($form->{transdate}), $form->{AR_amounts}{receivables});
197     do_query($form, $dbh, $query, @values);
198   }
199
200   # add paid transactions
201   for my $i (1 .. $form->{paidaccounts}) {
202     if ($form->{"paid_$i"} != 0) {
203       my $project_id = conv_i($form->{"paid_project_id_$i"});
204
205       $form->{"AR_paid_$i"} =~ s/\"//g;
206       ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
207       $form->{"datepaid_$i"} = $form->{transdate}
208         unless ($form->{"datepaid_$i"});
209
210       $form->{"exchangerate_$i"} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
211         ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy') ||
212           $form->parse_amount($myconfig, $form->{"exchangerate_$i"}) );
213
214       # if there is no amount and invtotal is zero there is no exchangerate
215       $form->{exchangerate} = $form->{"exchangerate_$i"}
216         if ($form->{amount} == 0 && $form->{netamount} == 0);
217
218       # receivables amount
219       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
220
221       if ($amount != 0) {
222         # add receivable
223         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey)
224                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
225         @values = (conv_i($form->{id}), $form->{AR}{receivables}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{receivables});
226         do_query($form, $dbh, $query, @values);
227       }
228
229       if ($form->{"paid_$i"} != 0) {
230         my $project_id = conv_i($form->{"paid_project_id_$i"});
231         # add payment
232         $amount = $form->{"paid_$i"} * -1;
233         $query  = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, project_id, taxkey)
234                      VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
235         @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $form->{AR}{"paid_$i"});
236         do_query($form, $dbh, $query, @values);
237
238         # exchangerate difference for payment
239         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1, 2);
240
241         if ($amount != 0) {
242           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey)
243                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
244           @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{"paid_$i"});
245           do_query($form, $dbh, $query, @values);
246         }
247
248         # exchangerate gain/loss
249         $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1, 2);
250
251         if ($amount != 0) {
252           $accno = ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
253           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey)
254                        VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
255           @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $accno);
256           do_query($form, $dbh, $query, @values);
257         }
258       }
259
260       # update exchangerate record
261       $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0)
262         if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
263     }
264   }
265
266   my $rc = 1;
267   if (!$provided_dbh) {
268     $rc = $dbh->commit();
269     $dbh->disconnect();
270   }
271
272   $main::lxdebug->leave_sub() and return $rc;
273 }
274
275 sub _delete_payments {
276   $main::lxdebug->enter_sub();
277
278   my ($self, $form, $dbh) = @_;
279
280   my @delete_oids;
281
282   # Delete old payment entries from acc_trans.
283   my $query =
284     qq|SELECT oid
285        FROM acc_trans
286        WHERE (trans_id = ?) AND fx_transaction
287
288        UNION
289
290        SELECT at.oid
291        FROM acc_trans at
292        LEFT JOIN chart c ON (at.chart_id = c.id)
293        WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
294   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
295
296   $query =
297     qq|SELECT at.oid
298        FROM acc_trans at
299        LEFT JOIN chart c ON (at.chart_id = c.id)
300        WHERE (trans_id = ?)
301          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
302        ORDER BY at.oid
303        OFFSET 1|;
304   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
305
306   if (@delete_oids) {
307     $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
308     do_query($form, $dbh, $query);
309   }
310
311   $main::lxdebug->leave_sub();
312 }
313
314 sub post_payment {
315   $main::lxdebug->enter_sub();
316
317   my ($self, $myconfig, $form, $locale) = @_;
318
319   # connect to database, turn off autocommit
320   my $dbh = $form->dbconnect_noauto($myconfig);
321
322   my (%payments, $old_form, $row, $item, $query, %keep_vars);
323
324   $old_form = save_form();
325
326   # Delete all entries in acc_trans from prior payments.
327   $self->_delete_payments($form, $dbh);
328
329   # Save the new payments the user made before cleaning up $form.
330   my $payments_re = '^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AR_paid_\d+$|^paidaccounts$';
331   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
332
333   # Clean up $form so that old content won't tamper the results.
334   %keep_vars = map { $_, 1 } qw(login password id);
335   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
336
337   # Retrieve the invoice from the database.
338   $form->create_links('AR', $myconfig, 'customer', $dbh);
339
340   # Restore the payment options from the user input.
341   map { $form->{$_} = $payments{$_} } keys %payments;
342
343   # Set up the content of $form in the way that AR::post_transaction() expects.
344
345   $self->setup_form($form);
346
347   ($form->{defaultcurrency}) = selectrow_query($form, $dbh, qq|SELECT curr FROM defaults|);
348   $form->{defaultcurrency}   = (split m/:/, $form->{defaultcurrency})[0];
349
350   $form->{exchangerate}      = $form->format_amount($myconfig, $form->{exchangerate});
351
352   # Get the AR accno (which is normally done by Form::create_links()).
353   $query =
354     qq|SELECT c.accno
355        FROM acc_trans at
356        LEFT JOIN chart c ON (at.chart_id = c.id)
357        WHERE (trans_id = ?)
358          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
359        ORDER BY at.oid
360        LIMIT 1|;
361
362   ($form->{ARselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
363
364   # Post the new payments.
365   $self->post_transaction($myconfig, $form, $dbh, 1);
366
367   restore_form($old_form);
368
369   my $rc = $dbh->commit();
370   $dbh->disconnect();
371
372   $main::lxdebug->leave_sub();
373
374   return $rc;
375 }
376
377 sub delete_transaction {
378   $main::lxdebug->enter_sub();
379
380   my ($self, $myconfig, $form) = @_;
381
382   # connect to database, turn AutoCommit off
383   my $dbh = $form->dbconnect_noauto($myconfig);
384
385   my $query = qq|DELETE FROM ar WHERE id = ?|;
386   do_query($form, $dbh, $query, $form->{id});
387
388   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
389   do_query($form, $dbh, $query, $form->{id});
390
391   # commit
392   my $rc = $dbh->commit;
393   $dbh->disconnect;
394
395   $main::lxdebug->leave_sub();
396
397   return $rc;
398 }
399
400 sub ar_transactions {
401   $main::lxdebug->enter_sub();
402
403   my ($self, $myconfig, $form) = @_;
404
405   # connect to database
406   my $dbh = $form->dbconnect($myconfig);
407
408   my @values;
409
410   my $query =
411     qq|SELECT a.id, a.invnumber, a.ordnumber, a.transdate, | .
412     qq|  a.duedate, a.netamount, a.amount, a.paid, | .
413     qq|  a.invoice, a.datepaid, a.terms, a.notes, a.shipvia, | .
414     qq|  a.shippingpoint, a.storno, a.storno_id, a.globalproject_id, | .
415     qq|  a.marge_total, a.marge_percent, | .
416     qq|  a.transaction_description, | .
417     qq|  pr.projectnumber AS globalprojectnumber, | .
418     qq|  c.name, | .
419     qq|  e.name AS employee, | .
420     qq|  e2.name AS salesman | .
421     qq|FROM ar a | .
422     qq|JOIN customer c ON (a.customer_id = c.id) | .
423     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
424     qq|LEFT JOIN employee e2 ON (a.salesman_id = e2.id) | .
425     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id)|;
426
427   my $where = "1 = 1";
428   if ($form->{customer_id}) {
429     $where .= " AND a.customer_id = ?";
430     push(@values, $form->{customer_id});
431   } elsif ($form->{customer}) {
432     $where .= " AND c.name ILIKE ?";
433     push(@values, $form->like($form->{customer}));
434   }
435   if ($form->{department}) {
436     my ($null, $department_id) = split /--/, $form->{department};
437     $where .= " AND a.department_id = ?";
438     push(@values, $department_id);
439   }
440   foreach my $column (qw(invnumber ordnumber notes transaction_description)) {
441     if ($form->{$column}) {
442       $where .= " AND a.$column ILIKE ?";
443       push(@values, $form->like($form->{$column}));
444     }
445   }
446   if ($form->{"project_id"}) {
447     $where .=
448       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
449       qq|  (SELECT * FROM invoice i | .
450       qq|   WHERE i.project_id = ? AND i.trans_id = a.id))|;
451     push(@values, $form->{"project_id"}, $form->{"project_id"});
452   }
453
454   if ($form->{transdatefrom}) {
455     $where .= " AND a.transdate >= ?";
456     push(@values, $form->{transdatefrom});
457   }
458   if ($form->{transdateto}) {
459     $where .= " AND a.transdate <= ?";
460     push(@values, $form->{transdateto});
461   }
462   if ($form->{open} || $form->{closed}) {
463     unless ($form->{open} && $form->{closed}) {
464       $where .= " AND a.amount <> a.paid" if ($form->{open});
465       $where .= " AND a.amount = a.paid"  if ($form->{closed});
466     }
467   }
468
469   my @a = (transdate, invnumber, name);
470   push @a, "employee" if $form->{l_employee};
471   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
472   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
473
474   if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description))) {
475     $sortorder = $form->{sort} . " $sortdir";
476   }
477
478   $query .= " WHERE $where ORDER BY $sortorder";
479
480   my $sth = $dbh->prepare($query);
481   $sth->execute(@values) ||
482     $form->dberror($query . " (" . join(", ", @values) . ")");
483
484   $form->{AR} = [];
485   while (my $ar = $sth->fetchrow_hashref(NAME_lc)) {
486     push @{ $form->{AR} }, $ar;
487   }
488
489   $sth->finish;
490   $dbh->disconnect;
491
492   $main::lxdebug->leave_sub();
493 }
494
495 sub get_transdate {
496   $main::lxdebug->enter_sub();
497
498   my ($self, $myconfig, $form) = @_;
499
500   # connect to database
501   my $dbh = $form->dbconnect($myconfig);
502
503   my $query =
504     "SELECT COALESCE(" .
505     "  (SELECT transdate FROM ar WHERE id = " .
506     "    (SELECT MAX(id) FROM ar) LIMIT 1), " .
507     "  current_date)";
508   ($form->{transdate}) = $dbh->selectrow_array($query);
509
510   $dbh->disconnect;
511
512   $main::lxdebug->leave_sub();
513 }
514
515 sub setup_form {
516   $main::lxdebug->enter_sub();
517
518   my ($self, $form) = @_;
519
520   my ($exchangerate, $key, $akey, $i, $j, $k, $index, $taxamount, $totaltax, $taxrate, $diff);
521
522   # forex
523   $form->{forex} = $form->{exchangerate};
524   $exchangerate  = $form->{exchangerate} ? $form->{exchangerate} : 1;
525
526   foreach $key (keys %{ $form->{AR_links} }) {
527     # if there is a value we have an old entry
528     $j = 0;
529     $k = 0;
530
531     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
532       if ($key eq "AR_paid") {
533         $j++;
534         $form->{"AR_paid_$j"} = $form->{acc_trans}{$key}->[$i-1]->{accno};
535
536         # reverse paid
537         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
538         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
539         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
540         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
541         $form->{"forex_$j"}           = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
542         $form->{"exchangerate_$i"}    = $form->{"forex_$j"};
543         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
544         $form->{paidaccounts}++;
545
546       } else {
547
548         $akey = $key;
549         $akey =~ s/AR_//;
550
551         if ($key eq "AR_tax" || $key eq "AP_tax") {
552           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
553           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
554
555           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
556             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
557             $taxrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
558
559           } else {
560             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
561             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
562           }
563
564           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
565           $form->{"tax_$index"}  = $form->{acc_trans}{$key}->[$i - 1]->{amount};
566           $totaltax             += $form->{"tax_$index"};
567
568         } else {
569           $k++;
570           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
571
572           if ($akey eq 'amount') {
573             $form->{rowcount}++;
574             $totalamount += $form->{"${akey}_$i"};
575
576             $form->{"oldprojectnumber_$k"} = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
577             $form->{"projectnumber_$k"}    = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
578             $form->{taxrate}               = $form->{acc_trans}{$key}->[$i - 1]->{rate};
579             $form->{"project_id_$k"}       = $form->{acc_trans}{$key}->[$i-1]->{project_id};
580           }
581
582           $form->{"${key}_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
583
584           if ($akey eq "AR") {
585             $form->{ARselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
586
587           } elsif ($akey eq "amount") {
588             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
589             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
590           }
591         }
592       }
593     }
594   }
595
596   $form->{taxincluded}  = $taxincluded if ($form->{id});
597   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
598
599   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
600
601     # add tax to amounts and invtotal
602     for $i (1 .. $form->{rowcount}) {
603       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
604       $tax                  = $form->round_amount($taxamount, 2);
605       $diff                += ($taxamount - $tax);
606       $form->{"amount_$i"} += $form->{"tax_$i"};
607     }
608     $form->{amount_1} += $form->round_amount($diff, 2);
609   }
610
611   $taxamount   = $form->round_amount($taxamount, 2);
612   $form->{tax} = $taxamount;
613
614   $form->{invtotal} = $totalamount + $totaltax;
615
616   $main::lxdebug->leave_sub();
617 }
618
619 sub storno {
620   $main::lxdebug->enter_sub();
621
622   my ($self, $form, $myconfig, $id) = @_;
623
624   my ($query, $new_id, $storno_row, $acc_trans_rows);
625   my $dbh = $form->get_standard_dbh($myconfig);
626
627   $query = qq|SELECT nextval('glid')|;
628   ($new_id) = selectrow_query($form, $dbh, $query);
629
630   $query = qq|SELECT * FROM ar WHERE id = ?|;
631   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
632
633   $storno_row->{id}         = $new_id;
634   $storno_row->{storno_id}  = $id;
635   $storno_row->{storno}     = 't';
636   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
637   $storno_row->{amount}    *= -1;
638   $storno_row->{netamount} *= -1;
639   $storno_row->{paid}       = $storno_row->{amount};
640
641   delete @$storno_row{qw(itime mtime)};
642
643   $query = sprintf 'INSERT INTO ar (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
644   do_query($form, $dbh, $query, (values %$storno_row));
645
646   $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
647   do_query($form, $dbh, $query, $id);
648
649   # now copy acc_trans entries
650   $query = qq|SELECT a.*, c.link FROM acc_trans a LEFT JOIN chart c ON a.chart_id = c.id WHERE a.trans_id = ? ORDER BY a.oid|;
651   my $rowref = selectall_hashref_query($form, $dbh, $query, $id); 
652
653   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
654   while ($rowref->[-1]{link} =~ /paid/) {
655     splice(@$rowref, -2);
656   }
657
658   for my $row (@$rowref) {
659     delete @$row{qw(itime mtime link)};
660     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
661     $row->{trans_id}   = $new_id;
662     $row->{amount}    *= -1;
663     do_query($form, $dbh, $query, (values %$row));
664   }
665
666   $dbh->commit;
667
668   $main::lxdebug->leave_sub();
669 }
670
671
672 1;
673