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);
44 use SL::Util qw(trim);
50 sub post_transaction {
51 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
52 $main::lxdebug->enter_sub();
54 my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, %params);
56 $::lxdebug->leave_sub;
60 sub _post_transaction {
61 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
63 my $payments_only = $params{payments_only};
64 my $dbh = $provided_dbh || SL::DB->client->dbh;
66 my ($null, $taxrate, $amount);
69 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
70 $form->{taxincluded} = 0 unless $form->{taxincluded};
72 if ($form->{currency} eq $form->{defaultcurrency}) {
73 $form->{exchangerate} = 1;
75 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
76 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
79 # get the charts selected
80 $form->{AP_amounts}{"amount_$_"} = $form->{"AP_amount_chart_id_$_"} for (1 .. $form->{rowcount});
82 # calculate the totals while calculating and reformatting the $amount_$i and $tax_$i
83 ($form->{netamount},$form->{total_tax},$form->{invtotal}) = $form->calculate_arap('buy',$form->{taxincluded}, $form->{exchangerate});
85 # adjust paidaccounts if there is no date in the last row
86 $form->{paidaccounts}-- unless ($form->{"datepaid_$form->{paidaccounts}"});
91 for my $i (1 .. $form->{paidaccounts}) {
93 $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}),
96 $form->{invpaid} += $form->{"paid_$i"};
97 $form->{datepaid} = $form->{"datepaid_$i"};
102 $form->round_amount($form->{invpaid} * $form->{exchangerate}, 2);
104 # # store invoice total, this goes into ap table
105 # $form->{invtotal} = $form->{netamount} + $form->{total_tax};
107 # amount for total AP
108 $form->{payables} = $form->{invtotal};
110 # update exchangerate
111 if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
112 $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, 0,
113 $form->{exchangerate});
116 my ($query, $sth, @values);
118 if (!$payments_only) {
119 # if we have an id delete old records
122 # delete detail records
123 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
124 do_query($form, $dbh, $query, $form->{id});
128 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
131 qq|INSERT INTO ap (id, invnumber, employee_id,currency_id, taxzone_id) | .
132 qq|VALUES (?, ?, (SELECT e.id FROM employee e WHERE e.login = ?),
133 (SELECT id FROM currencies WHERE name = ?), (SELECT taxzone_id FROM vendor WHERE id = ?) )|;
134 do_query($form, $dbh, $query, $form->{id}, $form->{invnumber}, $::myconfig{login}, $form->{currency}, $form->{vendor_id});
138 $query = qq|UPDATE ap SET invnumber = ?,
139 transdate = ?, ordnumber = ?, vendor_id = ?, taxincluded = ?,
140 amount = ?, duedate = ?, paid = ?, netamount = ?,
141 currency_id = (SELECT id FROM currencies WHERE name = ?), notes = ?, department_id = ?, storno = ?, storno_id = ?,
142 globalproject_id = ?, direct_debit = ?
144 @values = ($form->{invnumber}, conv_date($form->{transdate}),
145 $form->{ordnumber}, conv_i($form->{vendor_id}),
146 $form->{taxincluded} ? 't' : 'f', $form->{invtotal},
147 conv_date($form->{duedate}), $form->{invpaid},
149 $form->{currency}, $form->{notes},
150 conv_i($form->{department_id}), $form->{storno},
151 $form->{storno_id}, conv_i($form->{globalproject_id}),
152 $form->{direct_debit} ? 't' : 'f',
154 do_query($form, $dbh, $query, @values);
156 $form->new_lastmtime('ap');
158 # add individual transactions
159 for my $i (1 .. $form->{rowcount}) {
160 if ($form->{"amount_$i"} != 0) {
162 $project_id = conv_i($form->{"project_id_$i"});
164 # insert detail records in acc_trans
166 qq|INSERT INTO acc_trans | .
167 qq| (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)| .
168 qq|VALUES (?, ?, ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
169 @values = ($form->{id}, $form->{"AP_amount_chart_id_$i"},
170 $form->{"amount_$i"}, conv_date($form->{transdate}),
171 $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
172 $form->{"AP_amount_chart_id_$i"});
173 do_query($form, $dbh, $query, @values);
175 if ($form->{"tax_$i"} != 0) {
176 # insert detail records in acc_trans
178 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, | .
179 qq| project_id, taxkey, tax_id, chart_link) | .
180 qq|VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), | .
181 qq| ?, ?, ?, ?, ?,| .
182 qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
183 @values = ($form->{id}, $form->{AP_amounts}{"tax_$i"},
184 $form->{"tax_$i"}, conv_date($form->{transdate}),
185 $project_id, $form->{"taxkey_$i"}, conv_i($form->{"tax_id_$i"}),
186 $form->{AP_amounts}{"tax_$i"});
187 do_query($form, $dbh, $query, @values);
195 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) | .
196 qq|VALUES (?, ?, ?, ?, | .
197 qq| (SELECT taxkey_id FROM chart WHERE id = ?),| .
198 qq| (SELECT tax_id| .
200 qq| WHERE chart_id = ?| .
201 qq| AND startdate <= ?| .
202 qq| ORDER BY startdate DESC LIMIT 1),| .
203 qq| (SELECT c.link FROM chart c WHERE c.id = ?))|;
204 @values = ($form->{id}, $form->{AP_chart_id}, $form->{payables},
205 conv_date($form->{transdate}), $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{transdate}),
206 $form->{AP_chart_id});
207 do_query($form, $dbh, $query, @values);
210 # if there is no amount but a payment record a payable
211 if ($form->{amount} == 0 && $form->{invtotal} == 0) {
212 $form->{payables} = $form->{invpaid};
215 my %already_cleared = %{ $params{already_cleared} // {} };
217 # add paid transactions
218 for my $i (1 .. $form->{paidaccounts}) {
220 if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
224 if ($form->{"paid_$i"} != 0) {
225 my $project_id = conv_i($form->{"paid_project_id_$i"});
228 if ($form->{currency} eq $form->{defaultcurrency}) {
229 $form->{"exchangerate_$i"} = 1;
231 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
232 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
234 $form->{"AP_paid_$i"} =~ s/\"//g;
238 ($form->{"AP_paid_account_$i"}) = split(/--/, $form->{"AP_paid_$i"});
239 $form->{"datepaid_$i"} = $form->{transdate}
240 unless ($form->{"datepaid_$i"});
242 # if there is no amount and invtotal is zero there is no exchangerate
243 if ($form->{amount} == 0 && $form->{invtotal} == 0) {
244 $form->{exchangerate} = $form->{"exchangerate_$i"};
248 $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} * -1,
251 my $new_cleared = !$form->{"acc_trans_id_$i"} ? 'f'
252 : !$already_cleared{$form->{"acc_trans_id_$i"}} ? 'f'
253 : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $amount * -1 ? 'f'
254 : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno} != $form->{"AP_paid_account_$i"} ? 'f'
255 : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared} ? 't'
258 if ($form->{payables}) {
260 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, cleared, taxkey, tax_id, chart_link) | .
261 qq|VALUES (?, ?, ?, ?, ?, ?, | .
262 qq| (SELECT taxkey_id FROM chart WHERE id = ?),| .
263 qq| (SELECT tax_id| .
265 qq| WHERE chart_id = ?| .
266 qq| AND startdate <= ?| .
267 qq| ORDER BY startdate DESC LIMIT 1),| .
268 qq| (SELECT c.link FROM chart c WHERE c.id = ?))|;
269 @values = ($form->{id}, $form->{AP_chart_id}, $amount,
270 conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared,
271 $form->{AP_chart_id}, $form->{AP_chart_id}, conv_date($form->{"datepaid_$i"}),
272 $form->{AP_chart_id});
273 do_query($form, $dbh, $query, @values);
275 $form->{payables} = $amount;
278 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
280 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, cleared, taxkey, tax_id, chart_link) | .
281 qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, ?, | .
282 qq| (SELECT taxkey_id FROM chart WHERE accno = ?), | .
283 qq| (SELECT tax_id| .
285 qq| WHERE chart_id= (SELECT id | .
287 qq| WHERE accno = ?)| .
288 qq| AND startdate <= ?| .
289 qq| ORDER BY startdate DESC LIMIT 1),| .
290 qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
291 @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $form->{"paid_$i"},
292 conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"},
293 $form->{"memo_$i"}, $project_id, $new_cleared, $form->{"AP_paid_account_$i"},
294 $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
295 $form->{"AP_paid_account_$i"});
296 do_query($form, $dbh, $query, @values);
298 # add exchange rate difference
300 $form->round_amount($form->{"paid_$i"} *
301 ($form->{"exchangerate_$i"} - 1), 2);
304 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
305 qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
306 qq| (SELECT taxkey_id FROM chart WHERE accno = ?), | .
307 qq| (SELECT tax_id| .
309 qq| WHERE chart_id= (SELECT id | .
311 qq| WHERE accno = ?)| .
312 qq| AND startdate <= ?| .
313 qq| ORDER BY startdate DESC LIMIT 1),| .
314 qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
315 @values = ($form->{id}, $form->{"AP_paid_account_$i"}, $amount,
316 conv_date($form->{"datepaid_$i"}), $project_id,
317 $form->{"AP_paid_account_$i"},
318 $form->{"AP_paid_account_$i"}, conv_date($form->{"datepaid_$i"}),
319 $form->{"AP_paid_account_$i"});
320 do_query($form, $dbh, $query, @values);
323 # exchangerate gain/loss
325 $form->round_amount($form->{"paid_$i"} *
326 ($form->{exchangerate} -
327 $form->{"exchangerate_$i"}), 2);
330 # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
331 if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
332 $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
334 if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
335 $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
337 die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
338 die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
340 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link) | .
341 qq|VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, | .
342 qq| (SELECT taxkey_id FROM chart WHERE accno = ?),| .
343 qq| (SELECT tax_id| .
345 qq| WHERE chart_id= (SELECT id | .
347 qq| WHERE accno = ?)| .
348 qq| AND startdate <= ?| .
349 qq| ORDER BY startdate DESC LIMIT 1),| .
350 qq| (SELECT c.link FROM chart c WHERE c.accno = ?))|;
351 @values = ($form->{id},
352 ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
353 $amount, conv_date($form->{"datepaid_$i"}), $project_id,
354 ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno},
355 ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno}, conv_date($form->{"datepaid_$i"}),
356 ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno});
357 do_query($form, $dbh, $query, @values);
360 # update exchange rate record
361 if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
362 $form->update_exchangerate($dbh, $form->{currency},
363 $form->{"datepaid_$i"},
364 0, $form->{"exchangerate_$i"});
369 if ($payments_only) {
370 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
371 do_query($form, $dbh, $query, $form->{invpaid}, $form->{invpaid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
372 $form->new_lastmtime('ap');
375 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
377 if ($form->{draft_id}) {
378 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
381 # safety check datev export
382 if ($::instance_conf->get_datev_check_on_ap_transaction) {
383 my $datev = SL::DATEV->new(
385 trans_id => $form->{id},
387 $datev->generate_datev_data;
389 if ($datev->errors) {
390 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
397 sub delete_transaction {
398 $main::lxdebug->enter_sub();
400 my ($self, $myconfig, $form) = @_;
402 SL::DB->client->with_transaction(sub {
403 my $query = qq|DELETE FROM ap WHERE id = ?|;
404 do_query($form, SL::DB->client->dbh, $query, $form->{id});
406 }) or do { die SL::DB->client->error };
408 $main::lxdebug->leave_sub();
413 sub ap_transactions {
414 $main::lxdebug->enter_sub();
416 my ($self, $myconfig, $form) = @_;
418 # connect to database
419 my $dbh = $form->get_standard_dbh($myconfig);
422 qq|SELECT a.id, a.invnumber, a.transdate, a.duedate, a.amount, a.paid, | .
423 qq| a.ordnumber, v.name, a.invoice, a.netamount, a.datepaid, a.notes, | .
424 qq| a.globalproject_id, a.storno, a.storno_id, a.direct_debit, | .
425 qq| pr.projectnumber AS globalprojectnumber, | .
426 qq| e.name AS employee, | .
427 qq| v.vendornumber, v.country, v.ustid, | .
428 qq| tz.description AS taxzone, | .
429 qq| pt.description AS payment_terms, | .
430 qq{ ( SELECT ch.accno || ' -- ' || ch.description
432 LEFT JOIN chart ch ON ch.id = at.chart_id
433 WHERE ch.link ~ 'AP[[:>:]]'
434 AND at.trans_id = a.id
438 qq|JOIN vendor v ON (a.vendor_id = v.id) | .
439 qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
440 qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
441 qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id) | .
442 qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
443 qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)|;
450 # - Always return invoices & AP transactions for projects the employee has "view invoices" permissions for, no matter what the other rules say.
451 # - Exclude AP transactions if no permissions for them exist.
452 # - Filter by employee if requested.
453 my (@permission_where, @permission_values);
455 if ($::auth->assert('vendor_invoice_edit', 1)) {
456 if (!$::auth->assert('show_ap_transactions', 1)) {
457 push @permission_where, "NOT invoice = 'f'"; # remove ap transactions from Purchase -> Reports -> Invoices
460 if ($form->{employee_id}) {
461 push @permission_where, "a.employee_id = ?";
462 push @permission_values, conv_i($form->{employee_id});
466 if (@permission_where || !$::auth->assert('vendor_invoice_edit', 1)) {
467 my $permission_where_str = @permission_where ? "OR (" . join(" AND ", map { "($_)" } @permission_where) . ")" : "";
469 AND ( (a.globalproject_id IN (
470 SELECT epi.project_id
471 FROM employee_project_invoices epi
472 WHERE epi.employee_id = ?))
473 $permission_where_str)
475 push @values, SL::DB::Manager::Employee->current->id, @permission_values;
478 if ($form->{vendor}) {
479 $where .= " AND v.name ILIKE ?";
480 push(@values, like($form->{vendor}));
482 if ($form->{"cp_name"}) {
483 $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
484 push(@values, (like($form->{"cp_name"}))x2);
486 if ($form->{department_id}) {
487 $where .= " AND a.department_id = ?";
488 push(@values, $form->{department_id});
490 if ($form->{invnumber}) {
491 $where .= " AND a.invnumber ILIKE ?";
492 push(@values, like($form->{invnumber}));
494 if ($form->{ordnumber}) {
495 $where .= " AND a.ordnumber ILIKE ?";
496 push(@values, like($form->{ordnumber}));
498 if ($form->{notes}) {
499 $where .= " AND lower(a.notes) LIKE ?";
500 push(@values, like($form->{notes}));
502 if ($form->{project_id}) {
504 qq| AND ((a.globalproject_id = ?) OR EXISTS | .
505 qq| (SELECT * FROM invoice i | .
506 qq| WHERE i.project_id = ? AND i.trans_id = a.id) | .
508 qq| (SELECT * FROM acc_trans at | .
509 qq| WHERE at.project_id = ? AND at.trans_id = a.id)| .
511 push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
514 if ($form->{transdatefrom}) {
515 $where .= " AND a.transdate >= ?";
516 push(@values, trim($form->{transdatefrom}));
518 if ($form->{transdateto}) {
519 $where .= " AND a.transdate <= ?";
520 push(@values, trim($form->{transdateto}));
522 if ($form->{open} || $form->{closed}) {
523 unless ($form->{open} && $form->{closed}) {
524 $where .= " AND a.amount <> a.paid" if ($form->{open});
525 $where .= " AND a.amount = a.paid" if ($form->{closed});
529 if ($form->{parts_partnumber}) {
532 SELECT invoice.trans_id
534 LEFT JOIN parts ON (invoice.parts_id = parts.id)
535 WHERE (invoice.trans_id = a.id)
536 AND (parts.partnumber ILIKE ?)
540 push @values, like($form->{parts_partnumber});
543 if ($form->{parts_description}) {
546 SELECT invoice.trans_id
548 WHERE (invoice.trans_id = a.id)
549 AND (invoice.description ILIKE ?)
553 push @values, like($form->{parts_description});
557 $where =~ s{\s*AND\s*}{ WHERE };
561 my @a = qw(transdate invnumber name);
562 push @a, "employee" if $form->{l_employee};
563 my $sortdir = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
564 my $sortorder = join(', ', map { "$_ $sortdir" } @a);
566 if (grep({ $_ eq $form->{sort} } qw(transdate id invnumber ordnumber name netamount tax amount paid datepaid due duedate notes employee transaction_description direct_debit))) {
567 $sortorder = $form->{sort} . " $sortdir";
570 $query .= " ORDER BY $sortorder";
572 my @result = selectall_hashref_query($form, $dbh, $query, @values);
574 $form->{AP} = [ @result ];
576 $main::lxdebug->leave_sub();
580 $main::lxdebug->enter_sub();
582 my ($self, $myconfig, $form) = @_;
584 # connect to database
585 my $dbh = SL::DB->client->dbh;
589 " (SELECT transdate FROM ap WHERE id = " .
590 " (SELECT MAX(id) FROM ap) LIMIT 1), " .
592 ($form->{transdate}) = $dbh->selectrow_array($query);
594 $main::lxdebug->leave_sub();
597 sub _delete_payments {
598 $main::lxdebug->enter_sub();
600 my ($self, $form, $dbh) = @_;
602 my @delete_acc_trans_ids;
604 # Delete old payment entries from acc_trans.
606 qq|SELECT acc_trans_id
608 WHERE (trans_id = ?) AND fx_transaction
612 SELECT at.acc_trans_id
614 LEFT JOIN chart c ON (at.chart_id = c.id)
615 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
616 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
619 qq|SELECT at.acc_trans_id
621 LEFT JOIN chart c ON (at.chart_id = c.id)
623 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
624 ORDER BY at.acc_trans_id
626 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
628 if (@delete_acc_trans_ids) {
629 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
630 do_query($form, $dbh, $query);
633 $main::lxdebug->leave_sub();
637 my ($self, $myconfig, $form, $locale) = @_;
638 $main::lxdebug->enter_sub();
640 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
642 $::lxdebug->leave_sub;
647 my ($self, $myconfig, $form, $locale) = @_;
649 my $dbh = SL::DB->client->dbh;
651 my (%payments, $old_form, $row, $item, $query, %keep_vars);
653 $old_form = save_form();
656 SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
658 LEFT JOIN chart c ON (at.chart_id = c.id)
659 WHERE (at.trans_id = ?)
662 my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
664 # Delete all entries in acc_trans from prior payments.
665 if (SL::DB::Default->get->payments_changeable != 0) {
666 $self->_delete_payments($form, $dbh);
669 # Save the new payments the user made before cleaning up $form.
670 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$';
671 map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
673 # Clean up $form so that old content won't tamper the results.
674 %keep_vars = map { $_, 1 } qw(login password id);
675 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
677 # Retrieve the invoice from the database.
678 $form->create_links('AP', $myconfig, 'vendor', $dbh);
680 # Restore the payment options from the user input.
681 map { $form->{$_} = $payments{$_} } keys %payments;
683 # Set up the content of $form in the way that AR::post_transaction() expects.
685 $self->setup_form($form, 1);
687 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
688 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
694 LEFT JOIN chart c ON (at.chart_id = c.id)
696 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
697 ORDER BY at.acc_trans_id
700 ($form->{AP_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
702 # Post the new payments.
703 $self->post_transaction($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
705 restore_form($old_form);
711 $main::lxdebug->enter_sub();
713 my ($self, $form, $for_post_payments) = @_;
715 my ($exchangerate, $i, $j, $k, $key, $akey, $ref, $index, $taxamount, $totalamount, $totaltax, $totalwithholding, $withholdingrate,
719 $form->{forex} = $form->{exchangerate};
720 $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
722 foreach $key (keys %{ $form->{AP_links} }) {
723 foreach $ref (@{ $form->{AP_links}{$key} }) {
724 if ($key eq "AP_paid") {
725 $form->{"select$key"} .= "<option value=\"$ref->{accno}\">$ref->{accno}--$ref->{description}</option>\n";
727 $form->{"select$key"} .= "<option value=\"$ref->{accno}--$ref->{tax_id}\">$ref->{accno}--$ref->{description}</option>\n";
731 $form->{$key} = $form->{"select$key"};
736 # if there is a value we have an old entry
737 next unless $form->{acc_trans}{$key};
739 # do not use old entries for payments. They come from the form
740 # even if they are not changeable (then they are in hiddens)
741 next if $for_post_payments && $key eq "AP_paid";
743 for $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
745 if ($key eq "AP_paid") {
747 $form->{"AP_paid_$j"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
748 $form->{"acc_trans_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
749 $form->{"paid_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{amount};
750 $form->{"datepaid_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
751 $form->{"gldate_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
752 $form->{"source_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
753 $form->{"memo_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
755 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
756 $form->{"forex_$j"} = $form->{"exchangerate_$i"};
757 $form->{"AP_paid_$j"} = $form->{acc_trans}{$key}->[$i-1]->{accno};
758 $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
759 $form->{paidaccounts}++;
765 if (($key eq "AP_tax") || ($key eq "AR_tax")) {
766 $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
767 $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
769 if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
770 $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
772 $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
773 $withholdingrate += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
776 $index = $form->{acc_trans}{$key}->[$i - 1]->{index};
777 $form->{"tax_$index"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} * -1 / $exchangerate, 2);
778 $totaltax += $form->{"tax_$index"};
782 $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
784 if ($akey eq 'amount') {
786 $form->{"${akey}_$i"} *= -1;
787 $totalamount += $form->{"${akey}_$i"};
788 $form->{taxrate} = $form->{acc_trans}{$key}->[$i - 1]->{rate};
790 $form->{"projectnumber_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{projectnumber}";
791 $form->{"oldprojectnumber_$k"} = $form->{"projectnumber_$k"};
792 $form->{"project_id_$k"} = "$form->{acc_trans}{$key}->[$i-1]->{project_id}";
793 $form->{"${key}_chart_id_$k"} = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
794 $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id} . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
801 $form->{paidaccounts} = 1 if not defined $form->{paidaccounts};
803 if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
804 # add tax to amounts and invtotal
805 for $i (1 .. $form->{rowcount}) {
806 $taxamount = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
807 $tax = $form->round_amount($taxamount, 2);
808 $diff += ($taxamount - $tax);
809 $form->{"amount_$i"} += $form->{"tax_$i"};
812 $form->{amount_1} += $form->round_amount($diff, 2);
815 $taxamount = $form->round_amount($taxamount, 2);
816 $form->{invtotal} = $totalamount + $totaltax;
818 $main::lxdebug->leave_sub();
822 my ($self, $form, $myconfig, $id) = @_;
823 $main::lxdebug->enter_sub();
825 my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
827 $::lxdebug->leave_sub;
832 my ($self, $form, $myconfig, $id) = @_;
834 my ($query, $new_id, $storno_row, $acc_trans_rows);
835 my $dbh = SL::DB->client->dbh;
837 $query = qq|SELECT nextval('glid')|;
838 ($new_id) = selectrow_query($form, $dbh, $query);
840 $query = qq|SELECT * FROM ap WHERE id = ?|;
841 $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
843 $storno_row->{id} = $new_id;
844 $storno_row->{storno_id} = $id;
845 $storno_row->{storno} = 't';
846 $storno_row->{invnumber} = 'Storno-' . $storno_row->{invnumber};
847 $storno_row->{amount} *= -1;
848 $storno_row->{netamount} *= -1;
849 $storno_row->{paid} = $storno_row->{amount};
851 delete @$storno_row{qw(itime mtime)};
853 $query = sprintf 'INSERT INTO ap (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
854 do_query($form, $dbh, $query, (values %$storno_row));
856 $query = qq|UPDATE ap SET paid = amount + paid, storno = 't' WHERE id = ?|;
857 do_query($form, $dbh, $query, $id);
859 $form->new_lastmtime('ap') if $id == $form->{id};
861 # now copy acc_trans entries
862 $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|;
863 my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
865 # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
866 while ($rowref->[-1]{link} =~ /paid/) {
867 splice(@$rowref, -2);
870 for my $row (@$rowref) {
871 delete @$row{qw(itime mtime link acc_trans_id)};
872 $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
873 $row->{trans_id} = $new_id;
874 $row->{amount} *= -1;
875 do_query($form, $dbh, $query, (values %$row));
878 map { IO->set_datepaid(table => 'ap', id => $_, dbh => $dbh) } ($id, $new_id);