test action
[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., 51 Franklin Street, Fifth Floor, Boston,
29 # MA 02110-1335, USA.
30 #======================================================================
31 #
32 # Accounts Payables database backend routines
33 #
34 #======================================================================
35
36 package AP;
37
38 use SL::DATEV qw(:CONSTANTS);
39 use SL::DBUtils;
40 use SL::IO;
41 use SL::MoreCommon;
42 use SL::DB::Default;
43 use SL::DB::Draft;
44 use SL::DB::Order;
45 use SL::DB::PurchaseInvoice;
46 use SL::Util qw(trim);
47 use SL::DB;
48 use Data::Dumper;
49 use List::Util qw(sum0);
50 use strict;
51
52 sub post_transaction {
53   my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
54   $main::lxdebug->enter_sub();
55
56   my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, %params);
57
58   $::lxdebug->leave_sub;
59   return $rc;
60 }
61
62 sub _post_transaction {
63   my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
64
65   my $payments_only = $params{payments_only};
66   my $dbh = $provided_dbh || SL::DB->client->dbh;
67
68   my ($null, $taxrate, $amount);
69   my $exchangerate = 0;
70
71   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
72   $form->{taxincluded} = 0 unless $form->{taxincluded};
73
74   if ($form->{currency} eq $form->{defaultcurrency}) {
75     $form->{exchangerate} = 1;
76   } else {
77     $exchangerate         = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
78     $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
79   }
80
81   # get the charts selected
82   $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
83
84   # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
85   ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
86
87   # adjust paidaccounts if there is no date in the last row
88   $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
89
90   $form->{invpaid} = 0;
91
92   # add payments
93   for my $i (1 .. $form->{paidaccounts}) {
94     $form->{"paid_$i"} =
95       $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
96                           2);
97
98     $form->{invpaid} += $form->{"paid_$i"};
99     $form->{datepaid} = $form->{"datepaid_$i"};
100
101   }
102
103   $form->{invpaid} =
104     $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
105
106   # # store invoice total, this goes into ap table
107   # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
108
109   # amount for total AP
110   $form->{payables} = $form->{invtotal};
111
112   # update exchangerate
113   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
114     $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
115                                $form->{exchangerate});
116   }
117
118   my ($query, $sth, @values);
119
120   if (!$payments_only) {
121     # if we have an id delete old records
122     if ($form->{id}) {
123
124       # delete detail records
125       $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
126       do_query($form, $dbh, $query, $form->{id});
127
128     } else {
129
130       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
131
132       $query =
133         qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
134         qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
135                       (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
136       do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
137
138     }
139
140     $query = qq|UPDATE ap SET invnumber = ?,
141                 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
142                 amount = ?, duedate = ?, deliverydate = ?, tax_point = ?, paid = ?, netamount = ?,
143                 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
144                 globalproject_id = ?, direct_debit = ?, payment_id = ?
145                WHERE id = ?|;
146     @values = ($form->{invnumber}, conv_date($form->{transdate}),
147                   $form->{ordnumber}, conv_i($form->{vendor_id}),
148                   $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
149                   conv_date($form->{duedate}), conv_date($form->{deliverydate}), conv_date($form->{tax_point}),
150                   $form->{invpaid}, $form->{netamount},
151                   $form->{currency}, $form->{notes},
152                   conv_i($form->{department_id}), $form->{storno},
153                   $form->{storno_id}, conv_i($form->{globalproject_id}),
154                   $form->{direct_debit} ? 't' : 'f',
155                   conv_i($form->{payment_id}),
156                   $form->{id});
157     do_query($form, $dbh, $query, @values);
158
159     $form->new_lastmtime('ap');
160
161     # Link this record to the record it was created from.
162     my $convert_from_oe_id = delete $form->{convert_from_oe_id};
163     if (!$form->{postasnew} && $convert_from_oe_id) {
164       RecordLinks->create_links('dbh'        => $dbh,
165                                 'mode'       => 'ids',
166                                 'from_table' => 'oe',
167                                 'from_ids'   => $convert_from_oe_id,
168                                 'to_table'   => 'ap',
169                                 'to_id'      => $form->{id},
170       );
171
172       # Close the record it was created from if the amount of
173       # all APs create from this record equals the records amount.
174       my @links = RecordLinks->get_links('dbh'        => $dbh,
175                                          'from_table' => 'oe',
176                                          'from_id'    => $convert_from_oe_id,
177                                          'to_table'   => 'ap',
178       );
179
180       my $amount_sum = sum0 map { SL::DB::PurchaseInvoice->new(id => $_->{to_id})->load->amount } @links;
181       my $order      = SL::DB::Order->new(id => $convert_from_oe_id)->load;
182
183       $order->update_attributes(closed => 1) if ($amount_sum - $order->amount) == 0;
184     }
185
186     # add individual transactions
187     for my $i (1 .. $form->{rowcount}) {
188       if ($form->{"amount_$i"} != 0) {
189         my $project_id;
190         $project_id = conv_i($form->{"project_id_$i"});
191
192         # insert detail records in acc_trans
193         $query =
194           qq|INSERT INTO acc_trans | .
195           qq|  (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
196           qq|VALUES (?, ?,   ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
197         @values = ($form->{id}, $form->{"AP_amount_chart_id_$i"},
198                    $form->{"amount_$i"}, conv_date($form->{transdate}),
199                    $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
200                    $form->{"AP_amount_chart_id_$i"});
201         do_query($form, $dbh, $query, @values);
202
203         if ($form->{"tax_$i"} != 0) {
204           # insert detail records in acc_trans
205           $query =
206             qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
207             qq|  project_id, taxkey, tax_id, chart_link) | .
208             qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
209             qq|  ?, ?, ?, ?, ?,| .
210             qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
211           @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
212                      $form->{"tax_$i"}, conv_date($form->{transdate}),
213                      $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
214                      $form->{AP_amounts}{"tax_$i"});
215           do_query($form, $dbh, $query, @values);
216         }
217
218       }
219     }
220
221     # add payables
222     $query =
223       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
224       qq|VALUES (?, ?, ?, ?, | .
225       qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
226       qq|        (SELECT tax_id| .
227       qq|         FROM taxkeys| .
228       qq|         WHERE chart_id = ?| .
229       qq|         AND startdate <= ?| .
230       qq|         ORDER BY startdate DESC LIMIT 1),| .
231       qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
232     @values = ($form->{id}, $form->{AP_chart_id}, $form->{payables},
233                conv_date($form->{transdate}), $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{transdate}),
234                $form->{AP_chart_id});
235     do_query($form, $dbh, $query, @values);
236   }
237
238   # if there is no amount but a payment record a payable
239   if ($form->{amount} == 0 && $form->{invtotal} == 0) {
240     $form->{payables} = $form->{invpaid};
241   }
242
243   my %already_cleared = %{ $params{already_cleared} // {} };
244
245   # add paid transactions
246   for my $i (1 .. $form->{paidaccounts}) {
247
248     if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
249       next;
250     }
251
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
279       my $new_cleared = !$form->{"acc_trans_id_$i"}                                                             ? 'f'
280                       : !$already_cleared{$form->{"acc_trans_id_$i"}}                                           ? 'f'
281                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $amount * -1                  ? 'f'
282                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno}  != $form->{"AP_paid_account_$i"} ? 'f'
283                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared}                                 ? 't'
284                       :                                                                                           'f';
285
286       if ($form->{payables}) {
287         $query =
288           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, cleared, taxkey, tax_id, chart_link) | .
289           qq|VALUES (?, ?, ?, ?, ?, ?, | .
290           qq|        (SELECT taxkey_id FROM chart WHERE id = ?),| .
291           qq|        (SELECT tax_id| .
292           qq|         FROM taxkeys| .
293           qq|         WHERE chart_id = ?| .
294           qq|         AND startdate <= ?| .
295           qq|         ORDER BY startdate DESC LIMIT 1),| .
296           qq|        (SELECT c.link FROM chart c WHERE c.id = ?))|;
297         @values = ($form->{id}, $form->{AP_chart_id}, $amount,
298                    conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared,
299                    $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{"datepaid_$i"}),
300                    $form->{AP_chart_id});
301         do_query($form, $dbh, $query, @values);
302       }
303       $form->{payables} = $amount;
304
305       # add payment
306       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
307       $query =
308         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, cleared, taxkey, tax_id, chart_link) | .
309         qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, ?, | .
310         qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
311         qq|        (SELECT tax_id| .
312         qq|         FROM taxkeys| .
313         qq|         WHERE chart_id= (SELECT id | .
314         qq|                          FROM chart| .
315         qq|                          WHERE accno = ?)| .
316         qq|         AND startdate <= ?| .
317         qq|         ORDER BY startdate DESC LIMIT 1),| .
318         qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
319       @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
320                  conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
321                  $form->{"memo_$i"}, $project_id, $new_cleared, $form->{"AP_paid_account_$i"},
322                  $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
323                  $form->{"AP_paid_account_$i"});
324       do_query($form, $dbh, $query, @values);
325
326       # add exchange rate difference
327       $amount =
328         $form->round_amount($form->{"paid_$i"} *
329                             ($form->{"exchangerate_$i"} - 1), 2);
330       if ($amount != 0) {
331         $query =
332           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
333           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
334           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?), | .
335           qq|        (SELECT tax_id| .
336           qq|         FROM taxkeys| .
337           qq|         WHERE chart_id= (SELECT id | .
338           qq|                          FROM chart| .
339           qq|                          WHERE accno = ?)| .
340           qq|         AND startdate <= ?| .
341           qq|         ORDER BY startdate DESC LIMIT 1),| .
342           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
343         @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
344                    conv_date($form->{"datepaid_$i"}), $project_id,
345                    $form->{"AP_paid_account_$i"},
346                    $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
347                    $form->{"AP_paid_account_$i"});
348         do_query($form, $dbh, $query, @values);
349       }
350
351       # exchangerate gain/loss
352       $amount =
353         $form->round_amount($form->{"paid_$i"} *
354                             ($form->{exchangerate} -
355                              $form->{"exchangerate_$i"}), 2);
356
357       if ($amount != 0) {
358         # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
359         if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
360           $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
361         };
362         if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
363           $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
364         };
365         die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
366         die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
367         $query =
368           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
369           qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
370           qq|        (SELECT taxkey_id FROM chart WHERE accno = ?),| .
371           qq|        (SELECT tax_id| .
372           qq|         FROM taxkeys| .
373           qq|         WHERE chart_id= (SELECT id | .
374           qq|                          FROM chart| .
375           qq|                          WHERE accno = ?)| .
376           qq|         AND startdate <= ?| .
377           qq|         ORDER BY startdate DESC LIMIT 1),| .
378           qq|        (SELECT c.link FROM chart c WHERE c.accno = ?))|;
379         @values = ($form->{id},
380                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
381                    $amount, conv_date($form->{"datepaid_$i"}), $project_id,
382                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
383                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
384                    ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
385         do_query($form, $dbh, $query, @values);
386       }
387
388       # update exchange rate record
389       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
390         $form->update_exchangerate($dbh, $form->{currency},
391                                    $form->{"datepaid_$i"},
392                                    0, $form->{"exchangerate_$i"});
393       }
394     }
395   }
396
397   if ($payments_only) {
398     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
399     do_query($form, $dbh, $query,  $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
400     $form->new_lastmtime('ap');
401   }
402
403   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
404
405   if ($form->{draft_id}) {
406     SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
407   }
408
409   # safety check datev export
410   if ($::instance_conf->get_datev_check_on_ap_transaction) {
411     my $datev = SL::DATEV->new(
412       dbh        => $dbh,
413       trans_id   => $form->{id},
414     );
415     $datev->generate_datev_data;
416
417     if ($datev->errors) {
418       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
419     }
420   }
421
422   return 1;
423 }
424
425 sub delete_transaction {
426   $main::lxdebug->enter_sub();
427
428   my ($self, $myconfig, $form) = @_;
429
430   SL::DB->client->with_transaction(sub {
431     my $query = qq|DELETE FROM ap WHERE id = ?|;
432     do_query($form, SL::DB->client->dbh, $query, $form->{id});
433     1;
434   }) or do { die SL::DB->client->error };
435
436   $main::lxdebug->leave_sub();
437
438   return 1;
439 }
440
441 sub ap_transactions {
442   $main::lxdebug->enter_sub();
443
444   my ($self, $myconfig, $form) = @_;
445
446   # connect to database
447   my $dbh = $form->get_standard_dbh($myconfig);
448
449   my $query =
450     qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
451     qq|  a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
452     qq|  a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
453     qq|  a.transaction_description, a.itime::DATE AS insertdate, | .
454     qq|  pr.projectnumber AS globalprojectnumber, | .
455     qq|  e.name AS employee, | .
456     qq|  v.vendornumber, v.country, v.ustid, | .
457     qq|  tz.description AS taxzone, | .
458     qq|  pt.description AS payment_terms, | .
459     qq|  department.description AS department, | .
460     qq{  ( SELECT ch.accno || ' -- ' || ch.description
461            FROM acc_trans at
462            LEFT JOIN chart ch ON ch.id = at.chart_id
463            WHERE ch.link ~ 'AP[[:>:]]'
464             AND at.trans_id = a.id
465             LIMIT 1
466           ) AS charts, } .
467     qq{  ( SELECT ch.accno || ' -- ' || ch.description
468            FROM acc_trans at
469            LEFT JOIN chart ch ON ch.id = at.chart_id
470            WHERE ch.link ~ 'AP_amount'
471             AND at.trans_id = a.id
472             LIMIT 1
473           ) AS debit_chart } .
474     qq|FROM ap a | .
475     qq|JOIN vendor v ON (a.vendor_id = v.id) | .
476     qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
477     qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
478     qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
479     qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
480     qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)| .
481     qq|LEFT JOIN department ON (department.id = a.department_id)|;
482
483   my $where = '';
484
485   my @values;
486
487   # Permissions:
488   # - Always return invoices & AP transactions for projects the employee has "view invoices" permissions for, no matter what the other rules say.
489   # - Exclude AP transactions if no permissions for them exist.
490   # - Limit to own invoices unless may edit all invoices.
491   # - If may edit all, allow filtering by employee.
492   my (@permission_where, @permission_values);
493
494   if ($::auth->assert('vendor_invoice_edit', 1)) {
495     if (!$::auth->assert('show_ap_transactions', 1)) {
496       push @permission_where, "NOT invoice = 'f'"; # remove ap transactions from Purchase -> Reports -> Invoices
497     }
498
499     if (!$::auth->assert('purchase_all_edit', 1)) {
500       # only show own invoices
501       push @permission_where,  "a.employee_id = ?";
502       push @permission_values, SL::DB::Manager::Employee->current->id;
503
504     } else {
505       if ($form->{employee_id}) {
506         push @permission_where,  "a.employee_id = ?";
507         push @permission_values, conv_i($form->{employee_id});
508       }
509     }
510   }
511
512   if (@permission_where || !$::auth->assert('vendor_invoice_edit', 1)) {
513     my $permission_where_str = @permission_where ? "OR (" . join(" AND ", map { "($_)" } @permission_where) . ")" : "";
514     $where .= qq|
515       AND (   (a.globalproject_id IN (
516                SELECT epi.project_id
517                FROM employee_project_invoices epi
518                WHERE epi.employee_id = ?))
519            $permission_where_str)
520     |;
521     push @values, SL::DB::Manager::Employee->current->id, @permission_values;
522   }
523
524   if ($form->{vendor}) {
525     $where .= " AND v.name ILIKE ?";
526     push(@values, like($form->{vendor}));
527   }
528   if ($form->{"cp_name"}) {
529     $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
530     push(@values, (like($form->{"cp_name"}))x2);
531   }
532   if ($form->{department_id}) {
533     $where .= " AND a.department_id = ?";
534     push(@values, $form->{department_id});
535   }
536   if ($form->{invnumber}) {
537     $where .= " AND a.invnumber ILIKE ?";
538     push(@values, like($form->{invnumber}));
539   }
540   if ($form->{ordnumber}) {
541     $where .= " AND a.ordnumber ILIKE ?";
542     push(@values, like($form->{ordnumber}));
543   }
544   if ($form->{transaction_description}) {
545     $where .= " AND a.transaction_description ILIKE ?";
546     push(@values, like($form->{transaction_description}));
547   }
548   if ($form->{notes}) {
549     $where .= " AND lower(a.notes) LIKE ?";
550     push(@values, like($form->{notes}));
551   }
552   if ($form->{project_id}) {
553     $where .=
554       qq| AND ((a.globalproject_id = ?) OR EXISTS | .
555       qq|  (SELECT * FROM invoice i | .
556       qq|   WHERE i.project_id = ? AND i.trans_id = a.id) | .
557       qq| OR EXISTS | .
558       qq|  (SELECT * FROM acc_trans at | .
559       qq|   WHERE at.project_id = ? AND at.trans_id = a.id)| .
560       qq|  )|;
561     push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
562   }
563
564   if ($form->{transdatefrom}) {
565     $where .= " AND a.transdate >= ?";
566     push(@values, trim($form->{transdatefrom}));
567   }
568   if ($form->{transdateto}) {
569     $where .= " AND a.transdate <= ?";
570     push(@values, trim($form->{transdateto}));
571   }
572   if ($form->{duedatefrom}) {
573     $where .= " AND a.duedate >= ?";
574     push(@values, trim($form->{duedatefrom}));
575   }
576   if ($form->{duedateto}) {
577     $where .= " AND a.duedate <= ?";
578     push(@values, trim($form->{duedateto}));
579   }
580   if ($form->{open} || $form->{closed}) {
581     unless ($form->{open} && $form->{closed}) {
582       $where .= " AND a.amount <> a.paid" if ($form->{open});
583       $where .= " AND a.amount = a.paid"  if ($form->{closed});
584     }
585   }
586
587   if ($form->{parts_partnumber}) {
588     $where .= <<SQL;
589  AND EXISTS (
590         SELECT invoice.trans_id
591         FROM invoice
592         LEFT JOIN parts ON (invoice.parts_id = parts.id)
593         WHERE (invoice.trans_id = a.id)
594           AND (parts.partnumber ILIKE ?)
595         LIMIT 1
596       )
597 SQL
598     push @values, like($form->{parts_partnumber});
599   }
600
601   if ($form->{parts_description}) {
602     $where .= <<SQL;
603  AND EXISTS (
604         SELECT invoice.trans_id
605         FROM invoice
606         WHERE (invoice.trans_id = a.id)
607           AND (invoice.description ILIKE ?)
608         LIMIT 1
609       )
610 SQL
611     push @values, like($form->{parts_description});
612   }
613
614   if ($where) {
615     $where  =~ s{\s*AND\s*}{ WHERE };
616     $query .= $where;
617   }
618
619   my @a = qw(transdate invnumber name);
620   push @a, "employee" if $form->{l_employee};
621   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
622   my $sortorder = join(', ', map { "$_ $sortdir" } @a);
623
624   if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit department))) {
625     $sortorder = $form->{sort} . " $sortdir";
626   }
627
628   $query .= " ORDER BY $sortorder";
629
630   my @result = selectall_hashref_query($form, $dbh, $query, @values);
631
632   $form->{AP} = [ @result ];
633
634   $main::lxdebug->leave_sub();
635 }
636
637 sub get_transdate {
638   $main::lxdebug->enter_sub();
639
640   my ($self, $myconfig, $form) = @_;
641
642   # connect to database
643   my $dbh = SL::DB->client->dbh;
644
645   my $query =
646     "SELECT COALESCE(" .
647     "  (SELECT transdate FROM ap WHERE id = " .
648     "    (SELECT MAX(id) FROM ap) LIMIT 1), " .
649     "  current_date)";
650   ($form->{transdate}) = $dbh->selectrow_array($query);
651
652   $main::lxdebug->leave_sub();
653 }
654
655 sub _delete_payments {
656   $main::lxdebug->enter_sub();
657
658   my ($self, $form, $dbh) = @_;
659
660   my @delete_acc_trans_ids;
661
662   # Delete old payment entries from acc_trans.
663   my $query =
664     qq|SELECT acc_trans_id
665        FROM acc_trans
666        WHERE (trans_id = ?) AND fx_transaction
667
668        UNION
669
670        SELECT at.acc_trans_id
671        FROM acc_trans at
672        LEFT JOIN chart c ON (at.chart_id = c.id)
673        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
674   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
675
676   $query =
677     qq|SELECT at.acc_trans_id
678        FROM acc_trans at
679        LEFT JOIN chart c ON (at.chart_id = c.id)
680        WHERE (trans_id = ?)
681          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
682        ORDER BY at.acc_trans_id
683        OFFSET 1|;
684   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
685
686   if (@delete_acc_trans_ids) {
687     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
688     do_query($form, $dbh, $query);
689   }
690
691   $main::lxdebug->leave_sub();
692 }
693
694 sub post_payment {
695   my ($self, $myconfig, $form, $locale) = @_;
696   $main::lxdebug->enter_sub();
697
698   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
699
700   $::lxdebug->leave_sub;
701   return $rc;
702 }
703
704 sub _post_payment {
705   my ($self, $myconfig, $form, $locale) = @_;
706
707   my $dbh = SL::DB->client->dbh;
708
709   my (%payments, $old_form, $row, $item, $query, %keep_vars);
710
711   $old_form = save_form();
712
713   $query = <<SQL;
714     SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
715     FROM acc_trans at
716     LEFT JOIN chart c ON (at.chart_id = c.id)
717     WHERE (at.trans_id = ?)
718 SQL
719
720   my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
721
722   # Delete all entries in acc_trans from prior payments.
723   if (SL::DB::Default->get->payments_changeable != 0) {
724     $self->_delete_payments($form, $dbh);
725   }
726
727   # Save the new payments the user made before cleaning up $form.
728   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$';
729   map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
730
731   # Clean up $form so that old content won't tamper the results.
732   %keep_vars = map { $_, 1 } qw(login password id);
733   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
734
735   # Retrieve the invoice from the database.
736   $form->create_links('AP', $myconfig, 'vendor', $dbh);
737
738   # Restore the payment options from the user input.
739   map { $form->{$_} = $payments{$_} } keys %payments;
740
741   # Set up the content of $form in the way that AR::post_transaction() expects.
742
743   $self->setup_form($form, 1);
744
745   $form->{exchangerate}    = $form->format_amount($myconfig, $form->{exchangerate});
746   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
747
748   # Get the AP accno.
749   $query =
750     qq|SELECT c.id
751        FROM acc_trans at
752        LEFT JOIN chart c ON (at.chart_id = c.id)
753        WHERE (trans_id = ?)
754          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
755        ORDER BY at.acc_trans_id
756        LIMIT 1|;
757
758   ($form->{AP_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
759
760   # Post the new payments.
761   $self->post_transaction($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
762
763   restore_form($old_form);
764
765   return 1;
766 }
767
768 sub setup_form {
769   $main::lxdebug->enter_sub();
770
771   my ($self, $form, $for_post_payments) = @_;
772
773   my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
774       $tax, $diff);
775
776   # forex
777   $form->{forex} = $form->{exchangerate};
778   $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
779
780   foreach $key (keys %{ $form->{AP_links} }) {
781     foreach $ref (@{ $form->{AP_links}{$key} }) {
782       if ($key eq "AP_paid") {
783         $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
784       } else {
785         $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
786       }
787     }
788
789     $form->{$key} = $form->{"select$key"};
790
791     $j = 0;
792     $k = 0;
793
794     # if there is a value we have an old entry
795     next unless $form->{acc_trans}{$key};
796
797     # do not use old entries for payments. They come from the form
798     # even if they are not changeable (then they are in hiddens)
799     next if $for_post_payments && $key eq "AP_paid";
800
801     for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
802
803       if ($key eq "AP_paid") {
804         $j++;
805         $form->{"AP_paid_$j"}         = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
806         $form->{"acc_trans_id_$j"}    = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
807         $form->{"paid_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{amount};
808         $form->{"datepaid_$j"}        = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
809         $form->{"gldate_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
810         $form->{"source_$j"}          = $form->{acc_trans}{$key}->[$i - 1]->{source};
811         $form->{"memo_$j"}            = $form->{acc_trans}{$key}->[$i - 1]->{memo};
812
813         $form->{"exchangerate_$i"}    = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
814         $form->{"forex_$j"}           = $form->{"exchangerate_$i"};
815         $form->{"AP_paid_$j"}         = $form->{acc_trans}{$key}->[$i-1]->{accno};
816         $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
817         $form->{paidaccounts}++;
818
819       } else {
820         $akey = $key;
821         $akey =~ s/AP_//;
822
823         if (($key eq "AP_tax") || ($key eq "AR_tax")) {
824           $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"}  = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
825           $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
826
827           if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
828             $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
829           } else {
830             $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
831             $withholdingrate  += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
832           }
833
834           $index                 = $form->{acc_trans}{$key}->[$i - 1]->{index};
835           $form->{"tax_$index"}  = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
836           $totaltax             += $form->{"tax_$index"};
837
838         } else {
839           $k++;
840           $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
841
842           if ($akey eq 'amount') {
843             $form->{rowcount}++;
844             $form->{"${akey}_$i"} *= -1;
845             $totalamount          += $form->{"${akey}_$i"};
846             $form->{taxrate}       = $form->{acc_trans}{$key}->[$i - 1]->{rate};
847
848             $form->{"projectnumber_$k"}    = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
849             $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
850             $form->{"project_id_$k"}       = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
851             $form->{"${key}_chart_id_$k"}  = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
852             $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id}    . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
853           }
854         }
855       }
856     }
857   }
858
859   $form->{paidaccounts} = 1            if not defined $form->{paidaccounts};
860
861   if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
862     # add tax to amounts and invtotal
863     for $i (1 .. $form->{rowcount}) {
864       $taxamount            = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
865       $tax                  = $form->round_amount($taxamount, 2);
866       $diff                += ($taxamount - $tax);
867       $form->{"amount_$i"} += $form->{"tax_$i"};
868     }
869
870     $form->{amount_1} += $form->round_amount($diff, 2);
871   }
872
873   $taxamount        = $form->round_amount($taxamount, 2);
874   $form->{invtotal} = $totalamount + $totaltax;
875
876   $main::lxdebug->leave_sub();
877 }
878
879 sub storno {
880   my ($self, $form, $myconfig, $id) = @_;
881   $main::lxdebug->enter_sub();
882
883   my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
884
885   $::lxdebug->leave_sub;
886   return $rc;
887 }
888
889 sub _storno {
890   my ($self, $form, $myconfig, $id) = @_;
891
892   my ($query, $new_id, $storno_row, $acc_trans_rows);
893   my $dbh = SL::DB->client->dbh;
894
895   $query = qq|SELECT nextval('glid')|;
896   ($new_id) = selectrow_query($form, $dbh, $query);
897
898   $query = qq|SELECT * FROM ap WHERE id = ?|;
899   $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
900
901   $storno_row->{id}         = $new_id;
902   $storno_row->{storno_id}  = $id;
903   $storno_row->{storno}     = 't';
904   $storno_row->{invnumber}  = 'Storno-' . $storno_row->{invnumber};
905   $storno_row->{amount}    *= -1;
906   $storno_row->{netamount} *= -1;
907   $storno_row->{paid}       = $storno_row->{amount};
908
909   delete @$storno_row{qw(itime mtime gldate)};
910
911   $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
912   do_query($form, $dbh, $query, (values %$storno_row));
913
914   $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
915   do_query($form, $dbh, $query, $id);
916
917   $form->new_lastmtime('ap') if $id == $form->{id};
918
919   # now copy acc_trans entries
920   $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|;
921   my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
922
923   # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
924   while ($rowref->[-1]{link} =~ /paid/) {
925     splice(@$rowref, -2);
926   }
927
928   for my $row (@$rowref) {
929     delete @$row{qw(itime mtime link acc_trans_id gldate)};
930     $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
931     $row->{trans_id}   = $new_id;
932     $row->{amount}    *= -1;
933     do_query($form, $dbh, $query, (values %$row));
934   }
935
936   map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);
937
938   return 1;
939 }
940
941 1;