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 Receivable module backend routines
34 #======================================================================
39 use SL::DATEV qw(:CONSTANTS);
46 use SL::DB::EmailJournal;
47 use SL::DB::ValidityToken;
49 use SL::Util qw(trim);
54 sub post_transaction {
55 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
56 $main::lxdebug->enter_sub();
58 my $rc = SL::DB->client->with_transaction(\&_post_transaction, $self, $myconfig, $form, $provided_dbh, %params);
60 $::lxdebug->leave_sub;
64 sub _post_transaction {
65 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
69 $validity_token = SL::DB::Manager::ValidityToken->fetch_valid_token(
70 scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST(),
71 token => $form->{form_validity_token},
74 die $::locale->text('The form is not valid anymore.') if !$validity_token;
77 my $payments_only = $params{payments_only};
79 my ($query, $sth, $null, $taxrate, $amount, $tax);
82 $form->{script} = 'ar.pl' unless $form->{script};
86 my $dbh = $provided_dbh || SL::DB->client->dbh;
88 # if we have an id delete old records else make one
89 if (!$payments_only) {
91 # delete detail records
92 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
93 do_query($form, $dbh, $query, $form->{id});
96 $query = qq|SELECT nextval('glid')|;
97 ($form->{id}) = selectrow_query($form, $dbh, $query);
98 $query = qq|INSERT INTO ar (id, invnumber, employee_id, currency_id, taxzone_id) VALUES (?, 'dummy', ?, (SELECT id FROM currencies WHERE name=?), (SELECT taxzone_id FROM customer WHERE id = ?))|;
99 do_query($form, $dbh, $query, $form->{id}, $form->{employee_id}, $form->{currency}, $form->{customer_id});
100 if (!$form->{invnumber}) {
101 my $trans_number = SL::TransNumber->new(type => 'invoice', dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
102 $form->{invnumber} = $trans_number->create_unique;
107 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
108 # check default or record exchangerate
109 if ($form->{currency} eq $form->{defaultcurrency}) {
110 $form->{exchangerate} = 1;
112 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'buy');
113 $form->{exchangerate} = $form->parse_amount($myconfig, $form->{exchangerate}, 5);
115 # if default exchangerate is not defined, define one
116 unless ($exchangerate) {
117 $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate}, $form->{exchangerate}, 0);
118 # delete records exchangerate -> if user sets new invdate for record
119 $query = qq|UPDATE ar set exchangerate = NULL where id = ?|;
120 do_query($form, $dbh, $query, $form->{"id"});
122 # update record exchangerate, if the default is set and differs from current
123 if ($exchangerate && ($form->{exchangerate} != $exchangerate)) {
124 $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
125 $form->{exchangerate}, 0, $form->{id}, 'ar');
129 # get the charts selected
130 $form->{AR_amounts}{"amount_$_"} = $form->{"AR_amount_chart_id_$_"} for (1 .. $form->{rowcount});
132 $form->{tax} = 0; # is this still needed?
134 # main calculation of rowcount loop inside Form method, amount_$i and tax_$i get formatted
135 $form->{taxincluded} = 0 unless $form->{taxincluded};
136 ($form->{netamount},$form->{total_tax},$form->{amount}) = $form->calculate_arap('sell', $form->{taxincluded}, $form->{exchangerate});
138 # adjust paidaccounts if there is no date in the last row
139 # this does not apply to stornos, where the paid field is set manually
140 unless ($form->{storno}) {
141 $form->{paidaccounts}-- unless $form->{"datepaid_$form->{paidaccounts}"};
145 for $i (1 .. $form->{paidaccounts}) {
146 $form->{"paid_$i"} = $form->round_amount($form->parse_amount($myconfig, $form->{"paid_$i"}), 2);
147 $form->{paid} += $form->{"paid_$i"};
148 $form->{datepaid} = $form->{"datepaid_$i"};
152 $form->{paid} = $form->round_amount($form->{paid} * ($form->{exchangerate} || 1), 2);
154 $form->get_employee($dbh) unless $form->{employee_id};
158 # amount for AR account
159 $form->{receivables} = $form->round_amount($form->{amount}, 2) * -1;
161 if (!$payments_only) {
164 invnumber = ?, ordnumber = ?, transdate = ?, customer_id = ?,
165 taxincluded = ?, amount = ?, duedate = ?, deliverydate = ?, tax_point = ?, paid = ?,
166 currency_id = (SELECT id FROM currencies WHERE name = ?),
167 netamount = ?, notes = ?, department_id = ?,
168 employee_id = ?, storno = ?, storno_id = ?, globalproject_id = ?,
169 direct_debit = ?, transaction_description = ?
171 my @values = ($form->{invnumber}, $form->{ordnumber}, conv_date($form->{transdate}), conv_i($form->{customer_id}), $form->{taxincluded} ? 't' : 'f', $form->{amount},
172 conv_date($form->{duedate}), conv_date($form->{deliverydate}), conv_date($form->{tax_point}), $form->{paid},
174 $form->{netamount}, $form->{notes}, conv_i($form->{department_id}),
175 conv_i($form->{employee_id}), $form->{storno} ? 't' : 'f', $form->{storno_id},
176 conv_i($form->{globalproject_id}), $form->{direct_debit} ? 't' : 'f', $form->{transaction_description},
177 conv_i($form->{id}));
178 do_query($form, $dbh, $query, @values);
180 # add individual transactions for AR, amount and taxes
181 for $i (1 .. $form->{rowcount}) {
182 if ($form->{"amount_$i"} != 0) {
183 my $project_id = conv_i($form->{"project_id_$i"});
185 # insert detail records in acc_trans
186 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
187 VALUES (?, ?, ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.id = ?))|;
188 @values = (conv_i($form->{id}), $form->{AR_amounts}{"amount_$i"}, conv_i($form->{"amount_$i"}), conv_date($form->{transdate}), $project_id,
189 conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"amount_$i"});
190 do_query($form, $dbh, $query, @values);
192 if ($form->{"tax_$i"} != 0) {
193 # insert detail records in acc_trans
194 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey, tax_id, chart_link)
195 VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT c.link FROM chart c WHERE c.accno = ?))|;
196 @values = (conv_i($form->{id}), $form->{AR_amounts}{"tax_$i"}, conv_i($form->{"tax_$i"}), conv_date($form->{transdate}), $project_id,
197 conv_i($form->{"taxkey_$i"}), conv_i($form->{"tax_id_$i"}), $form->{AR_amounts}{"tax_$i"});
198 do_query($form, $dbh, $query, @values);
204 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link)
205 VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
210 ORDER BY startdate DESC LIMIT 1),
211 (SELECT c.link FROM chart c WHERE c.id = ?))|;
212 @values = (conv_i($form->{id}), $form->{AR_chart_id}, conv_i($form->{receivables}), conv_date($form->{transdate}),
213 $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{transdate}), $form->{AR_chart_id});
214 do_query($form, $dbh, $query, @values);
217 # Record paid amount.
218 $query = qq|UPDATE ar SET paid = ?, datepaid = ? WHERE id = ?|;
219 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
222 $form->new_lastmtime('ar');
224 my %already_cleared = %{ $params{already_cleared} // {} };
226 # add paid transactions
227 for my $i (1 .. $form->{paidaccounts}) {
229 if ($form->{"acc_trans_id_$i"} && $payments_only && (SL::DB::Default->get->payments_changeable == 0)) {
233 if ($form->{"paid_$i"} != 0) {
234 my $project_id = conv_i($form->{"paid_project_id_$i"});
236 $form->{"AR_paid_$i"} =~ s/\"//g;
237 ($form->{AR}{"paid_$i"}) = split(/--/, $form->{"AR_paid_$i"});
238 $form->{"datepaid_$i"} = $form->{transdate}
239 unless ($form->{"datepaid_$i"});
241 $form->{"exchangerate_$i"} = ($form->{currency} eq $form->{defaultcurrency}) ? 1 :
242 ( $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy') ||
243 $form->parse_amount($myconfig, $form->{"exchangerate_$i"}) );
245 # if there is no amount and invtotal is zero there is no exchangerate
246 $form->{exchangerate} = $form->{"exchangerate_$i"}
247 if ($form->{amount} == 0 && $form->{netamount} == 0);
249 my $new_cleared = !$form->{"acc_trans_id_$i"} ? 'f'
250 : !$already_cleared{$form->{"acc_trans_id_$i"}} ? 'f'
251 : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $form->{"paid_$i"} * -1 ? 'f'
252 : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno} != $form->{AR}{"paid_$i"} ? 'f'
253 : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared} ? 't'
257 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
261 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, cleared, taxkey, tax_id, chart_link)
262 VALUES (?, ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
267 ORDER BY startdate DESC LIMIT 1),
268 (SELECT c.link FROM chart c WHERE c.id = ?))|;
269 @values = (conv_i($form->{id}), $form->{AR_chart_id}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared,
270 $form->{AR_chart_id}, $form->{AR_chart_id}, conv_date($form->{"datepaid_$i"}), $form->{AR_chart_id});
272 do_query($form, $dbh, $query, @values);
275 if ($form->{"paid_$i"} != 0) {
277 my $project_id = conv_i($form->{"paid_project_id_$i"});
278 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
279 $amount = $form->{"paid_$i"} * -1;
280 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, project_id, cleared, taxkey, tax_id, chart_link)
281 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
284 WHERE chart_id= (SELECT id
288 ORDER BY startdate DESC LIMIT 1),
289 (SELECT c.link FROM chart c WHERE c.accno = ?))|;
290 @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $project_id, $new_cleared, $form->{AR}{"paid_$i"},
291 $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
292 do_query($form, $dbh, $query, @values);
294 # exchangerate difference for payment
295 $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) * -1, 2);
298 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
299 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
302 WHERE chart_id= (SELECT id
306 ORDER BY startdate DESC LIMIT 1),
307 (SELECT c.link FROM chart c WHERE c.accno = ?))|;
308 @values = (conv_i($form->{id}), $form->{AR}{"paid_$i"}, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AR}{"paid_$i"},
309 $form->{AR}{"paid_$i"}, conv_date($form->{"datepaid_$i"}), $form->{AR}{"paid_$i"});
310 do_query($form, $dbh, $query, @values);
313 # exchangerate gain/loss
314 $amount = $form->round_amount( $form->{"paid_$i"} * ($form->{exchangerate} - $form->{"exchangerate_$i"}) * -1, 2);
317 # fetch fxgain and fxloss chart info from defaults if charts aren't already filled in form
318 if ( !$form->{fxgain_accno} && $::instance_conf->get_fxgain_accno_id ) {
319 $form->{fxgain_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id)->accno;
321 if ( !$form->{fxloss_accno} && $::instance_conf->get_fxloss_accno_id ) {
322 $form->{fxloss_accno} = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id)->accno;
324 die "fxloss_accno missing" if $amount < 0 and not $form->{fxloss_accno};
325 die "fxgain_accno missing" if $amount > 0 and not $form->{fxgain_accno};
326 my $accno = ($amount > 0) ? $form->{fxgain_accno} : $form->{fxloss_accno};
327 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, fx_transaction, cleared, project_id, taxkey, tax_id, chart_link)
328 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, 't', 'f', ?, (SELECT taxkey_id FROM chart WHERE accno = ?),
331 WHERE chart_id= (SELECT id
335 ORDER BY startdate DESC LIMIT 1),
336 (SELECT c.link FROM chart c WHERE c.accno = ?))|;
337 @values = (conv_i($form->{id}), $accno, $amount, conv_date($form->{"datepaid_$i"}), $project_id, $accno, $accno, conv_date($form->{"datepaid_$i"}), $accno);
338 do_query($form, $dbh, $query, @values);
342 # update exchangerate record
343 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0)
344 if ($form->{currency} ne $form->{defaultcurrency}) && !$form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
348 IO->set_datepaid(table => 'ar', id => $form->{id}, dbh => $dbh);
350 if ($form->{draft_id}) {
351 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
354 # safety check datev export
355 if ($::instance_conf->get_datev_check_on_ar_transaction) {
356 my $datev = SL::DATEV->new(
358 trans_id => $form->{id},
361 $datev->generate_datev_data;
363 if ($datev->errors) {
364 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
368 $validity_token->delete if $validity_token;
369 delete $form->{form_validity_token};
374 sub _delete_payments {
375 $main::lxdebug->enter_sub();
377 my ($self, $form, $dbh) = @_;
379 my @delete_acc_trans_ids;
381 # Delete old payment entries from acc_trans.
383 qq|SELECT acc_trans_id
385 WHERE (trans_id = ?) AND fx_transaction
389 SELECT at.acc_trans_id
391 LEFT JOIN chart c ON (at.chart_id = c.id)
392 WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
393 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
396 qq|SELECT at.acc_trans_id
398 LEFT JOIN chart c ON (at.chart_id = c.id)
400 AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
401 ORDER BY at.acc_trans_id
403 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
405 if (@delete_acc_trans_ids) {
406 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
407 do_query($form, $dbh, $query);
410 $main::lxdebug->leave_sub();
414 my ($self, $myconfig, $form, $locale) = @_;
415 $main::lxdebug->enter_sub();
417 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
419 $::lxdebug->leave_sub;
424 my ($self, $myconfig, $form, $locale) = @_;
426 my $dbh = SL::DB->client->dbh;
428 my (%payments, $old_form, $row, $item, $query, %keep_vars);
430 $old_form = save_form();
433 SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
435 LEFT JOIN chart c ON (at.chart_id = c.id)
436 WHERE (at.trans_id = ?)
439 my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
441 # Delete all entries in acc_trans from prior payments.
442 if (SL::DB::Default->get->payments_changeable != 0) {
443 $self->_delete_payments($form, $dbh);
446 # Save the new payments the user made before cleaning up $form.
447 my $payments_re = '^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^paid_project_id_\d+$|^AR_paid_\d+$|^paidaccounts$';
448 map { $payments{$_} = $form->{$_} } grep m/$payments_re/, keys %{ $form };
450 # Clean up $form so that old content won't tamper the results.
451 %keep_vars = map { $_, 1 } qw(login password id);
452 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
454 # Retrieve the invoice from the database.
455 $form->create_links('AR', $myconfig, 'customer', $dbh);
457 # Restore the payment options from the user input.
458 map { $form->{$_} = $payments{$_} } keys %payments;
460 # Set up the content of $form in the way that AR::post_transaction() expects.
462 $self->setup_form($form, 1);
464 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
465 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
467 # Get the AR chart ID (which is normally done by Form::create_links()).
471 LEFT JOIN chart c ON (at.chart_id = c.id)
473 AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
474 ORDER BY at.acc_trans_id
477 ($form->{AR_chart_id}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
479 # Post the new payments.
480 $self->post_transaction($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
482 restore_form($old_form);
487 sub delete_transaction {
488 $main::lxdebug->enter_sub();
490 my ($self, $myconfig, $form) = @_;
492 SL::DB->client->with_transaction(sub {
493 # acc_trans entries are deleted by database triggers.
494 my $query = qq|DELETE FROM ar WHERE id = ?|;
495 do_query($form, SL::DB->client->dbh, $query, $form->{id});
497 }) or do { die SL::DB->client->error };
499 $main::lxdebug->leave_sub();
504 sub ar_transactions {
505 $main::lxdebug->enter_sub();
507 my ($self, $myconfig, $form) = @_;
509 # connect to database
510 my $dbh = $form->get_standard_dbh($myconfig);
515 qq|SELECT DISTINCT a.id, a.invnumber, a.ordnumber, a.cusordnumber, a.transdate, | .
516 qq| a.donumber, a.deliverydate, | .
517 qq| a.duedate, a.netamount, a.amount, a.paid, | .
518 qq| a.invoice, a.datepaid, a.notes, a.shipvia, | .
519 qq| a.shippingpoint, a.storno, a.storno_id, a.globalproject_id, | .
520 qq| a.marge_total, a.marge_percent, | .
521 qq| a.transaction_description, a.direct_debit, | .
523 qq| pr.projectnumber AS globalprojectnumber, | .
524 qq| c.name, c.customernumber, c.country, c.ustid, b.description as customertype, | .
525 qq| c.id as customer_id, c.dunning_lock as customer_dunning_lock,| .
526 qq| e.name AS employee, | .
527 qq| e2.name AS salesman, | .
528 qq| dc.dunning_description, | .
529 qq| tz.description AS taxzone, | .
530 qq| pt.description AS payment_terms, | .
531 qq| d.description AS department, | .
532 qq| s.shiptoname, s.shiptodepartment_1, s.shiptodepartment_2, | .
533 qq| s.shiptostreet, s.shiptozipcode, s.shiptocity, s.shiptocountry, | .
534 qq{ ( SELECT ch.accno || ' -- ' || ch.description
536 LEFT JOIN chart ch ON ch.id = at.chart_id
537 WHERE ch.link ~ 'AR[[:>:]]'
538 AND at.trans_id = a.id
542 qq|JOIN customer c ON (a.customer_id = c.id) | .
543 qq|LEFT JOIN contacts cp ON (a.cp_id = cp.cp_id) | .
544 qq|LEFT JOIN employee e ON (a.employee_id = e.id) | .
545 qq|LEFT JOIN employee e2 ON (a.salesman_id = e2.id) | .
546 qq|LEFT JOIN dunning_config dc ON (a.dunning_config_id = dc.id) | .
547 qq|LEFT JOIN project pr ON (a.globalproject_id = pr.id)| .
548 qq|LEFT JOIN tax_zones tz ON (tz.id = a.taxzone_id)| .
549 qq|LEFT JOIN payment_terms pt ON (pt.id = a.payment_id)| .
550 qq|LEFT JOIN business b ON (b.id = c.business_id)| .
551 qq|LEFT JOIN shipto s ON (
552 (a.shipto_id = s.shipto_id) or
553 (a.id = s.trans_id and s.module = 'AR')
555 qq|LEFT JOIN department d ON (d.id = a.department_id)|;
560 # - Always return invoices & AR transactions for projects the employee has "view invoices" permissions for, no matter what the other rules say.
561 # - Exclude AR transactions if no permissions for them exist.
562 # - Limit to own invoices unless may edit all invoices or view invoices is allowed.
563 # - If may edit all or view invoices is allowed, allow filtering by employee/salesman.
564 my (@permission_where, @permission_values);
566 if ($::auth->assert('invoice_edit', 1) || $::auth->assert('sales_invoice_view', 1)) {
567 if (!$::auth->assert('show_ar_transactions', 1) ) {
568 push @permission_where, "NOT invoice = 'f'"; # remove ar transactions from Sales -> Reports -> Invoices
571 if (!$::auth->assert('sales_all_edit', 1) && !$::auth->assert('sales_invoice_view', 1)) {
572 # only show own invoices
573 push @permission_where, "a.employee_id = ?";
574 push @permission_values, SL::DB::Manager::Employee->current->id;
577 if ($form->{employee_id}) {
578 push @permission_where, "a.employee_id = ?";
579 push @permission_values, conv_i($form->{employee_id});
581 if ($form->{salesman_id}) {
582 push @permission_where, "a.salesman_id = ?";
583 push @permission_values, conv_i($form->{salesman_id});
588 if (@permission_where || (!$::auth->assert('invoice_edit', 1) && !$::auth->assert('sales_invoice_view', 1))) {
589 my $permission_where_str = @permission_where ? "OR (" . join(" AND ", map { "($_)" } @permission_where) . ")" : "";
591 AND ( (a.globalproject_id IN (
592 SELECT epi.project_id
593 FROM employee_project_invoices epi
594 WHERE epi.employee_id = ?))
595 $permission_where_str)
597 push @values, SL::DB::Manager::Employee->current->id, @permission_values;
600 if ($form->{customer}) {
601 $where .= " AND c.name ILIKE ?";
602 push(@values, like($form->{customer}));
604 if ($form->{"cp_name"}) {
605 $where .= " AND (cp.cp_name ILIKE ? OR cp.cp_givenname ILIKE ?)";
606 push(@values, (like($form->{"cp_name"}))x2);
608 if ($form->{business_id}) {
609 my $business_id = $form->{business_id};
610 $where .= " AND c.business_id = ?";
611 push(@values, $business_id);
613 if ($form->{taxzone_id}) {
614 $where .= " AND a.taxzone_id = ?";
615 push(@values, $form->{taxzone_id});
617 if ($form->{department_id}) {
618 $where .= " AND a.department_id = ?";
619 push(@values, $form->{department_id});
621 if ($form->{payment_id}) {
622 $where .= " AND a.payment_id = ?";
623 push(@values, $form->{payment_id});
625 foreach my $column (qw(invnumber ordnumber cusordnumber notes transaction_description shipvia shippingpoint)) {
626 if ($form->{$column}) {
627 $where .= " AND a.$column ILIKE ?";
628 push(@values, like($form->{$column}));
631 if ($form->{"project_id"}) {
633 qq| AND ((a.globalproject_id = ?) OR EXISTS | .
634 qq| (SELECT * FROM invoice i | .
635 qq| WHERE i.project_id = ? AND i.trans_id = a.id) | .
637 qq| (SELECT * FROM acc_trans at | .
638 qq| WHERE at.project_id = ? AND at.trans_id = a.id)| .
640 push(@values, $form->{project_id}, $form->{project_id}, $form->{project_id});
643 if ($form->{transdatefrom}) {
644 $where .= " AND a.transdate >= ?";
645 push(@values, trim($form->{transdatefrom}));
647 if ($form->{transdateto}) {
648 $where .= " AND a.transdate <= ?";
649 push(@values, trim($form->{transdateto}));
651 if ($form->{duedatefrom}) {
652 $where .= " AND a.duedate >= ?";
653 push(@values, trim($form->{duedatefrom}));
655 if ($form->{duedateto}) {
656 $where .= " AND a.duedate <= ?";
657 push(@values, trim($form->{duedateto}));
659 if ($form->{datepaidfrom}) {
660 $where .= " AND a.datepaid >= ?";
661 push(@values, trim($form->{datepaidfrom}));
663 if ($form->{datepaidto}) {
664 $where .= " AND a.datepaid <= ?";
665 push(@values, trim($form->{datepaidto}));
667 if ($form->{open} || $form->{closed}) {
668 unless ($form->{open} && $form->{closed}) {
669 $where .= " AND a.amount <> a.paid" if ($form->{open});
670 $where .= " AND a.amount = a.paid" if ($form->{closed});
674 if ($form->{parts_partnumber}) {
677 SELECT invoice.trans_id
679 LEFT JOIN parts ON (invoice.parts_id = parts.id)
680 WHERE (invoice.trans_id = a.id)
681 AND (parts.partnumber ILIKE ?)
685 push @values, like($form->{parts_partnumber});
688 if ($form->{parts_description}) {
691 SELECT invoice.trans_id
693 WHERE (invoice.trans_id = a.id)
694 AND (invoice.description ILIKE ?)
698 push @values, like($form->{parts_description});
701 if ($form->{show_not_mailed}) {
706 WHERE (rl.from_id = a.id)
707 AND (rl.to_table = 'email_journal')
713 if ($form->{show_marked_as_closed}) {
716 SELECT SUM(acc_trans.amount) AS amount, trans_id
718 LEFT JOIN chart ON chart.id = chart_id
719 WHERE chart.link ILIKE ?
721 ) AS paid_difference ON (paid_difference.trans_id = a.id)
723 unshift @values, '%AR_paid%';
724 $where .= ' AND COALESCE(paid_difference.amount, 0) + a.paid != 0';
727 if ($form->{shiptoname}) {
728 $where .= " AND s.shiptoname ILIKE ?";
729 push(@values, like($form->{shiptoname}));
731 if ($form->{shiptodepartment_1}) {
732 $where .= " AND s.shiptodepartment_1 ILIKE ?";
733 push(@values, like($form->{shiptodepartment_1}));
735 if ($form->{shiptodepartment_2}) {
736 $where .= " AND s.shiptodepartment_2 ILIKE ?";
737 push(@values, like($form->{shiptodepartment_2}));
739 if ($form->{shiptostreet}) {
740 $where .= " AND s.shiptostreet ILIKE ?";
741 push(@values, like($form->{shiptostreet}));
743 if ($form->{shiptozipcode}) {
744 $where .= " AND s.shiptozipcode ILIKE ?";
745 push(@values, like($form->{shiptozipcode}));
747 if ($form->{shiptocity}) {
748 $where .= " AND s.shiptocity ILIKE ?";
749 push(@values, like($form->{shiptocity}));
751 if ($form->{shiptocountry}) {
752 $where .= " AND s.shiptocountry ILIKE ?";
753 push(@values, like($form->{shiptocountry}));
756 my ($cvar_where, @cvar_values) = CVar->build_filter_query('module' => 'CT',
757 'trans_id_field' => 'c.id',
761 $where .= qq| AND ($cvar_where)|;
762 push @values, @cvar_values;
765 my @a = qw(transdate invnumber name);
766 push @a, "employee" if $form->{l_employee};
767 my $sortdir = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
768 my $sortorder = join(', ', map { "$_ $sortdir" } @a);
770 if (grep({ $_ eq $form->{sort} } qw(id transdate duedate invnumber ordnumber cusordnumber donumber deliverydate name datepaid employee shippingpoint shipvia transaction_description department taxzone))) {
771 $sortorder = $form->{sort} . " $sortdir";
774 $query .= " WHERE $where ORDER BY $sortorder";
776 my @result = selectall_hashref_query($form, $dbh, $query, @values);
778 $form->{AR} = [ @result ];
780 if ($form->{l_items} && scalar @{ $form->{AR} }) {
781 my ($items_query, $items_sth);
782 if ($form->{l_items}) {
789 $items_sth = prepare_query($form, $dbh, $items_query);
792 foreach my $ar (@{ $form->{AR} }) {
793 do_statement($form, $items_sth, $items_query, $ar->{id});
794 $ar->{item_ids} = $dbh->selectcol_arrayref($items_sth);
795 $ar->{item_ids} = undef if !@{$ar->{item_ids}};
797 $items_sth->finish();
800 $main::lxdebug->leave_sub();
804 $main::lxdebug->enter_sub();
806 my ($self, $myconfig, $form) = @_;
808 # connect to database
809 my $dbh = SL::DB->client->dbh;
813 " (SELECT transdate FROM ar WHERE id = " .
814 " (SELECT MAX(id) FROM ar) LIMIT 1), " .
816 ($form->{transdate}) = $dbh->selectrow_array($query);
818 $main::lxdebug->leave_sub();
822 $main::lxdebug->enter_sub();
824 my ($self, $form, $for_post_payments) = @_;
826 my ($exchangerate, $akey, $j, $k, $index, $taxamount, $totaltax, $taxrate, $diff, $totalwithholding, $withholdingrate,
830 $form->{forex} = $form->{exchangerate};
831 $exchangerate = $form->{exchangerate} ? $form->{exchangerate} : 1;
833 # expected keys: AR, AR_paid, AR_tax, AR_amount
834 foreach my $key (keys %{ $form->{AR_links} }) {
838 # if there is a value we have an old entry
839 next unless $form->{acc_trans}{$key};
841 # do not use old entries for payments. They come from the form
842 # even if they are not changeable (then they are in hiddens)
843 next if $for_post_payments && $key eq "AR_paid";
845 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
846 if ($key eq "AR_paid") {
848 $form->{"AR_paid_$j"} = $form->{acc_trans}{$key}->[$i-1]->{accno};
850 $form->{"acc_trans_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
852 $form->{"paid_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
853 $form->{"datepaid_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
854 $form->{"gldate_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
855 $form->{"source_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
856 $form->{"memo_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
857 $form->{"forex_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
858 $form->{"exchangerate_$i"} = $form->{"forex_$j"};
859 $form->{"paid_project_id_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{project_id};
860 $form->{"defaultcurrency_paid_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{defaultcurrency_paid};
861 $form->{"fx_transaction_$j"} = $form->{acc_trans}{$key}->[$i - 1]->{fx_transaction};
862 $form->{paidaccounts}++;
864 } else { # e.g. AR_amount, AR, AR_tax
867 $akey =~ s/AR_//; # e.g. tax, amount, AR, used to store form key tax_$i, amount_$i, ...
869 if ($key eq "AR_tax" || $key eq "AP_tax") { # AR_tax
870 $form->{"${key}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
871 # determine the rounded tax amounts for each account, e.g. tax_1776
872 $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
874 # check e.g. $form->{1776_rate}, does this make sense for AR_tax charts? Is this ever valid? If it was, totaltax would be calculated twice
875 if ($form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"} > 0) {
876 $totaltax += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
877 $taxrate += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
880 $totalwithholding += $form->{"${akey}_$form->{acc_trans}{$key}->[$i-1]->{accno}"};
881 $withholdingrate += $form->{"$form->{acc_trans}{$key}->[$i-1]->{accno}_rate"};
884 $index = $form->{acc_trans}{$key}->[$i - 1]->{index};
885 $form->{"tax_$index"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2); # convert the tax_$i amounts
886 # currently totaltax is the sum of rounded tax amounts, is this correct?
887 $totaltax += $form->{"tax_$index"};
889 } else { # e.g. AR_amount, AR
891 $form->{"${akey}_$k"} = $form->round_amount($form->{acc_trans}{$key}->[$i - 1]->{amount} / $exchangerate, 2);
893 if ($akey eq 'amount') {
895 $totalamount += $form->{"${akey}_$i"};
897 $form->{"oldprojectnumber_$k"} = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
898 $form->{"projectnumber_$k"} = $form->{acc_trans}{$key}->[$i-1]->{projectnumber};
899 $form->{taxrate} = $form->{acc_trans}{$key}->[$i - 1]->{rate};
900 $form->{"project_id_$k"} = $form->{acc_trans}{$key}->[$i-1]->{project_id};
902 $form->{"${key}_chart_id_$k"} = $form->{acc_trans}{$key}->[$i-1]->{chart_id};
903 $form->{"taxchart_$k"} = $form->{acc_trans}{$key}->[$i-1]->{id} . "--" . $form->{acc_trans}{$key}->[$i-1]->{rate};
910 $form->{paidaccounts} = 1 if not defined $form->{paidaccounts};
912 if ($form->{taxincluded} && $form->{taxrate} && $totalamount) {
914 # add tax to amounts and invtotal
915 for my $i (1 .. $form->{rowcount}) {
916 $taxamount = ($totaltax + $totalwithholding) * $form->{"amount_$i"} / $totalamount;
917 $tax = $form->round_amount($taxamount, 2);
918 $diff += ($taxamount - $tax);
919 $form->{"amount_$i"} += $form->{"tax_$i"};
921 $form->{amount_1} += $form->round_amount($diff, 2);
924 $taxamount = $form->round_amount($taxamount, 2);
925 $form->{tax} = $taxamount;
927 $form->{invtotal} = $totalamount + $totaltax;
929 $main::lxdebug->leave_sub();
933 my ($self, $form, $myconfig, $id) = @_;
934 $main::lxdebug->enter_sub();
936 my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
938 $::lxdebug->leave_sub;
944 my ($self, $form, $myconfig, $id) = @_;
946 my ($query, $new_id, $storno_row, $acc_trans_rows);
947 my $dbh = SL::DB->client->dbh;
949 $query = qq|SELECT nextval('glid')|;
950 ($new_id) = selectrow_query($form, $dbh, $query);
952 $query = qq|SELECT * FROM ar WHERE id = ?|;
953 $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
955 $storno_row->{id} = $new_id;
956 $storno_row->{storno_id} = $id;
957 $storno_row->{storno} = 't';
958 $storno_row->{invnumber} = 'Storno-' . $storno_row->{invnumber};
959 $storno_row->{amount} *= -1;
960 $storno_row->{netamount} *= -1;
961 $storno_row->{paid} = $storno_row->{amount};
963 delete @$storno_row{qw(itime mtime)};
965 $query = sprintf 'INSERT INTO ar (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
966 do_query($form, $dbh, $query, (values %$storno_row));
968 $query = qq|UPDATE ar SET paid = amount + paid, storno = 't' WHERE id = ?|;
969 do_query($form, $dbh, $query, $id);
971 $form->new_lastmtime('ar') if $id == $form->{id};
973 # now copy acc_trans entries
974 $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|;
975 my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
977 # kill all entries containing payments, which are the last 2n rows, of which the last has link =~ /paid/
978 while ($rowref->[-1]{link} =~ /paid/) {
979 splice(@$rowref, -2);
982 for my $row (@$rowref) {
983 delete @$row{qw(itime mtime link acc_trans_id)};
984 $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
985 $row->{trans_id} = $new_id;
986 $row->{amount} *= -1;
987 do_query($form, $dbh, $query, (values %$row));
990 map { IO->set_datepaid(table => 'ar', id => $_, dbh => $dbh) } ($id, $new_id);
992 if ($form->{workflow_email_journal_id}) {
993 my $ar_transaction_storno = SL::DB::Invoice->new(id => $new_id)->load;
994 my $email_journal = SL::DB::EmailJournal->new(
995 id => delete $form->{workflow_email_journal_id}
997 $email_journal->link_to_record_with_attachment(
998 $ar_transaction_storno,
999 delete $form->{workflow_email_attachment_id}
1001 $form->{callback} = delete $form->{workflow_email_callback};
1004 $form->{storno_id} = $id;