Storno von Debitoren-/Kreditorenrechnungen: acc_trans_id nicht doppelt einfügen
[kivitendo-erp.git] / SL / AP.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 Payables database backend routines
32 #
33 #======================================================================
34
35 package AP;
36
37 use SL::DBUtils;
38 use SL::IO;
39 use SL::MoreCommon;
40
41 use Data::Dumper;
42
43 use strict;
44
45 sub post_transaction {
46   $main::lxdebug->enter_sub();
47
48   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
49   my $rc = 0; # return code auf false setzen
50   # connect to database
51   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
52
53   my ($null, $taxrate, $amount);
54   my $exchangerate = 0;
55
56   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
57   delete $form->{currency} unless $form->{defaultcurrency};
58
59   ($null, $form->{department_id}) = split(/--/, $form->{department});
60   $form->{department_id} *= 1;
61
62   if ($form->{currency} eq $form->{defaultcurrency}) {
63     $form->{exchangerate} = 1;
64   } else {
65     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
66     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
67   }
68
69   for my $i (1 .. $form->{rowcount}) {
70     $form->{AP_amounts}{"amount_$i"} =
71       (split(/--/, $form->{"AP_amount_$i"}))[0];
72   }
73   ($form->{AP_amounts}{payables}) = split(/--/, $form->{APselected});
74   ($form->{AP_payables})          = split(/--/, $form->{APselected});
75
76   # reverse and parse amounts
77   for my $i (1 .. $form->{rowcount}) {
78     $form->{"amount_$i"} =
79       $form->round_amount(
80                          $form->parse_amount($myconfig, $form->{"amount_$i"}) *
81                            $form->{exchangerate} * -1,
82                          2);
83     $amount += ($form->{"amount_$i"} * -1);
84
85     # parse tax_$i for later
86     $form->{"tax_$i"} = $form->parse_amount($myconfig, $form->{"tax_$i"}) * -1;
87   }
88
89   # this is for ap
90   $form->{amount} = $amount;
91
92   # taxincluded doesn't make sense if there is no amount
93   $form->{taxincluded} = 0 if ($form->{amount} == 0);
94
95   for my $i (1 .. $form->{rowcount}) {
96     ($form->{"tax_id_$i"}, undef) = split /--/, $form->{"taxchart_$i"};
97
98     my $query =
99       qq|SELECT c.accno, t.taxkey, t.rate | .
100       qq|FROM tax t LEFT JOIN chart c on (c.id=t.chart_id) | .
101       qq|WHERE t.id = ? | .
102       qq|ORDER BY c.accno|;
103     my $sth = $dbh->prepare($query);
104     $sth->execute($form->{"tax_id_$i"}) || $form->dberror($query . " (" . $form->{"tax_id_$i"} . ")");
105     ($form->{AP_amounts}{"tax_$i"}, $form->{"taxkey_$i"}, $form->{"taxrate_$i"}) = $sth->fetchrow_array();
106
107     $sth->finish;
108
109     my ($tax, $diff);
110     if ($form->{taxincluded} *= 1) {
111       if (!$form->{"korrektur_$i"}) {
112         $tax =
113           $form->{"amount_$i"} -
114           ($form->{"amount_$i"} / ($form->{"taxrate_$i"} + 1));
115       } else {
116         $tax = $form->{"tax_$i"};
117       }
118       $amount = $form->{"amount_$i"} - $tax;
119       $form->{"amount_$i"} = $form->round_amount($amount, 2);
120       $diff += $amount - $form->{"amount_$i"};
121       $form->{"tax_$i"} = $form->round_amount($tax, 2);
122       $form->{netamount} += $form->{"amount_$i"};
123     } else {
124       if (!$form->{"korrektur_$i"}) {
125         $form->{"tax_$i"} = $form->{"amount_$i"} * $form->{"taxrate_$i"};
126       } else {
127         $tax = $form->{"tax_$i"};
128       }
129       $form->{"tax_$i"} =
130         $form->round_amount($form->{"tax_$i"} * $form->{exchangerate}, 2);
131       $form->{netamount} += $form->{"amount_$i"};
132     }
133     $form->{total_tax} += $form->{"tax_$i"} * -1;
134   }
135
136   # adjust paidaccounts if there is no date in the last row
137   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
138
139   $form->{invpaid} = 0;
140   $form->{netamount} *= -1;
141
142   # add payments
143   for my $i (1 .. $form->{paidaccounts}) {
144     $form->{"paid_$i"} =
145       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
146                           2);
147
148     $form->{invpaid} += $form->{"paid_$i"};
149     $form->{datepaid} = $form->{"datepaid_$i"};
150
151   }
152
153   $form->{invpaid} =
154     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
155
156   # store invoice total, this goes into ap table
157   $form->{invtotal} = $form->{netamount} + $form->{total_tax};
158
159   # amount for total AP
160   $form->{payables} = $form->{invtotal};
161
162   # update exchangerate
163   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
164     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
165                                $form->{exchangerate});
166   }
167
168   my ($query, $sth, @values);
169
170   if (!$payments_only) {
171     # if we have an id delete old records
172     if ($form->{id}) {
173
174       # delete detail records
175       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
176       do_query($form, $dbh, $query, $form->{id});
177
178     } else {
179       my $uid = rand() . time;
180
181       $uid .= $form->{login};
182
183       $uid = substr($uid, 2, 75);
184
185       $query =
186         qq|INSERT INTO ap (invnumber, employee_id) | .
187         qq|VALUES (?, (SELECT e.id FROM employee e WHERE e.login = ?))|;
188       do_query($form, $dbh, $query, $uid, $form->{login});
189
190       $query = qq|SELECT a.id FROM ap a
191                   WHERE a.invnumber = ?|;
192       ($form->{id}) = selectrow_query($form, $dbh, $query, $uid);
193     }
194
195     $form->{invnumber} = $form->{id} unless $form->{invnumber};
196
197     $query = qq|UPDATE ap SET
198                 invnumber = ?, transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
199                 amount = ?, duedate = ?, paid = ?, netamount = ?,
200                 curr = ?, notes = ?, department_id = ?, storno = ?, storno_id = ?
201                WHERE id = ?|;
202     @values = ($form->{invnumber}, conv_date($form->{transdate}),
203                   $form->{ordnumber}, conv_i($form->{vendor_id}),
204                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
205                   conv_date($form->{duedate}), $form->{invpaid},
206                   $form->{netamount},
207                   $form->{currency}, $form->{notes},
208                   conv_i($form->{department_id}), $form->{storno},
209                   $form->{storno_id}, $form->{id});
210     do_query($form, $dbh, $query, @values);
211
212     # add individual transactions
213     for my $i (1 .. $form->{rowcount}) {
214       if ($form->{"amount_$i"} != 0) {
215         my $project_id;
216         $project_id = conv_i($form->{"project_id_$i"});
217
218         # insert detail records in acc_trans
219         $query =
220           qq|INSERT INTO acc_trans | .
221           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey)| .
222           qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
223           qq|  ?, ?, ?, ?)|;
224         @values = ($form->{id}, $form->{AP_amounts}{"amount_$i"},
225                    $form->{"amount_$i"}, conv_date($form->{transdate}),
226                    $project_id, $form->{"taxkey_$i"});
227         do_query($form, $dbh, $query, @values);
228
229         if ($form->{"tax_$i"} != 0) {
230           # insert detail records in acc_trans
231           $query =
232             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
233             qq|  project_id, taxkey) | .
234             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
235             qq|  ?, ?, ?, ?)|;
236           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
237                      $form->{"tax_$i"}, conv_date($form->{transdate}),
238                      $project_id, $form->{"taxkey_$i"});
239           do_query($form, $dbh, $query, @values);
240         }
241
242       }
243     }
244
245     # add payables
246     $query =
247       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) | .
248       qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, | .
249       qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
250     @values = ($form->{id}, $form->{AP_amounts}{payables}, $form->{payables},
251                conv_date($form->{transdate}), $form->{AP_amounts}{payables});
252     do_query($form, $dbh, $query, @values);
253   }
254
255   # if there is no amount but a payment record a payable
256   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
257     $form->{payables} = $form->{invpaid};
258   }
259
260   # add paid transactions
261   for my $i (1 .. $form->{paidaccounts}) {
262     if ($form->{"paid_$i"} != 0) {
263       my $project_id = conv_i($form->{"paid_project_id_$i"});
264
265       $exchangerate = 0;
266       if ($form->{currency} eq $form->{defaultcurrency}) {
267         $form->{"exchangerate_$i"} = 1;
268       } else {
269         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
270         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
271       }
272       $form->{"AP_paid_$i"} =~ s/\"//g;
273
274       # get paid account
275
276       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
277       $form->{"datepaid_$i"} = $form->{transdate}
278         unless ($form->{"datepaid_$i"});
279
280       # if there is no amount and invtotal is zero there is no exchangerate
281       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
282         $form->{exchangerate} = $form->{"exchangerate_$i"};
283       }
284
285       $amount =
286         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
287                             2);
288       if ($form->{payables}) {
289         $query =
290           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey) | .
291           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, | .
292           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
293         @values = ($form->{id}, $form->{AP_payables}, $amount,
294                    conv_date($form->{"datepaid_$i"}), $project_id,
295                    $form->{AP_payables});
296         do_query($form, $dbh, $query, @values);
297       }
298       $form->{payables} = $amount;
299
300       # add payment
301       $query =
302         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, project_id, taxkey) | .
303         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, | .
304         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
305       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
306                  conv_date($form->{"datepaid_$i"}), $form->{"source_$i"},
307                  $form->{"memo_$i"}, $project_id, $form->{"AP_paid_account_$i"});
308       do_query($form, $dbh, $query, @values);
309
310       # add exchange rate difference
311       $amount =
312         $form->round_amount($form->{"paid_$i"} *
313                             ($form->{"exchangerate_$i"} - 1), 2);
314       if ($amount != 0) {
315         $query =
316           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey) | .
317           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
318           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
319         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
320                    conv_date($form->{"datepaid_$i"}), $project_id,
321                    $form->{"AP_paid_account_$i"});
322         do_query($form, $dbh, $query, @values);
323       }
324
325       # exchangerate gain/loss
326       $amount =
327         $form->round_amount($form->{"paid_$i"} *
328                             ($form->{exchangerate} -
329                              $form->{"exchangerate_$i"}), 2);
330
331       if ($amount != 0) {
332         $query =
333           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey) | .
334           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
335           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
336         @values = ($form->{id}, ($amount > 0) ?
337                    $form->{fxgain_accno} : $form->{fxloss_accno},
338                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
339                    ($amount > 0) ?
340                    $form->{fxgain_accno} : $form->{fxloss_accno});
341         do_query($form, $dbh, $query, @values);
342       }
343
344       # update exchange rate record
345       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
346         $form->update_exchangerate($dbh, $form->{currency},
347                                    $form->{"datepaid_$i"},
348                                    0, $form->{"exchangerate_$i"});
349       }
350     }
351   }
352
353   if ($payments_only) {
354     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
355     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
356   }
357
358   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
359
360   if (!$provided_dbh) {
361     $dbh->commit();
362     $dbh->disconnect();
363   }
364
365   $rc = 1; #  Den return-code auf true setzen, aber nur falls beim commit alles i.O. ist
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, $spool) = @_;
376
377   # connect to database
378   my $dbh = $form->dbconnect_noauto($myconfig);
379
380   my $query = qq|DELETE FROM ap 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 and redirect
387   my $rc = $dbh->commit;
388   $dbh->disconnect;
389
390   $main::lxdebug->leave_sub();
391
392   return $rc;
393 }
394
395 sub ap_transactions {
396   $main::lxdebug->enter_sub();
397
398   my ($self, $myconfig, $form) = @_;
399
400   # connect to database
401   my $dbh = $form->get_standard_dbh($myconfig);
402
403   my $query =
404     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
405     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
406     qq|  a.globalproject_id, a.storno, a.storno_id, | .
407     qq|  pr.projectnumber AS globalprojectnumber, | .
408     qq|  e.name AS employee, | .
409     qq|  v.vendornumber, v.country, v.ustid, | .
410     qq|  tz.description AS taxzone, | .
411     qq|  pt.description AS payment_terms, | .
412     qq{  ( SELECT ch.accno || ' -- ' || ch.description
413            FROM acc_trans at
414            LEFT JOIN chart ch ON ch.id = at.chart_id
415            WHERE ch.link ~ 'AP[[:>:]]'
416             AND at.trans_id = a.id
417             LIMIT 1
418           ) AS charts } .
419     qq|FROM ap a | .
420     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
421     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
422     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
423     qq|LEFT JOIN tax_zones tz ON (tz.id = v.taxzone_id)| .
424     qq|LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)|;
425
426   my $where = '';
427   my @values;
428
429   if ($form->{vendor_id}) {
430     $where .= " AND a.vendor_id = ?";
431     push(@values, $form->{vendor_id});
432   } elsif ($form->{vendor}) {
433     $where .= " AND v.name ILIKE ?";
434     push(@values, $form->like($form->{vendor}));
435   }
436   if ($form->{department}) {
437     my ($null, $department_id) = split /--/, $form->{department};
438     $where .= " AND a.department_id = ?";
439     push(@values, $department_id);
440   }
441   if ($form->{invnumber}) {
442     $where .= " AND a.invnumber ILIKE ?";
443     push(@values, $form->like($form->{invnumber}));
444   }
445   if ($form->{ordnumber}) {
446     $where .= " AND a.ordnumber ILIKE ?";
447     push(@values, $form->like($form->{ordnumber}));
448   }
449   if ($form->{notes}) {
450     $where .= " AND lower(a.notes) LIKE ?";
451     push(@values, $form->like($form->{notes}));
452   }
453   if ($form->{project_id}) {
454     $where .=
455       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
456       qq|  (SELECT * FROM invoice i | .
457       qq|   WHERE i.project_id = ? AND i.trans_id = a.id))|;
458     push(@values, $form->{project_id}, $form->{project_id});
459   }
460
461   if ($form->{transdatefrom}) {
462     $where .= " AND a.transdate >= ?";
463     push(@values, $form->{transdatefrom});
464   }
465   if ($form->{transdateto}) {
466     $where .= " AND a.transdate <= ?";
467     push(@values, $form->{transdateto});
468   }
469   if ($form->{open} || $form->{closed}) {
470     unless ($form->{open} && $form->{closed}) {
471       $where .= " AND a.amount <> a.paid" if ($form->{open});
472       $where .= " AND a.amount = a.paid"  if ($form->{closed});
473     }
474   }
475
476   if ($where) {
477     substr($where, 0, 4, " WHERE ");
478     $query .= $where;
479   }
480
481   my @a = qw(transdate invnumber name);
482   push @a, "employee" if $form->{l_employee};
483   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
484   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
485
486   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description))) {
487     $sortorder = $form->{sort} . " $sortdir";
488   }
489
490   $query .= " ORDER BY $sortorder";
491
492   my @result = selectall_hashref_query($form, $dbh, $query, @values);
493
494   $form->{AP} = [ @result ];
495
496   $main::lxdebug->leave_sub();
497 }
498
499 sub get_transdate {
500   $main::lxdebug->enter_sub();
501
502   my ($self, $myconfig, $form) = @_;
503
504   # connect to database
505   my $dbh = $form->dbconnect($myconfig);
506
507   my $query =
508     "SELECT COALESCE(" .
509     "  (SELECT transdate FROM ap WHERE id = " .
510     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
511     "  current_date)";
512   ($form->{transdate}) = $dbh->selectrow_array($query);
513
514   $dbh->disconnect;
515
516   $main::lxdebug->leave_sub();
517 }
518
519 sub _delete_payments {
520   $main::lxdebug->enter_sub();
521
522   my ($self, $form, $dbh) = @_;
523
524   my @delete_acc_trans_ids;
525
526   # Delete old payment entries from acc_trans.
527   my $query =
528     qq|SELECT acc_trans_id
529        FROM acc_trans
530        WHERE (trans_id = ?) AND fx_transaction
531
532        UNION
533
534        SELECT at.acc_trans_id
535        FROM acc_trans at
536        LEFT JOIN chart c ON (at.chart_id = c.id)
537        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
538   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
539
540   $query =
541     qq|SELECT at.acc_trans_id
542        FROM acc_trans at
543        LEFT JOIN chart c ON (at.chart_id = c.id)
544        WHERE (trans_id = ?)
545          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
546        ORDER BY at.acc_trans_id
547        OFFSET 1|;
548   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
549
550   if (@delete_acc_trans_ids) {
551     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
552     do_query($form, $dbh, $query);
553   }
554
555   $main::lxdebug->leave_sub();
556 }
557
558 sub post_payment {
559   $main::lxdebug->enter_sub();
560
561   my ($self, $myconfig, $form, $locale) = @_;
562
563   # connect to database, turn off autocommit
564   my $dbh = $form->dbconnect_noauto($myconfig);
565
566   my (%payments, $old_form, $row, $item, $query, %keep_vars);
567
568   $old_form = save_form();
569
570   # Delete all entries in acc_trans from prior payments.
571   $self->_delete_payments($form, $dbh);
572
573   # Save the new payments the user made before cleaning up $form.
574   my $payments_re = '^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AP_paid_\d+$|^paidaccounts$';
575   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
576
577   # Clean up $form so that old content won't tamper the results.
578   %keep_vars = map { $_, 1 } qw(login password id);
579   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
580
581   # Retrieve the invoice from the database.
582   $form->create_links('AP', $myconfig, 'vendor', $dbh);
583
584   # Restore the payment options from the user input.
585   map { $form->{$_} = $payments{$_} } keys %payments;
586
587   # Set up the content of $form in the way that AR::post_transaction() expects.
588
589   $self->setup_form($form);
590
591   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
592   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
593   delete $form->{currency} unless $form->{defaultcurrency};
594
595   # Get the AP accno.
596   $query =
597     qq|SELECT c.accno
598        FROM acc_trans at
599        LEFT JOIN chart c ON (at.chart_id = c.id)
600        WHERE (trans_id = ?)
601          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
602        ORDER BY at.acc_trans_id
603        LIMIT 1|;
604
605   ($form->{APselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
606
607   # Post the new payments.
608   $self->post_transaction($myconfig, $form, $dbh, 1);
609
610   restore_form($old_form);
611
612   my $rc = $dbh->commit();
613   $dbh->disconnect();
614
615   $main::lxdebug->leave_sub();
616
617   return $rc;
618 }
619
620 sub setup_form {
621   $main::lxdebug->enter_sub();
622
623   my ($self, $form) = @_;
624
625   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
626       $taxincluded, $tax, $diff);
627
628   # forex
629   $form->{forex} = $form->{exchangerate};
630   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
631
632   foreach $key (keys %{ $form->{AP_links} }) {
633     foreach $ref (@{ $form->{AP_links}{$key} }) {
634       if ($key eq "AP_paid") {
635         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
636       } else {
637         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
638       }
639     }
640
641     $form->{$key} = $form->{"select$key"};
642
643     # if there is a value we have an old entry
644     $j = 0;
645     $k = 0;
646
647     next unless $form->{acc_trans}{$key};
648     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
649
650       if ($key eq "AP_paid") {
651         $j++;
652         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
653         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
654         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
655         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
656         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
657
658         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
659         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
660         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
661         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
662         $form->{paidaccounts}++;
663
664       } else {
665         $akey = $key;
666         $akey =~ s/AP_//;
667
668         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
669           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
670           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
671
672           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
673             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
674           } else {
675             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
676             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
677           }
678
679           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
680           $form->{"tax_$index"}  = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
681           $totaltax             += $form->{"tax_$index"};
682
683         } else {
684           $k++;
685           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
686
687           if ($akey eq 'amount') {
688             $form->{rowcount}++;
689             $form->{"${akey}_$i"} *= -1;
690             $totalamount          += $form->{"${akey}_$i"};
691             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
692
693             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
694             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
695             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
696           }
697
698           $form->{"${key}_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
699
700           my $q_description    = quotemeta($form->{acc_trans}{$key}->[$i-1]->{description});
701           $form->{"select${key}"} =~
702             m/<option value=\"
703                 ($form->{acc_trans}{$key}->[$i-1]->{accno}--[^\"]*)
704               \">
705               $form->{acc_trans}{$key}->[$i-1]->{accno}
706               --
707               ${q_description}
708               <\/option>\n/x;
709           $form->{"${key}_$k"} = $1;
710
711           if ($akey eq "AP") {
712             $form->{APselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
713
714           } elsif ($akey eq 'amount') {
715             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
716             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
717           }
718         }
719       }
720     }
721   }
722
723   $form->{taxincluded}  = $taxincluded if ($form->{id});
724   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
725
726   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
727     # add tax to amounts and invtotal
728     for $i (1 .. $form->{rowcount}) {
729       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
730       $tax                  = $form->round_amount($taxamount, 2);
731       $diff                += ($taxamount - $tax);
732       $form->{"amount_$i"} += $form->{"tax_$i"};
733     }
734
735     $form->{amount_1} += $form->round_amount($diff, 2);
736   }
737
738   $taxamount        = $form->round_amount($taxamount, 2);
739   $form->{invtotal} = $totalamount + $totaltax;
740
741   $main::lxdebug->leave_sub();
742 }
743
744 sub storno {
745   $main::lxdebug->enter_sub();
746
747   my ($self, $form, $myconfig, $id) = @_;
748
749   my ($query, $new_id, $storno_row, $acc_trans_rows);
750   my $dbh = $form->get_standard_dbh($myconfig);
751
752   $query = qq|SELECT nextval('glid')|;
753   ($new_id) = selectrow_query($form, $dbh, $query);
754
755   $query = qq|SELECT * FROM ap WHERE id = ?|;
756   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
757
758   $storno_row->{id}         = $new_id;
759   $storno_row->{storno_id}  = $id;
760   $storno_row->{storno}     = 't';
761   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
762   $storno_row->{amount}    *= -1;
763   $storno_row->{netamount} *= -1;
764   $storno_row->{paid}       = $storno_row->{amount};
765
766   delete @$storno_row{qw(itime mtime)};
767
768   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
769   do_query($form, $dbh, $query, (values %$storno_row));
770
771   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
772   do_query($form, $dbh, $query, $id);
773
774   # now copy acc_trans entries
775   $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.acc_trans_id|;
776   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
777
778   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
779   while ($rowref->[-1]{link} =~ /paid/) {
780     splice(@$rowref, -2);
781   }
782
783   for my $row (@$rowref) {
784     delete @$row{qw(itime mtime link acc_trans_id)};
785     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
786     $row->{trans_id}   = $new_id;
787     $row->{amount}    *= -1;
788     do_query($form, $dbh, $query, (values %$row));
789   }
790
791   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);
792
793   $dbh->commit;
794
795   $main::lxdebug->leave_sub();
796 }
797
798 1;
799