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