1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
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.
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,
30 #======================================================================
32 # Accounts Payables database backend routines
34 #======================================================================
38 use SL::DATEV qw(:CONSTANTS);
46 use SL::DB::PurchaseInvoice;
47 use SL::DB::EmailJournal;
48 use SL::DB::ValidityToken;
49 use SL::Util qw(trim);
52 use List::Util qw(sum0);
56 sub post_transaction {
57 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
58 $main::lxdebug->enter_sub();
60 my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, %params);
62 $::lxdebug->leave_sub;
66 sub _post_transaction {
67 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
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},
76 die $::locale->text('The form is not valid anymore.') if !$validity_token;
79 my $payments_only = $params{payments_only};
80 my $dbh = $provided_dbh || SL::DB->client->dbh;
82 my ($null, $taxrate, $amount);
85 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
86 $form->{taxincluded} = 0 unless $form->{taxincluded};
87 $form->{script} = 'ap.pl' unless $form->{script};
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
95 # delete detail records
96 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
97 do_query($form, $dbh, $query, $form->{id});
101 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
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});
111 # check default or record exchangerate
112 if ($form->{currency} eq $form->{defaultcurrency}) {
113 $form->{exchangerate} = 1;
115 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
116 $form->{exchangerate} = $form->parse_amount($myconfig, $form->{exchangerate}, 5);
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"});
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');
131 # get the charts selected
132 $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
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});
137 # adjust paidaccounts if there is no date in the last row
138 $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
140 $form->{invpaid} = 0;
143 for my $i (1 .. $form->{paidaccounts}) {
145 $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
148 $form->{invpaid} += $form->{"paid_$i"};
149 $form->{datepaid} = $form->{"datepaid_$i"};
154 $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
156 # # store invoice total, this goes into ap table
157 # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
159 # amount for total AP
160 $form->{payables} = $form->{invtotal};
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 = ?,
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},
181 $form->{qrbill_data_encoded} ? uri_unescape($form->{qrbill_data_encoded}) : undef,
183 do_query($form, $dbh, $query, @values);
185 $form->new_lastmtime('ap');
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,
192 'from_table' => 'oe',
193 'from_ids' => $convert_from_oe_id,
195 'to_id' => $form->{id},
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,
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;
209 $order->update_attributes(closed => 1) if ($amount_sum - $order->amount) == 0;
212 # add individual transactions
213 for my $i (1 .. $form->{rowcount}) {
214 if ($form->{"amount_$i"} != 0) {
216 $project_id = conv_i($form->{"project_id_$i"});
218 # insert detail records in acc_trans
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);
229 if ($form->{"tax_$i"} != 0 && !$form->{"reverse_charge_$i"}) {
230 # insert detail records in acc_trans
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);
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| .
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);
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};
269 my %already_cleared = %{ $params{already_cleared} // {} };
271 # add paid transactions
272 for my $i (1 .. $form->{paidaccounts}) {
274 if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
278 if ($form->{"paid_$i"} != 0) {
279 my $project_id = conv_i($form->{"paid_project_id_$i"});
282 if ($form->{currency} eq $form->{defaultcurrency}) {
283 $form->{"exchangerate_$i"} = 1;
285 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
286 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
288 $form->{"AP_paid_$i"} =~ s/\"//g;
292 ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
293 $form->{"datepaid_$i"} = $form->{transdate}
294 unless ($form->{"datepaid_$i"});
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"};
302 $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
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'
312 if ($form->{payables}) {
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| .
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);
329 $form->{payables} = $amount;
332 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
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| .
339 qq| WHERE chart_id= (SELECT id | .
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);
352 # add exchange rate difference
354 $form->round_amount($form->{"paid_$i"} *
355 ($form->{"exchangerate_$i"} - 1), 2);
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| .
363 qq| WHERE chart_id= (SELECT id | .
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);
377 # exchangerate gain/loss
379 $form->round_amount($form->{"paid_$i"} *
380 ($form->{exchangerate} -
381 $form->{"exchangerate_$i"}), 2);
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;
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;
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};
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| .
399 qq| WHERE chart_id= (SELECT id | .
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);
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"});
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');
429 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
431 if ($form->{draft_id}) {
432 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
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(
441 trans_id => $form->{id},
443 $datev->generate_datev_data;
445 if ($datev->errors) {
446 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
450 $validity_token->delete if $validity_token;
451 delete $form->{form_validity_token};
456 sub _reverse_charge {
457 my ($self, $myconfig, $form) = @_;
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;
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} ]);
467 my ($i, $current_transaction);
469 for $i (1 .. $form->{rowcount}) {
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';
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);
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';
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
491 )->add_chart_booking(
492 chart => $tmptaxamount > 0 ? $debit : $credit,
493 debit => abs($tmptaxamount),
494 source => "Reverse Charge for " . $form->{invnumber},
496 )->add_chart_booking(
497 chart => $tmptaxamount > 0 ? $credit : $debit,
498 credit => abs($tmptaxamount),
499 source => "Reverse Charge for " . $form->{invnumber},
502 # add a stable link from ap to gl
504 ap_id => $form->{id},
505 gl_id => $current_transaction->id,
507 SL::DB::ApGl->new(%props_gl)->save;
508 # Record a record link from ap to gl
511 from_id => $form->{id},
513 to_id => $current_transaction->id,
515 SL::DB::RecordLink->new(%props_rl)->save;
519 sub delete_transaction {
520 $main::lxdebug->enter_sub();
522 my ($self, $myconfig, $form) = @_;
524 SL::DB->client->with_transaction(sub {
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;
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
536 my $query = qq|DELETE FROM ap WHERE id = ?|;
537 do_query($form, SL::DB->client->dbh, $query, $form->{id});
539 }) or do { die SL::DB->client->error };
541 $main::lxdebug->leave_sub();
546 sub ap_transactions {
547 $main::lxdebug->enter_sub();
549 my ($self, $myconfig, $form) = @_;
551 # connect to database
552 my $dbh = $form->get_standard_dbh($myconfig);
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
567 LEFT JOIN chart ch ON ch.id = at.chart_id
568 WHERE ch.link ~ 'AP[[:>:]]'
569 AND at.trans_id = a.id
572 qq{ ( SELECT ch.accno || ' -- ' || ch.description
574 LEFT JOIN chart ch ON ch.id = at.chart_id
575 WHERE ch.link ~ 'AP_amount'
576 AND at.trans_id = a.id
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)|;
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);
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
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;
610 if ($form->{employee_id}) {
611 push @permission_where, "a.employee_id = ?";
612 push @permission_values, conv_i($form->{employee_id});
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) . ")" : "";
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)
626 push @values, SL::DB::Manager::Employee->current->id, @permission_values;
629 if ($form->{vendor}) {
630 $where .= " AND v.name ILIKE ?";
631 push(@values, like($form->{vendor}));
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);
637 if ($form->{department_id}) {
638 $where .= " AND a.department_id = ?";
639 push(@values, $form->{department_id});
641 if ($form->{invnumber}) {
642 $where .= " AND a.invnumber ILIKE ?";
643 push(@values, like($form->{invnumber}));
645 if ($form->{ordnumber}) {
646 $where .= " AND a.ordnumber ILIKE ?";
647 push(@values, like($form->{ordnumber}));
649 if ($form->{taxzone_id}) {
650 $where .= " AND a.taxzone_id = ?";
651 push(@values, $form->{taxzone_id});
653 if ($form->{payment_id}) {
654 $where .= " AND a.payment_id = ?";
655 push(@values, $form->{payment_id});
657 if ($form->{transaction_description}) {
658 $where .= " AND a.transaction_description ILIKE ?";
659 push(@values, like($form->{transaction_description}));
661 if ($form->{notes}) {
662 $where .= " AND a.notes ILIKE ?";
663 push(@values, like($form->{notes}));
665 if ($form->{intnotes}) {
666 $where .= " AND a.intnotes ILIKE ?";
667 push(@values, like($form->{intnotes}));
669 if ($form->{project_id}) {
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) | .
675 qq| (SELECT * FROM acc_trans at | .
676 qq| WHERE at.project_id = ? AND at.trans_id = a.id)| .
678 push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
681 if ($form->{transdatefrom}) {
682 $where .= " AND a.transdate >= ?";
683 push(@values, trim($form->{transdatefrom}));
685 if ($form->{transdateto}) {
686 $where .= " AND a.transdate <= ?";
687 push(@values, trim($form->{transdateto}));
689 if ($form->{duedatefrom}) {
690 $where .= " AND a.duedate >= ?";
691 push(@values, trim($form->{duedatefrom}));
693 if ($form->{duedateto}) {
694 $where .= " AND a.duedate <= ?";
695 push(@values, trim($form->{duedateto}));
697 if ($form->{datepaidfrom}) {
698 $where .= " AND a.datepaid >= ?";
699 push(@values, trim($form->{datepaidfrom}));
701 if ($form->{datepaidto}) {
702 $where .= " AND a.datepaid <= ?";
703 push(@values, trim($form->{datepaidto}));
705 if ($form->{insertdatefrom}) {
706 $where .= " AND a.itime >= ?";
707 push(@values, trim($form->{insertdatefrom}));
709 if ($form->{insertdateto}) {
710 $where .= " AND a.itime <= ?";
711 push(@values, trim($form->{insertdateto}));
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});
720 $form->{fulltext} = trim($form->{fulltext});
721 if ($form->{fulltext}) {
722 my @fulltext_fields = qw(a.notes
725 a.transaction_description
730 $where .= join ' OR ', map {"$_ ILIKE ?"} @fulltext_fields;
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 ?)
738 $where .= ')'; # end AND
740 push(@values, like($form->{fulltext})) for 1 .. (scalar @fulltext_fields) + 1;
743 if ($form->{parts_partnumber}) {
746 SELECT invoice.trans_id
748 LEFT JOIN parts ON (invoice.parts_id = parts.id)
749 WHERE (invoice.trans_id = a.id)
750 AND (parts.partnumber ILIKE ?)
754 push @values, like($form->{parts_partnumber});
757 if ($form->{parts_description}) {
760 SELECT invoice.trans_id
762 WHERE (invoice.trans_id = a.id)
763 AND (invoice.description ILIKE ?)
767 push @values, like($form->{parts_description});
771 $where =~ s{\s*AND\s*}{ WHERE };
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);
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";
784 $query .= " ORDER BY $sortorder";
786 my @result = selectall_hashref_query($form, $dbh, $query, @values);
788 $form->{AP} = [ @result ];
790 if ($form->{l_items} && scalar @{ $form->{AP} }) {
791 my ($items_query, $items_sth);
792 if ($form->{l_items}) {
799 $items_sth = prepare_query($form, $dbh, $items_query);
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}};
807 $items_sth->finish();
810 $main::lxdebug->leave_sub();
814 $main::lxdebug->enter_sub();
816 my ($self, $myconfig, $form) = @_;
818 # connect to database
819 my $dbh = SL::DB->client->dbh;
823 " (SELECT transdate FROM ap WHERE id = " .
824 " (SELECT MAX(id) FROM ap) LIMIT 1), " .
826 ($form->{transdate}) = $dbh->selectrow_array($query);
828 $main::lxdebug->leave_sub();
831 sub _delete_payments {
832 $main::lxdebug->enter_sub();
834 my ($self, $form, $dbh) = @_;
836 my @delete_acc_trans_ids;
838 # Delete old payment entries from acc_trans.
840 qq|SELECT acc_trans_id
842 WHERE (trans_id = ?) AND fx_transaction
846 SELECT at.acc_trans_id
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}));
853 qq|SELECT at.acc_trans_id
855 LEFT JOIN chart c ON (at.chart_id = c.id)
857 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
858 ORDER BY at.acc_trans_id
860 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
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);
867 $main::lxdebug->leave_sub();
871 my ($self, $myconfig, $form, $locale) = @_;
872 $main::lxdebug->enter_sub();
874 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
876 $::lxdebug->leave_sub;
881 my ($self, $myconfig, $form, $locale) = @_;
883 my $dbh = SL::DB->client->dbh;
885 my (%payments, $old_form, $row, $item, $query, %keep_vars);
887 $old_form = save_form();
890 SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
892 LEFT JOIN chart c ON (at.chart_id = c.id)
893 WHERE (at.trans_id = ?)
896 my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
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);
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 };
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 };
911 # Retrieve the invoice from the database.
912 $form->create_links('AP', $myconfig, 'vendor', $dbh);
914 # Restore the payment options from the user input.
915 map { $form->{$_} = $payments{$_} } keys %payments;
917 # Set up the content of $form in the way that AR::post_transaction() expects.
919 $self->setup_form($form, 1);
921 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
922 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
928 LEFT JOIN chart c ON (at.chart_id = c.id)
930 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
931 ORDER BY at.acc_trans_id
934 ($form->{AP_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
936 # Post the new payments.
937 $self->post_transaction($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
939 restore_form($old_form);
945 $main::lxdebug->enter_sub();
947 my ($self, $form, $for_post_payments) = @_;
949 my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
953 $form->{forex} = $form->{exchangerate};
954 $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
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";
961 $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
965 $form->{$key} = $form->{"select$key"};
970 # if there is a value we have an old entry
971 next unless $form->{acc_trans}{$key};
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";
977 for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
979 if ($key eq "AP_paid") {
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};
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}++;
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);
1005 if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
1006 $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
1008 $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
1009 $withholdingrate += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
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"};
1018 $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
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};
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};
1037 $form->{paidaccounts} = 1 if not defined $form->{paidaccounts};
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"};
1048 $form->{amount_1} += $form->round_amount($diff, 2);
1051 $taxamount = $form->round_amount($taxamount, 2);
1052 $form->{invtotal} = $totalamount + $totaltax;
1054 $main::lxdebug->leave_sub();
1058 my ($self, $form, $myconfig, $id) = @_;
1059 $main::lxdebug->enter_sub();
1061 my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
1063 $::lxdebug->leave_sub;
1068 my ($self, $form, $myconfig, $id) = @_;
1070 my ($query, $new_id, $storno_row, $acc_trans_rows);
1071 my $dbh = SL::DB->client->dbh;
1073 $query = qq|SELECT nextval('glid')|;
1074 ($new_id) = selectrow_query($form, $dbh, $query);
1076 $query = qq|SELECT * FROM ap WHERE id = ?|;
1077 $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
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};
1087 delete @$storno_row{qw(itime mtime gldate)};
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));
1092 $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
1093 do_query($form, $dbh, $query, $id);
1095 $form->new_lastmtime('ap') if $id == $form->{id};
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);
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);
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));
1114 map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);
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}
1121 $email_journal->link_to_record_with_attachment(
1122 $ap_transaction_storno,
1123 delete $form->{workflow_email_attachment_id}
1125 $form->{callback} = delete $form->{workflow_email_callback};
1128 $form->{storno_id} = $id;