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