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