Debitoren-/Kreditoren-/Dialogbuchungen: Fremdschlüsselspalte "department_id" nicht...
[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
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
253     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
254       next;
255     }
256
257     if ($form->{"paid_$i"} != 0) {
258       my $project_id = conv_i($form->{"paid_project_id_$i"});
259
260       $exchangerate = 0;
261       if ($form->{currency} eq $form->{defaultcurrency}) {
262         $form->{"exchangerate_$i"} = 1;
263       } else {
264         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
265         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
266       }
267       $form->{"AP_paid_$i"} =~ s/\"//g;
268
269       # get paid account
270
271       ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
272       $form->{"datepaid_$i"} = $form->{transdate}
273         unless ($form->{"datepaid_$i"});
274
275       # if there is no amount and invtotal is zero there is no exchangerate
276       if ($form->{amount} == 0 && $form->{invtotal} == 0) {
277         $form->{exchangerate} = $form->{"exchangerate_$i"};
278       }
279
280       $amount =
281         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
282                             2);
283       if ($form->{payables}) {
284         $query =
285           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey) | .
286           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, | .
287           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
288         @values = ($form->{id}, $form->{AP_payables}, $amount,
289                    conv_date($form->{"datepaid_$i"}), $project_id,
290                    $form->{AP_payables});
291         do_query($form, $dbh, $query, @values);
292       }
293       $form->{payables} = $amount;
294
295       # add payment
296       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
297       $query =
298         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, taxkey) | .
299         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, | .
300         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
301       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
302                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
303                  $form->{"memo_$i"}, $project_id, $form->{"AP_paid_account_$i"});
304       do_query($form, $dbh, $query, @values);
305
306       # add exchange rate difference
307       $amount =
308         $form->round_amount($form->{"paid_$i"} *
309                             ($form->{"exchangerate_$i"} - 1), 2);
310       if ($amount != 0) {
311         $query =
312           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey) | .
313           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
314           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
315         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
316                    conv_date($form->{"datepaid_$i"}), $project_id,
317                    $form->{"AP_paid_account_$i"});
318         do_query($form, $dbh, $query, @values);
319       }
320
321       # exchangerate gain/loss
322       $amount =
323         $form->round_amount($form->{"paid_$i"} *
324                             ($form->{exchangerate} -
325                              $form->{"exchangerate_$i"}), 2);
326
327       if ($amount != 0) {
328         $query =
329           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey) | .
330           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
331           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?))|;
332         @values = ($form->{id}, ($amount > 0) ?
333                    $form->{fxgain_accno} : $form->{fxloss_accno},
334                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
335                    ($amount > 0) ?
336                    $form->{fxgain_accno} : $form->{fxloss_accno});
337         do_query($form, $dbh, $query, @values);
338       }
339
340       # update exchange rate record
341       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
342         $form->update_exchangerate($dbh, $form->{currency},
343                                    $form->{"datepaid_$i"},
344                                    0, $form->{"exchangerate_$i"});
345       }
346     }
347   }
348
349   if ($payments_only) {
350     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
351     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
352   }
353
354   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
355
356   # safety check datev export
357   if ($::instance_conf->get_datev_check_on_ap_transaction) {
358     my $transdate = $::form->{transdate} ? DateTime->from_lxoffice($::form->{transdate}) : undef;
359     $transdate  ||= DateTime->today;
360
361     my $datev = SL::DATEV->new(
362       exporttype => DATEV_ET_BUCHUNGEN,
363       format     => DATEV_FORMAT_KNE,
364       dbh        => $dbh,
365       from       => $transdate,
366       to         => $transdate,
367     );
368
369     $datev->export;
370
371     if ($datev->errors) {
372       $dbh->rollback;
373       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
374     }
375   }
376
377   if (!$provided_dbh) {
378     $dbh->commit();
379     $dbh->disconnect();
380   }
381
382   $rc = 1; #  Den return-code auf true setzen, aber nur falls beim commit alles i.O. ist
383
384   $main::lxdebug->leave_sub();
385
386   return $rc;
387 }
388
389 sub delete_transaction {
390   $main::lxdebug->enter_sub();
391
392   my ($self, $myconfig, $form) = @_;
393
394   # connect to database
395   my $dbh = $form->dbconnect_noauto($myconfig);
396
397   # acc_trans entries are deleted by database triggers.
398   my $query = qq|DELETE FROM ap WHERE id = ?|;
399   do_query($form, $dbh, $query, $form->{id});
400
401   my $rc = $dbh->commit;
402   $dbh->disconnect;
403
404   $main::lxdebug->leave_sub();
405
406   return $rc;
407 }
408
409 sub ap_transactions {
410   $main::lxdebug->enter_sub();
411
412   my ($self, $myconfig, $form) = @_;
413
414   # connect to database
415   my $dbh = $form->get_standard_dbh($myconfig);
416
417   my $query =
418     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
419     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
420     qq|  a.globalproject_id, a.storno, a.storno_id, | .
421     qq|  pr.projectnumber AS globalprojectnumber, | .
422     qq|  e.name AS employee, | .
423     qq|  v.vendornumber, v.country, v.ustid, | .
424     qq|  tz.description AS taxzone, | .
425     qq|  pt.description AS payment_terms, | .
426     qq{  ( SELECT ch.accno || ' -- ' || ch.description
427            FROM acc_trans at
428            LEFT JOIN chart ch ON ch.id = at.chart_id
429            WHERE ch.link ~ 'AP[[:>:]]'
430             AND at.trans_id = a.id
431             LIMIT 1
432           ) AS charts } .
433     qq|FROM ap a | .
434     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
435     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
436     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
437     qq|LEFT JOIN tax_zones tz ON (tz.id = v.taxzone_id)| .
438     qq|LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)|;
439
440   my $where = '';
441   my @values;
442
443   if ($form->{vendor_id}) {
444     $where .= " AND a.vendor_id = ?";
445     push(@values, $form->{vendor_id});
446   } elsif ($form->{vendor}) {
447     $where .= " AND v.name ILIKE ?";
448     push(@values, $form->like($form->{vendor}));
449   }
450   if ($form->{department}) {
451     # ähnlich wie commit 0bbfb33b6aa8e38bb6c81d1684ab7d08e5b5c5af abteilung
452     # wird so nicht mehr als zeichenkette zusammengebaut
453     # hätte zu ee9f9f9aa4c3b9d5d20ab10a45c12bcaa6aa78d0 auffallen können ;-) jan
454     #my ($null, $department_id) = split /--/, $form->{department};
455     $where .= " AND a.department_id = ?";
456     push(@values, $form->{department});
457   }
458   if ($form->{invnumber}) {
459     $where .= " AND a.invnumber ILIKE ?";
460     push(@values, $form->like($form->{invnumber}));
461   }
462   if ($form->{ordnumber}) {
463     $where .= " AND a.ordnumber ILIKE ?";
464     push(@values, $form->like($form->{ordnumber}));
465   }
466   if ($form->{notes}) {
467     $where .= " AND lower(a.notes) LIKE ?";
468     push(@values, $form->like($form->{notes}));
469   }
470   if ($form->{project_id}) {
471     $where .=
472       qq|AND ((a.globalproject_id = ?) OR EXISTS | .
473       qq|  (SELECT * FROM invoice i | .
474       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
475       qq| OR EXISTS | .
476       qq|  (SELECT * FROM acc_trans at | .
477       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
478       qq|  )|;
479     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
480   }
481
482   if ($form->{transdatefrom}) {
483     $where .= " AND a.transdate >= ?";
484     push(@values, $form->{transdatefrom});
485   }
486   if ($form->{transdateto}) {
487     $where .= " AND a.transdate <= ?";
488     push(@values, $form->{transdateto});
489   }
490   if ($form->{open} || $form->{closed}) {
491     unless ($form->{open} && $form->{closed}) {
492       $where .= " AND a.amount <> a.paid" if ($form->{open});
493       $where .= " AND a.amount = a.paid"  if ($form->{closed});
494     }
495   }
496
497   if ($where) {
498     substr($where, 0, 4, " WHERE ");
499     $query .= $where;
500   }
501
502   my @a = qw(transdate invnumber name);
503   push @a, "employee" if $form->{l_employee};
504   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
505   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
506
507   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description))) {
508     $sortorder = $form->{sort} . " $sortdir";
509   }
510
511   $query .= " ORDER BY $sortorder";
512
513   my @result = selectall_hashref_query($form, $dbh, $query, @values);
514
515   $form->{AP} = [ @result ];
516
517   $main::lxdebug->leave_sub();
518 }
519
520 sub get_transdate {
521   $main::lxdebug->enter_sub();
522
523   my ($self, $myconfig, $form) = @_;
524
525   # connect to database
526   my $dbh = $form->dbconnect($myconfig);
527
528   my $query =
529     "SELECT COALESCE(" .
530     "  (SELECT transdate FROM ap WHERE id = " .
531     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
532     "  current_date)";
533   ($form->{transdate}) = $dbh->selectrow_array($query);
534
535   $dbh->disconnect;
536
537   $main::lxdebug->leave_sub();
538 }
539
540 sub _delete_payments {
541   $main::lxdebug->enter_sub();
542
543   my ($self, $form, $dbh) = @_;
544
545   my @delete_acc_trans_ids;
546
547   # Delete old payment entries from acc_trans.
548   my $query =
549     qq|SELECT acc_trans_id
550        FROM acc_trans
551        WHERE (trans_id = ?) AND fx_transaction
552
553        UNION
554
555        SELECT at.acc_trans_id
556        FROM acc_trans at
557        LEFT JOIN chart c ON (at.chart_id = c.id)
558        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
559   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
560
561   $query =
562     qq|SELECT at.acc_trans_id
563        FROM acc_trans at
564        LEFT JOIN chart c ON (at.chart_id = c.id)
565        WHERE (trans_id = ?)
566          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
567        ORDER BY at.acc_trans_id
568        OFFSET 1|;
569   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
570
571   if (@delete_acc_trans_ids) {
572     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
573     do_query($form, $dbh, $query);
574   }
575
576   $main::lxdebug->leave_sub();
577 }
578
579 sub post_payment {
580   $main::lxdebug->enter_sub();
581
582   my ($self, $myconfig, $form, $locale) = @_;
583
584   # connect to database, turn off autocommit
585   my $dbh = $form->dbconnect_noauto($myconfig);
586
587   my (%payments, $old_form, $row, $item, $query, %keep_vars);
588
589   $old_form = save_form();
590
591   # Delete all entries in acc_trans from prior payments.
592   if (SL::DB::Default->get->payments_changeable != 0) {
593     $self->_delete_payments($form, $dbh);
594   }
595
596   # Save the new payments the user made before cleaning up $form.
597   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$';
598   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
599
600   # Clean up $form so that old content won't tamper the results.
601   %keep_vars = map { $_, 1 } qw(login password id);
602   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
603
604   # Retrieve the invoice from the database.
605   $form->create_links('AP', $myconfig, 'vendor', $dbh);
606
607   # Restore the payment options from the user input.
608   map { $form->{$_} = $payments{$_} } keys %payments;
609
610   # Set up the content of $form in the way that AR::post_transaction() expects.
611
612   $self->setup_form($form, 1);
613
614   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
615   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
616   delete $form->{currency} unless $form->{defaultcurrency};
617
618   # Get the AP accno.
619   $query =
620     qq|SELECT c.accno
621        FROM acc_trans at
622        LEFT JOIN chart c ON (at.chart_id = c.id)
623        WHERE (trans_id = ?)
624          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
625        ORDER BY at.acc_trans_id
626        LIMIT 1|;
627
628   ($form->{APselected}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
629
630   # Post the new payments.
631   $self->post_transaction($myconfig, $form, $dbh, 1);
632
633   restore_form($old_form);
634
635   my $rc = $dbh->commit();
636   $dbh->disconnect();
637
638   $main::lxdebug->leave_sub();
639
640   return $rc;
641 }
642
643 sub setup_form {
644   $main::lxdebug->enter_sub();
645
646   my ($self, $form, $for_post_payments) = @_;
647
648   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
649       $taxincluded, $tax, $diff);
650
651   # forex
652   $form->{forex} = $form->{exchangerate};
653   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
654
655   foreach $key (keys %{ $form->{AP_links} }) {
656     foreach $ref (@{ $form->{AP_links}{$key} }) {
657       if ($key eq "AP_paid") {
658         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
659       } else {
660         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
661       }
662     }
663
664     $form->{$key} = $form->{"select$key"};
665
666     $j = 0;
667     $k = 0;
668
669     # if there is a value we have an old entry
670     next unless $form->{acc_trans}{$key};
671
672     # do not use old entries for payments. They come from the form
673     # even if they are not changeable (then they are in hiddens)
674     next if $for_post_payments && $key eq "AP_paid";
675
676     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
677
678       if ($key eq "AP_paid") {
679         $j++;
680         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
681         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
682         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
683         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
684         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
685         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
686         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
687
688         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
689         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
690         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
691         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
692         $form->{paidaccounts}++;
693
694       } else {
695         $akey = $key;
696         $akey =~ s/AP_//;
697
698         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
699           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
700           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
701
702           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
703             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
704           } else {
705             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
706             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
707           }
708
709           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
710           $form->{"tax_$index"}  = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
711           $totaltax             += $form->{"tax_$index"};
712
713         } else {
714           $k++;
715           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
716
717           if ($akey eq 'amount') {
718             $form->{rowcount}++;
719             $form->{"${akey}_$i"} *= -1;
720             $totalamount          += $form->{"${akey}_$i"};
721             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
722
723             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
724             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
725             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
726           }
727
728           $form->{"${key}_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
729
730           my $q_description    = quotemeta($form->{acc_trans}{$key}->[$i-1]->{description});
731           $form->{"select${key}"} =~
732             m/<option value=\"
733                 ($form->{acc_trans}{$key}->[$i-1]->{accno}--[^\"]*)
734               \">
735               $form->{acc_trans}{$key}->[$i-1]->{accno}
736               --
737               ${q_description}
738               <\/option>\n/x;
739           $form->{"${key}_$k"} = $1;
740
741           if ($akey eq "AP") {
742             $form->{APselected} = $form->{acc_trans}{$key}->[$i-1]->{accno};
743
744           } elsif ($akey eq 'amount') {
745             $form->{"${key}_$k"}   = $form->{acc_trans}{$key}->[$i-1]->{accno} . "--" . $form->{acc_trans}{$key}->[$i-1]->{id};
746             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
747           }
748         }
749       }
750     }
751   }
752
753   $form->{taxincluded}  = $taxincluded if ($form->{id});
754   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
755
756   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
757     # add tax to amounts and invtotal
758     for $i (1 .. $form->{rowcount}) {
759       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
760       $tax                  = $form->round_amount($taxamount, 2);
761       $diff                += ($taxamount - $tax);
762       $form->{"amount_$i"} += $form->{"tax_$i"};
763     }
764
765     $form->{amount_1} += $form->round_amount($diff, 2);
766   }
767
768   $taxamount        = $form->round_amount($taxamount, 2);
769   $form->{invtotal} = $totalamount + $totaltax;
770
771   $main::lxdebug->leave_sub();
772 }
773
774 sub storno {
775   $main::lxdebug->enter_sub();
776
777   my ($self, $form, $myconfig, $id) = @_;
778
779   my ($query, $new_id, $storno_row, $acc_trans_rows);
780   my $dbh = $form->get_standard_dbh($myconfig);
781
782   $query = qq|SELECT nextval('glid')|;
783   ($new_id) = selectrow_query($form, $dbh, $query);
784
785   $query = qq|SELECT * FROM ap WHERE id = ?|;
786   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
787
788   $storno_row->{id}         = $new_id;
789   $storno_row->{storno_id}  = $id;
790   $storno_row->{storno}     = 't';
791   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
792   $storno_row->{amount}    *= -1;
793   $storno_row->{netamount} *= -1;
794   $storno_row->{paid}       = $storno_row->{amount};
795
796   delete @$storno_row{qw(itime mtime)};
797
798   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
799   do_query($form, $dbh, $query, (values %$storno_row));
800
801   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
802   do_query($form, $dbh, $query, $id);
803
804   # now copy acc_trans entries
805   $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|;
806   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
807
808   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
809   while ($rowref->[-1]{link} =~ /paid/) {
810     splice(@$rowref, -2);
811   }
812
813   for my $row (@$rowref) {
814     delete @$row{qw(itime mtime link acc_trans_id)};
815     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
816     $row->{trans_id}   = $new_id;
817     $row->{amount}    *= -1;
818     do_query($form, $dbh, $query, (values %$row));
819   }
820
821   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);
822
823   $dbh->commit;
824
825   $main::lxdebug->leave_sub();
826 }
827
828 1;
829