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