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