1 #======================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
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 # Dunning process module
34 #======================================================================
44 use SL::GenericTranslations;
52 use SL::Util qw(trim);
57 use File::Slurp qw(read_file);
62 $main::lxdebug->enter_sub();
64 my ($self, $myconfig, $form) = @_;
67 my $dbh = SL::DB->client->dbh;
71 qq|FROM dunning_config | .
72 qq|ORDER BY dunning_level|;
73 $form->{DUNNING} = selectall_hashref_query($form, $dbh, $query);
75 foreach my $ref (@{ $form->{DUNNING} }) {
76 $ref->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
77 $ref->{interest_rate} = $form->format_amount($myconfig, ($ref->{interest_rate} * 100));
81 qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar, dunning_creator
83 ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}, $form->{dunning_creator})
84 = selectrow_query($form, $dbh, $query);
86 $main::lxdebug->leave_sub();
90 my ($self, $myconfig, $form) = @_;
91 $main::lxdebug->enter_sub();
93 my $rc = SL::DB->client->with_transaction(\&_save_config, $self, $myconfig, $form);
95 $::lxdebug->leave_sub;
100 my ($self, $myconfig, $form) = @_;
102 my $dbh = SL::DB->client->dbh;
104 my ($query, @values);
106 for my $i (1 .. $form->{rowcount}) {
107 $form->{"fee_$i"} = $form->parse_amount($myconfig, $form->{"fee_$i"}) * 1;
108 $form->{"interest_rate_$i"} = $form->parse_amount($myconfig, $form->{"interest_rate_$i"}) / 100;
110 if (($form->{"dunning_level_$i"} ne "") &&
111 ($form->{"dunning_description_$i"} ne "")) {
112 @values = (conv_i($form->{"dunning_level_$i"}), $form->{"dunning_description_$i"},
113 $form->{"email_subject_$i"}, $form->{"email_body_$i"},
114 $form->{"template_$i"}, $form->{"fee_$i"}, $form->{"interest_rate_$i"},
115 $form->{"active_$i"} ? 't' : 'f', $form->{"auto_$i"} ? 't' : 'f', $form->{"email_$i"} ? 't' : 'f',
116 $form->{"email_attachment_$i"} ? 't' : 'f', conv_i($form->{"payment_terms_$i"}), conv_i($form->{"terms_$i"}),
117 $form->{"create_invoices_for_fees_$i"} ? 't' : 'f',
118 $form->{"print_original_invoice_$i"} ? 't' : 'f');
119 if ($form->{"id_$i"}) {
121 qq|UPDATE dunning_config SET
122 dunning_level = ?, dunning_description = ?,
123 email_subject = ?, email_body = ?,
124 template = ?, fee = ?, interest_rate = ?,
125 active = ?, auto = ?, email = ?,
126 email_attachment = ?, payment_terms = ?, terms = ?,
127 create_invoices_for_fees = ?,
128 print_original_invoice = ?
130 push(@values, conv_i($form->{"id_$i"}));
133 qq|INSERT INTO dunning_config
134 (dunning_level, dunning_description, email_subject, email_body,
135 template, fee, interest_rate, active, auto, email,
136 email_attachment, payment_terms, terms, create_invoices_for_fees,
137 print_original_invoice)
138 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
140 do_query($form, $dbh, $query, @values);
143 if (($form->{"dunning_description_$i"} eq "") && ($form->{"id_$i"})) {
144 $query = qq|DELETE FROM dunning_config WHERE id = ?|;
145 do_query($form, $dbh, $query, $form->{"id_$i"});
149 $query = qq|UPDATE defaults SET dunning_ar_amount_fee = ?, dunning_ar_amount_interest = ?, dunning_ar = ?,
150 dunning_creator = ?|;
151 @values = (conv_i($form->{AR_amount_fee}), conv_i($form->{AR_amount_interest}), conv_i($form->{AR}),
152 $form->{dunning_creator});
153 do_query($form, $dbh, $query, @values);
158 sub create_invoice_for_fees {
159 $main::lxdebug->enter_sub();
161 my ($self, $myconfig, $form, $dbh, $dunning_id) = @_;
163 my ($query, @values, $sth, $ref);
165 $query = qq|SELECT dcfg.create_invoices_for_fees
167 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
168 WHERE d.dunning_id = ?|;
169 my ($create_invoices_for_fees) = selectrow_query($form, $dbh, $query, $dunning_id);
171 if (!$create_invoices_for_fees) {
172 $main::lxdebug->leave_sub();
176 $query = qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar FROM defaults|;
177 ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}) = selectrow_query($form, $dbh, $query);
183 SELECT MAX(d_fee.fee)
185 WHERE (d_fee.trans_id = d.trans_id)
186 AND (d_fee.dunning_id <> ?)
187 AND NOT (d_fee.fee_interest_ar_id ISNULL)
192 SELECT MAX(d_interest.interest)
193 FROM dunning d_interest
194 WHERE (d_interest.trans_id = d.trans_id)
195 AND (d_interest.dunning_id <> ?)
196 AND NOT (d_interest.fee_interest_ar_id ISNULL)
198 AS max_previous_interest,
201 WHERE dunning_id = ?|;
202 @values = ($dunning_id, $dunning_id, $dunning_id);
203 $sth = prepare_execute_query($form, $dbh, $query, @values);
205 my ($fee_remaining, $interest_remaining) = (0, 0);
206 my ($fee_total, $interest_total) = (0, 0);
210 while (my $ref = $sth->fetchrow_hashref()) {
211 $fee_remaining += $form->round_amount($ref->{fee}, 2);
212 $fee_remaining -= $form->round_amount($ref->{max_previous_fee}, 2);
213 $fee_total += $form->round_amount($ref->{fee}, 2);
214 $interest_remaining += $form->round_amount($ref->{interest}, 2);
215 $interest_remaining -= $form->round_amount($ref->{max_previous_interest}, 2);
216 $interest_total += $form->round_amount($ref->{interest}, 2);
217 push @link_ids, $ref->{link_id};
222 my $amount = $fee_remaining + $interest_remaining;
225 $main::lxdebug->leave_sub();
229 my ($ar_id) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
230 my $curr = $form->get_default_currency($myconfig);
231 my $trans_number = SL::TransNumber->new(type => 'invoice', dbh => $dbh);
234 qq|INSERT INTO ar (id, invnumber, transdate, gldate, customer_id,
235 taxincluded, amount, netamount, paid, duedate,
236 invoice, currency_id, taxzone_id, notes,
241 current_date, -- transdate
242 current_date, -- gldate
244 (SELECT ar.customer_id
246 LEFT JOIN ar ON (dn.trans_id = ar.id)
247 WHERE dn.dunning_id = ?
254 (SELECT duedate FROM dunning WHERE dunning_id = ? LIMIT 1),
256 (SELECT id FROM currencies WHERE name = ?), -- curr
258 (SELECT taxzone_id FROM customer WHERE id =
259 (SELECT ar.customer_id
261 LEFT JOIN ar ON (dn.trans_id = ar.id)
262 WHERE dn.dunning_id = ?
267 (SELECT id FROM employee WHERE login = ?)
269 @values = ($ar_id, # id
270 $trans_number->create_unique, # invnumber
271 $dunning_id, # customer_id
274 $dunning_id, # duedate
275 $curr, # default currency
276 $dunning_id, # taxzone_id
277 sprintf($main::locale->text('Automatically created invoice for fee and interest for dunning %s'), $dunning_id), # notes
278 $::myconfig{login}); # employee_id
279 do_query($form, $dbh, $query, @values);
281 RecordLinks->create_links(
284 'from_table' => 'dunning',
285 'from_ids' => \@link_ids,
291 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, taxkey, tax_id, chart_link)
292 VALUES (?, ?, ?, current_date, current_date, 0,
293 (SELECT id FROM tax WHERE (taxkey = 0) AND (rate = 0)),
294 (SELECT link FROM chart WHERE id = ?))|;
295 $sth = prepare_query($form, $dbh, $query);
297 @values = ($ar_id, conv_i($form->{AR_amount_fee}), $fee_remaining, conv_i($form->{AR_amount_fee}));
298 do_statement($form, $sth, $query, @values);
300 if ($interest_remaining) {
301 @values = ($ar_id, conv_i($form->{AR_amount_interest}), $interest_remaining, conv_i($form->{AR_amount_interest}));
302 do_statement($form, $sth, $query, @values);
305 @values = ($ar_id, conv_i($form->{AR}), -1 * $amount, conv_i($form->{AR}));
306 do_statement($form, $sth, $query, @values);
310 $query = qq|UPDATE dunning SET fee_interest_ar_id = ? WHERE dunning_id = ?|;
311 do_query($form, $dbh, $query, $ar_id, $dunning_id);
313 $main::lxdebug->leave_sub();
318 my ($self, $myconfig, $form, $rows) = @_;
319 $main::lxdebug->enter_sub();
321 $form->{DUNNING_PDFS_STORAGE} = [];
323 # Catch any error, either exception or a call to form->error
324 # and return it to the calling function.
327 local $form->{__ERROR_HANDLER} = sub { die @_ };
328 $rc = SL::DB->client->with_transaction(\&_save_dunning, $self, $myconfig, $form, $rows);
334 # Save PDFs in filemanagement and webdav after transation succeeded,
335 # because otherwise files in the storage may exists if the transaction
336 # failed. Ignore all errros.
337 # Todo: Maybe catch errros and display them as warnings or non fatal errors in the status.
338 if (!$error && $form->{DUNNING_PDFS_STORAGE} && scalar @{ $form->{DUNNING_PDFS_STORAGE} }) {
339 _store_pdf_to_webdav_and_filemanagement($_->{dunning_id}, $_->{path}, $_->{name}) for @{ $form->{DUNNING_PDFS_STORAGE} };
342 $error = 'unknown errror' if !$error && !$rc;
343 $rc->{error} = $error if $error;
345 $::lxdebug->leave_sub;
352 my ($self, $myconfig, $form, $rows) = @_;
354 my $dbh = SL::DB->client->dbh;
356 my ($query, @values);
358 my ($dunning_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
360 my $q_update_ar = qq|UPDATE ar SET dunning_config_id = ? WHERE id = ?|;
361 my $h_update_ar = prepare_query($form, $dbh, $q_update_ar);
363 my $q_insert_dunning =
364 qq|INSERT INTO dunning (id, dunning_id, dunning_config_id, dunning_level, trans_id,
365 fee, interest, transdate, duedate, original_invoice_printed)
367 (SELECT dunning_level FROM dunning_config WHERE id = ?),
371 WHERE dunning_level <= (SELECT dunning_level FROM dunning_config WHERE id = ?)),
372 (SELECT (amount - paid) * (current_date - duedate) FROM ar WHERE id = ?)
373 * (SELECT interest_rate FROM dunning_config WHERE id = ?)
376 current_date + (SELECT payment_terms FROM dunning_config WHERE id = ?),
378 my $h_insert_dunning = prepare_query($form, $dbh, $q_insert_dunning);
381 my ($next_dunning_config_id, $customer_id);
382 my ($send_email, $print_invoice) = (0, 0);
384 foreach my $row (@{ $rows }) {
385 if ($row->{credit_note}) {
387 %{ $form->{LIST_CREDIT_NOTES}{$row->{customer_id}}{$row->{invoice_id}} } = (
388 open_amount => $form->{"open_amount_$i"},
389 amount => $form->{"amount_$i"},
390 invnumber => $form->{"invnumber_$i"},
391 invdate => $form->{"invdate_$i"},
395 push @invoice_ids, $row->{invoice_id};
396 $next_dunning_config_id = $row->{next_dunning_config_id};
397 $customer_id = $row->{customer_id};
399 @values = ($row->{next_dunning_config_id}, $row->{invoice_id});
400 do_statement($form, $h_update_ar, $q_update_ar, @values);
402 $send_email |= $row->{email};
403 $print_invoice |= $row->{print_invoice};
405 my ($row_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
406 my $next_config_id = conv_i($row->{next_dunning_config_id});
407 my $invoice_id = conv_i($row->{invoice_id});
409 @values = ($row_id, $dunning_id, $next_config_id,
410 $next_config_id, $invoice_id, $next_config_id,
411 $invoice_id, $next_config_id, $next_config_id,
413 do_statement($form, $h_insert_dunning, $q_insert_dunning, @values);
415 RecordLinks->create_links(
418 'from_table' => 'ar',
419 'from_ids' => $invoice_id,
420 'to_table' => 'dunning',
424 # die this transaction, because for this customer only credit notes are
426 die "only credit notes are selected for this customer\n" unless $customer_id;
428 $h_update_ar->finish();
429 $h_insert_dunning->finish();
431 $form->{DUNNING_PDFS_EMAIL} = [];
433 $form->{dunning_id} = $dunning_id;
435 $self->create_invoice_for_fees($myconfig, $form, $dbh, $dunning_id);
437 $self->print_invoice_for_fees($myconfig, $form, $dunning_id, $dbh);
438 $self->print_dunning($myconfig, $form, $dunning_id, $dbh);
440 if ($print_invoice) {
441 $self->print_original_invoice($myconfig, $form, $dunning_id, $_) for @invoice_ids;
445 $self->send_email($myconfig, $form, $dunning_id, $dbh);
448 return ({dunning_id => $dunning_id, print_original_invoice => $print_invoice, send_email => $send_email});
452 $main::lxdebug->enter_sub();
454 my ($self, $myconfig, $form, $dunning_id, $dbh) = @_;
458 dcfg.email_body, dcfg.email_subject, dcfg.email_attachment,
459 COALESCE (NULLIF(c.invoice_mail, ''), c.email) AS recipient, c.name,
460 (SELECT login from employee where id = ar.employee_id) as invoice_employee_login
462 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
463 LEFT JOIN ar ON (d.trans_id = ar.id)
464 LEFT JOIN customer c ON (ar.customer_id = c.id)
465 WHERE (d.dunning_id = ?)
467 my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
469 # without a recipient, we cannot send a mail
470 if (!$ref || !$ref->{recipient}) {
471 $main::lxdebug->leave_sub();
472 die $main::locale->text("No email recipient for customer #1 defined.", $ref->{name});
475 # without a sender we cannot send a mail
476 # two cases: check mail from 1. current user OR 2. employee who created the invoice
478 if ($::instance_conf->get_dunning_creator eq 'current_employee') {
479 $from = $myconfig->{email};
480 die $main::locale->text('No email for current user #1 defined.', $myconfig->{name}) unless $from;
483 $from = SL::DB::Manager::AuthUser->find_by(login => $ref->{invoice_employee_login})->get_config_value("email");
484 $sign = SL::DB::Manager::AuthUser->find_by(login => $ref->{invoice_employee_login})->get_config_value("signature");
487 } or die $main::locale->text('No email for user with login #1 defined.', $ref->{invoice_employee_login});
490 my $html_template = SL::Template::create(type => 'HTML', form => $form, myconfig => $myconfig);
491 $html_template->set_tag_style('<%', '%>');
493 my $template = SL::Template::create(type => 'PlainText', form => $form, myconfig => $myconfig);
494 my $mail = Mailer->new();
495 $mail->{bcc} = $form->get_bcc_defaults($myconfig, $form->{bcc});
496 $mail->{from} = $from;
497 $mail->{to} = $ref->{recipient};
498 $mail->{subject} = $template->parse_block($ref->{email_subject});
499 $mail->{message} = $html_template->parse_block($ref->{email_body});
500 $mail->{content_type} = 'text/html';
501 my $sign_backup = $::myconfig{signature};
502 $::myconfig{signature} = $sign if $sign;
503 $mail->{message} .= $form->create_email_signature();
504 $::myconfig{signature} = $sign_backup if $sign;
506 $mail->{message} =~ s/\r\n/\n/g;
508 if ($ref->{email_attachment} && @{ $form->{DUNNING_PDFS_EMAIL} }) {
509 $mail->{attachments} = $form->{DUNNING_PDFS_EMAIL};
512 $query = qq|SELECT id FROM dunning WHERE dunning_id = ?|;
513 my @ids = selectall_array_query($form, $dbh, $query, $dunning_id);
514 $mail->{record_id} = \@ids;
515 $mail->{record_type} = 'dunning';
519 $main::lxdebug->leave_sub();
522 sub set_template_options {
523 $main::lxdebug->enter_sub();
525 my ($self, $myconfig, $form) = @_;
527 my $defaults = SL::DB::Default->get;
528 $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
529 $form->{templates} = $defaults->templates;
530 $form->{language} = $form->get_template_language($myconfig);
531 $form->{printer_code} = $form->get_printer_code($myconfig);
533 if ($form->{language} ne "") {
534 $form->{language} = "_" . $form->{language};
537 if ($form->{printer_code} ne "") {
538 $form->{printer_code} = "_" . $form->{printer_code};
541 my $extension = 'html';
542 if ($form->{format} eq 'postscript') {
543 $form->{postscript} = 1;
546 } elsif ($form->{"format"} =~ /pdf/) {
548 $extension = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
550 } elsif ($form->{"format"} =~ /opendocument/) {
551 $form->{opendocument} = 1;
553 } elsif ($form->{"format"} =~ /excel/) {
559 # search for the template
561 push @template_files, "$form->{formname}_email$form->{language}$form->{printer_code}.$extension" if $form->{media} eq 'email';
562 push @template_files, "$form->{formname}$form->{language}$form->{printer_code}.$extension";
563 push @template_files, "$form->{formname}.$extension";
564 push @template_files, "default.$extension";
567 for my $filename (@template_files) {
568 if (-f ($defaults->templates . "/$filename")) {
569 $form->{IN} = $filename;
574 if (!defined $form->{IN}) {
575 $::form->error($::locale->text('Cannot find matching template for this print request. Please contact your template maintainer. I tried these: #1.', join ', ', map { "'$_'"} @template_files));
578 # prepare meta information for template introspection
579 $form->{template_meta} = {
580 formname => $form->{formname},
581 language => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
582 format => $form->{format},
583 media => $form->{media},
584 extension => $extension,
585 printer => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
586 today => DateTime->today,
589 $main::lxdebug->leave_sub();
594 $main::lxdebug->enter_sub();
596 my ($self, $myconfig, $form) = @_;
598 # connect to database
599 my $dbh = SL::DB->client->dbh;
604 $form->{customer_id} = $1 if ($form->{customer} =~ /--(\d+)$/);
606 if ($form->{customer_id}) {
607 $where .= qq| AND (a.customer_id = ?)|;
608 push(@values, $form->{customer_id});
610 } elsif ($form->{customer}) {
611 $where .= qq| AND (ct.name ILIKE ?)|;
612 push(@values, like($form->{customer}));
615 if ($form->{department_id}) {
616 $where .= qq| AND (a.department_id = ?)|;
617 push(@values, $form->{department_id});
621 "ordnumber" => "a.ordnumber",
622 "invnumber" => "a.invnumber",
623 "notes" => "a.notes",
624 "country" => "ct.country",
626 foreach my $key (keys(%columns)) {
627 next unless ($form->{$key});
628 $where .= qq| AND $columns{$key} ILIKE ?|;
629 push(@values, like($form->{$key}));
632 if ($form->{dunning_level}) {
633 $where .= qq| AND nextcfg.id = ?|;
634 push(@values, conv_i($form->{dunning_level}));
637 $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
638 if ($form->{minamount}) {
639 $where .= qq| AND ((a.amount - a.paid) > ?) |;
640 push(@values, trim($form->{minamount}));
646 WHERE dunning_level = (SELECT MAX(dunning_level) FROM dunning_config)|;
647 my ($id_for_max_dunning_level) = selectrow_query($form, $dbh, $query);
649 if (!$form->{l_include_direct_debit}) {
650 $where .= qq| AND NOT COALESCE(a.direct_debit, FALSE) |;
652 my $paid = ($form->{l_include_credit_notes}) ? "WHERE (a.paid <> a.amount)" : "WHERE (a.paid < a.amount)";
656 a.id, a.invoice, a.ordnumber, a.transdate, a.invnumber, a.amount, a.language_id,
657 ct.name AS customername, a.customer_id, a.duedate,
658 a.amount - a.paid AS open_amount,
660 pt.description as payment_term,
661 dep.description as departmentname,
662 ct.invoice_mail AS cv_email,
663 cfg.dunning_description, cfg.dunning_level,
665 d.transdate AS dunning_date, d.duedate AS dunning_duedate,
668 a.duedate + cfg.terms - current_date AS nextlevel,
669 current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
670 current_date + cfg.payment_terms AS next_duedate,
672 nextcfg.dunning_description AS next_dunning_description,
673 nextcfg.id AS next_dunning_config_id,
674 nextcfg.terms, nextcfg.active, nextcfg.email, nextcfg.print_original_invoice
678 LEFT JOIN customer ct ON (a.customer_id = ct.id)
679 LEFT JOIN department dep ON (a.department_id = dep.id)
680 LEFT JOIN payment_terms pt ON (a.payment_id = pt.id)
681 LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
682 LEFT JOIN dunning_config nextcfg ON
687 WHERE dunning_level >
688 COALESCE((SELECT dunning_level
690 WHERE id = a.dunning_config_id
691 ORDER BY dunning_level DESC
694 ORDER BY dunning_level ASC
697 LEFT JOIN dunning d ON (d.id = (
700 WHERE (d2.trans_id = a.id)
701 AND (d2.dunning_level = cfg.dunning_level)
704 AND (a.duedate < current_date)
708 ORDER BY a.id, transdate, duedate, name|;
709 my $sth = prepare_execute_query($form, $dbh, $query, $id_for_max_dunning_level, @values);
711 $form->{DUNNINGS} = [];
713 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
714 next if ($ref->{pastdue} < $ref->{terms});
715 $ref->{credit_note} = 1 if ($ref->{amount} < 0 && $form->{l_include_credit_notes});
716 $ref->{interest} = $form->round_amount($ref->{interest}, 2);
717 push(@{ $form->{DUNNINGS} }, $ref);
722 $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
723 $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
725 $main::lxdebug->leave_sub();
730 $main::lxdebug->enter_sub();
732 my ($self, $myconfig, $form) = @_;
734 # connect to database
735 my $dbh = SL::DB->client->dbh;
737 my $where = qq| WHERE (da.trans_id = a.id)|;
741 if ($form->{customer_id}) {
742 $where .= qq| AND (a.customer_id = ?)|;
743 push(@values, $form->{customer_id});
745 } elsif ($form->{customer}) {
746 $where .= qq| AND (ct.name ILIKE ?)|;
747 push(@values, like($form->{customer}));
751 "ordnumber" => "a.ordnumber",
752 "invnumber" => "a.invnumber",
753 "notes" => "a.notes",
755 foreach my $key (keys(%columns)) {
756 next unless ($form->{$key});
757 $where .= qq| AND $columns{$key} ILIKE ?|;
758 push(@values, like($form->{$key}));
761 if ($form->{dunning_id}) {
762 $where .= qq| AND da.dunning_id = ?|;
763 push(@values, conv_i($form->{dunning_id}));
766 if ($form->{dunning_level}) {
767 $where .= qq| AND a.dunning_config_id = ?|;
768 push(@values, conv_i($form->{dunning_level}));
771 if ($form->{department_id}) {
772 $where .= qq| AND a.department_id = ?|;
773 push @values, conv_i($form->{department_id});
776 $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
777 if ($form->{minamount}) {
778 $where .= qq| AND ((a.amount - a.paid) > ?) |;
779 push(@values, $form->{minamount});
782 if (!$form->{showold}) {
783 $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
786 if ($form->{transdatefrom}) {
787 $where .= qq| AND a.transdate >= ?|;
788 push(@values, $form->{transdatefrom});
790 if ($form->{transdateto}) {
791 $where .= qq| AND a.transdate <= ?|;
792 push(@values, $form->{transdateto});
794 if ($form->{dunningfrom}) {
795 $where .= qq| AND da.transdate >= ?|;
796 push(@values, $form->{dunningfrom});
798 if ($form->{dunningto}) {
799 $where .= qq| AND da.transdate >= ?|;
800 push(@values, $form->{dunningto});
803 if ($form->{salesman_id}) {
804 $where .= qq| AND a.salesman_id = ?|;
805 push(@values, conv_i($form->{salesman_id}));
809 'dunning_description' => [ qw(dn.dunning_description da.dunning_id customername invnumber) ],
810 'customername' => [ qw(customername da.dunning_id invnumber) ],
811 'invnumber' => [ qw(a.invnumber) ],
812 'transdate' => [ qw(a.transdate a.invnumber) ],
813 'duedate' => [ qw(a.duedate a.invnumber) ],
814 'dunning_date' => [ qw(dunning_date da.dunning_id a.invnumber) ],
815 'dunning_duedate' => [ qw(dunning_duedate da.dunning_id a.invnumber) ],
816 'dunning_id' => [ qw(dunning_id a.invnumber) ],
817 'salesman' => [ qw(salesman) ],
820 my $sortdir = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
821 my $sortkey = $sort_columns{$form->{sort}} ? $form->{sort} : 'customername';
822 my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
825 qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount, a.language_id,
826 ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
827 da.interest, dn.dunning_description, dn.dunning_level, da.transdate AS dunning_date,
828 da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id,
829 da.id AS dunning_table_id,
832 JOIN customer ct ON (a.customer_id = ct.id)
833 LEFT JOIN employee e2 ON (a.salesman_id = e2.id), dunning da
834 LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
836 ORDER BY $sortorder|;
838 $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
840 foreach my $ref (@{ $form->{DUNNINGS} }) {
841 map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
844 $main::lxdebug->leave_sub();
849 $main::lxdebug->enter_sub();
851 my ($self, $myconfig, $form, $copies, %params) = @_;
853 # Don't allow access outside of $spool.
854 map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
857 $copies = 1 unless $copies;
858 my $spool = $::lx_office_conf{paths}->{spool};
859 my $inputfiles = join " ", map { "$spool/$_ " x $copies } @{ $form->{DUNNING_PDFS} };
860 my $dunning_id = $form->{dunning_id};
862 $dunning_id =~ s|[^\d]||g;
864 my $in = IO::File->new($::lx_office_conf{applications}->{ghostscript} . " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=- $inputfiles |");
865 $form->error($main::locale->text('Could not spawn ghostscript.')) unless $in;
867 my $dunning_filename = $form->get_formname_translation('dunning');
868 my $attachment_filename = "${dunning_filename}_${dunning_id}.pdf";
870 if ($params{return_content}) {
871 $content = read_file($in);
874 if ($form->{media} eq 'printer') {
875 $form->get_printer_code($myconfig);
877 if ($form->{printer_command}) {
878 $out = IO::File->new("| $form->{printer_command}");
881 $form->error($main::locale->text('Could not spawn the printer command.')) unless $out;
883 $::locale->with_raw_io($out, sub { $out->print($_) while <$in> });
886 print qq|Content-Type: Application/PDF\n| .
887 qq|Content-Disposition: attachment; filename=$attachment_filename\n\n|;
889 $::locale->with_raw_io(\*STDOUT, sub { print while <$in> });
895 map { unlink("$spool/$_") } @{ $form->{DUNNING_PDFS} };
897 $main::lxdebug->leave_sub();
898 return ($attachment_filename, $content) if $params{return_content};
902 $main::lxdebug->enter_sub();
904 my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
906 # connect to database
907 my $dbh = $provided_dbh || SL::DB->client->dbh;
909 $dunning_id =~ s|[^\d]||g;
911 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
912 if ($form->{"language_id"}) {
913 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
914 AM->get_language_details($myconfig, $form, $form->{language_id});
916 $output_dateformat = $myconfig->{dateformat};
917 $output_numberformat = $myconfig->{numberformat};
918 $output_longdates = 1;
924 da.transdate AS dunning_date,
925 da.duedate AS dunning_duedate,
927 dcfg.template AS formname,
928 dcfg.email_subject, dcfg.email_body, dcfg.email_attachment,
930 ar.transdate, ar.duedate, ar.customer_id,
931 ar.invnumber, ar.ordnumber, ar.cp_id,
932 ar.amount, ar.netamount, ar.paid,
933 ar.employee_id, ar.salesman_id,
934 (SELECT cu.name FROM currencies cu WHERE cu.id = ar.currency_id) AS curr,
935 (SELECT description from department WHERE id = ar.department_id) AS department,
936 ar.amount - ar.paid AS open_amount,
937 ar.amount - ar.paid + da.fee + da.interest AS linetotal
940 LEFT JOIN dunning_config dcfg ON (dcfg.id = da.dunning_config_id)
941 LEFT JOIN ar ON (ar.id = da.trans_id)
942 WHERE (da.dunning_id = ?)|;
944 my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
946 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
948 $form->{TEMPLATE_ARRAYS} = {};
949 map({ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} = []; } keys(%{$ref}));
952 map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest linetotal);
953 map { $form->{$_} = $ref->{$_} } keys %$ref;
954 map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $ref->{$_} } keys %$ref;
958 # if we have some credit notes to add, do a safety check on the first customer id
959 # and add one entry for each credit note
960 if ($form->{LIST_CREDIT_NOTES} && $form->{LIST_CREDIT_NOTES}->{$form->{TEMPLATE_ARRAYS}->{"dn_customer_id"}[0]}) {
961 my $first_customer_id = $form->{TEMPLATE_ARRAYS}->{"dn_customer_id"}[0];
962 while ( my ($cred_id, $value) = each(%{ $form->{LIST_CREDIT_NOTES}->{$first_customer_id} } ) ) {
963 map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $value->{$_} } keys %{ $value };
968 c.id AS customer_id, c.name, c.street, c.zipcode, c.city,
969 c.country, c.department_1, c.department_2, c.email, c.customernumber,
970 c.greeting, c.contact, c.phone, c.fax, c.homepage,
971 c.email, c.taxincluded, c.business_id, c.taxnumber, c.iban,
972 c.ustid, c.currency_id, curr.name as currency,
976 LEFT JOIN ar ON (d.trans_id = ar.id)
977 LEFT JOIN customer c ON (ar.customer_id = c.id)
978 LEFT JOIN contacts co ON (ar.cp_id = co.cp_id)
979 LEFT JOIN employee e ON (ar.salesman_id = e.id)
980 LEFT JOIN currencies curr ON (c.currency_id = curr.id)
981 WHERE (d.dunning_id = ?)
983 my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
984 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
988 cfg.interest_rate, cfg.template AS formname, cfg.dunning_level,
989 cfg.email_subject, cfg.email_body, cfg.email_attachment,
990 d.transdate AS dunning_date,
993 WHERE dunning_id = ?)
995 (SELECT SUM(interest)
997 WHERE dunning_id = ?)
999 (SELECT SUM(amount) - SUM(paid)
1004 WHERE dunning_id = ?))
1005 AS total_open_amount
1007 LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
1008 WHERE d.dunning_id = ?
1010 $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id, $dunning_id);
1011 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1013 $form->{interest_rate} = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
1014 $form->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
1015 $form->{total_interest} = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
1016 my $total_open_amount = $ref->{total_open_amount};
1017 if ($form->{l_include_credit_notes}) {
1018 # a bit stupid, but redo calc because of credit notes
1019 $total_open_amount = 0;
1020 foreach my $amount (@{ $form->{TEMPLATE_ARRAYS}->{dn_open_amount} }) {
1021 $total_open_amount += $form->parse_amount($myconfig, $amount, 2);
1024 $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($total_open_amount, 2), 2);
1025 $form->{total_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $total_open_amount, 2), 2);
1027 $::form->format_dates($output_dateformat, $output_longdates,
1028 qw(dn_dunning_date dn_dunning_duedate dn_transdate dn_duedate
1029 dunning_date dunning_duedate transdate duedate)
1031 $::form->reformat_numbers($output_numberformat, 2, qw(
1032 dn_amount dn_netamount dn_paid dn_open_amount dn_fee dn_interest dn_linetotal
1033 amount netamount paid open_amount fee interest linetotal
1034 total_interest total_open_interest total_amount total_open_amount
1036 $::form->reformat_numbers($output_numberformat, undef, qw(interest_rate));
1038 $self->set_customer_cvars($myconfig, $form);
1039 $self->set_template_options($myconfig, $form);
1041 my $filename = "dunning_${dunning_id}_" . Common::unique_id() . ".pdf";
1042 my $spool = $::lx_office_conf{paths}->{spool};
1043 $form->{OUT} = "${spool}/$filename";
1044 $form->{keep_tmpfile} = 1;
1046 delete $form->{tmpfile};
1048 my $employee_id = ($::instance_conf->get_dunning_creator eq 'invoice_employee') ?
1049 $form->{employee_id} :
1050 SL::DB::Manager::Employee->current->id;
1052 $form->get_employee_data('prefix' => 'employee', 'id' => $employee_id);
1053 $form->get_employee_data('prefix' => 'salesman', 'id' => $form->{salesman_id});
1055 $form->{attachment_type} = "dunning";
1056 if ( $form->{dunning_level} ) {
1057 $form->{attachment_type} .= $form->{dunning_level} if $form->{dunning_level} < 4;
1059 $form->{attachment_filename} = $form->get_formname_translation($form->{attachment_type}) . "_${dunning_id}.pdf";
1060 $form->{attachment_id} = $form->{invoice_id};
1062 # this generates the file in the spool directory
1063 $form->parse_template($myconfig);
1065 push @{ $form->{DUNNING_PDFS} } , $filename;
1066 push @{ $form->{DUNNING_PDFS_EMAIL} } , { 'path' => "${spool}/$filename",
1067 'name' => $form->get_formname_translation('dunning') . "_${dunning_id}.pdf" };
1068 push @{ $form->{DUNNING_PDFS_STORAGE} }, { 'dunning_id' => $dunning_id,
1069 'path' => "${spool}/$filename",
1070 'name' => $form->get_formname_translation('dunning') . "_${dunning_id}.pdf" };
1072 $main::lxdebug->leave_sub();
1075 sub print_invoice_for_fees {
1076 $main::lxdebug->enter_sub();
1078 my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
1080 my $dbh = $provided_dbh || SL::DB->client->dbh;
1082 my ($query, @values, $sth);
1086 d.fee_interest_ar_id,
1087 d.trans_id AS invoice_id,
1091 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
1092 WHERE d.dunning_id = ?|;
1093 my ($ar_id, $invoice_id, $template, $dunning_level) = selectrow_query($form, $dbh, $query, $dunning_id);
1096 $main::lxdebug->leave_sub();
1100 my $saved_form = save_form();
1102 $query = qq|SELECT SUM(fee), SUM(interest) FROM dunning WHERE id = ?|;
1103 my ($fee_total, $interest_total) = selectrow_query($form, $dbh, $query, $dunning_id);
1107 ar.invnumber, ar.transdate AS invdate, ar.amount, ar.netamount,
1108 ar.duedate, ar.notes, ar.notes AS invoicenotes, ar.customer_id,
1110 c.name, c.department_1, c.department_2, c.street, c.zipcode, c.city, c.country,
1111 c.contact, c.customernumber, c.phone, c.fax, c.email,
1112 c.taxnumber, c.greeting
1115 LEFT JOIN customer c ON (ar.customer_id = c.id)
1117 my $ref = selectfirst_hashref_query($form, $dbh, $query, $ar_id);
1118 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1120 $query = qq|SELECT * FROM employee WHERE login = ?|;
1121 $ref = selectfirst_hashref_query($form, $dbh, $query, $::myconfig{login});
1122 map { $form->{"employee_${_}"} = $ref->{$_} } keys %{ $ref };
1124 $query = qq|SELECT * FROM acc_trans WHERE trans_id = ? ORDER BY acc_trans_id ASC|;
1125 $sth = prepare_execute_query($form, $dbh, $query, $ar_id);
1127 my ($row, $fee, $interest) = (0, 0, 0);
1129 while ($ref = $sth->fetchrow_hashref()) {
1130 next if ($ref->{amount} < 0);
1135 $fee = $ref->{amount};
1137 $interest = $ref->{amount};
1141 $form->{fee} = $form->round_amount($fee, 2);
1142 $form->{interest} = $form->round_amount($interest, 2);
1143 $form->{invamount} = $form->round_amount($fee + $interest, 2);
1144 $form->{dunning_id} = $dunning_id;
1145 $form->{formname} = "${template}_invoice";
1147 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) } qw(fee interest invamount);
1149 $self->set_customer_cvars($myconfig, $form);
1150 $self->set_template_options($myconfig, $form);
1152 my $filename = Common::unique_id() . "dunning_invoice_" . $form->{invnumber} . ".pdf";
1154 my $spool = $::lx_office_conf{paths}->{spool};
1155 $form->{OUT} = "$spool/$filename";
1156 $form->{keep_tmpfile} = 1;
1157 delete $form->{tmpfile};
1159 map { delete $form->{$_} } grep /^[a-z_]+_\d+$/, keys %{ $form };
1161 my $attachment_filename = $form->get_formname_translation('dunning_invoice') . "_" . $form->{invnumber} . ".pdf";
1162 $form->{attachment_filename} = $attachment_filename;
1163 $form->{attachment_type} = "dunning";
1164 $form->{attachment_id} = $invoice_id;
1165 $form->parse_template($myconfig);
1167 restore_form($saved_form);
1169 push @{ $form->{DUNNING_PDFS} }, $filename;
1170 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$filename",
1171 'name' => $attachment_filename };
1172 push @{ $form->{DUNNING_PDFS_STORAGE} }, { 'dunning_id' => $dunning_id,
1173 'path' => "${spool}/$filename",
1174 'name' => $attachment_filename };
1176 $main::lxdebug->leave_sub();
1179 sub set_customer_cvars {
1180 my ($self, $myconfig, $form) = @_;
1182 my $custom_variables = CVar->get_custom_variables(dbh => $form->get_standard_dbh,
1184 trans_id => $form->{customer_id});
1185 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1187 $form->{cp_greeting} = GenericTranslations->get(dbh => $form->get_standard_dbh,
1188 translation_type => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1189 language_id => $form->{language_id},
1190 allow_fallback => 1);
1191 if ($form->{cp_id}) {
1192 $custom_variables = CVar->get_custom_variables(dbh => $form->get_standard_dbh,
1193 module => 'Contacts',
1194 trans_id => $form->{cp_id});
1195 $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1200 sub print_original_invoice {
1201 my ($self, $myconfig, $form, $dunning_id, $invoice_id) = @_;
1202 # get one invoice as object and print to pdf
1203 my $invoice = SL::DB::Invoice->new(id => $invoice_id)->load;
1205 die "Invalid invoice object" unless ref($invoice) eq 'SL::DB::Invoice';
1207 my $print_form = Form->new('');
1208 $print_form->{type} = 'invoice';
1209 $print_form->{formname} = 'invoice',
1210 $print_form->{format} = 'pdf',
1211 $print_form->{media} = 'file';
1212 # no language override, should always be the object's language
1213 $invoice->flatten_to_form($print_form, format_amounts => 1);
1214 for my $i (1 .. $print_form->{rowcount}) {
1215 $print_form->{"sellprice_$i"} = $print_form->{"fxsellprice_$i"};
1217 $print_form->prepare_for_printing;
1219 my $filename = SL::Helper::CreatePDF->create_pdf(
1220 template => 'invoice.tex',
1221 variables => $print_form,
1222 return => 'file_name',
1223 variable_content_types => {
1224 longdescription => 'html',
1225 partnotes => 'html',
1227 $print_form->get_variable_content_types_for_cvars,
1231 my $spool = $::lx_office_conf{paths}->{spool};
1232 my ($volume, $directory, $file_name) = File::Spec->splitpath($filename);
1233 my $full_file_name = File::Spec->catfile($spool, $file_name);
1235 move($filename, $full_file_name) or die "The move operation failed: $!";
1237 # form get_formname_translation should use language_id_$i
1238 my $saved_reicpient_locale = $form->{recipient_locale};
1239 $form->{recipient_locale} = $invoice->language;
1241 my $attachment_filename = $form->get_formname_translation('invoice') . "_" . $invoice->invnumber . ".pdf";
1243 push @{ $form->{DUNNING_PDFS} }, $file_name;
1244 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$file_name",
1245 'name' => $attachment_filename };
1246 push @{ $form->{DUNNING_PDFS_STORAGE} }, { 'dunning_id' => $dunning_id,
1247 'path' => "${spool}/$file_name",
1248 'name' => $attachment_filename };
1250 $form->{recipient_locale} = $saved_reicpient_locale;
1253 sub _store_pdf_to_webdav_and_filemanagement {
1254 my ($dunning_id, $path, $name) =@_;
1258 if ($::instance_conf->get_doc_storage) {
1261 object_id => $dunning_id,
1262 object_type => 'dunning',
1263 mime_type => 'application/pdf',
1264 source => 'created',
1265 file_type => 'document',
1271 push @errors, $::locale->text('Storing PDF in storage backend failed: #1', $@);
1275 if ($::instance_conf->get_webdav_documents) {
1277 my $webdav = SL::Webdav->new(
1279 number => $dunning_id,
1281 my $webdav_file = SL::Webdav::File->new(
1285 $webdav_file->store(file => $path);
1287 push @errors, $::locale->text('Storing PDF to webdav folder failed: #1', $@);