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