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