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 #======================================================================
43 use SL::GenericTranslations;
51 use SL::Util qw(trim);
59 $main::lxdebug->enter_sub();
61 my ($self, $myconfig, $form) = @_;
64 my $dbh = SL::DB->client->dbh;
68 qq|FROM dunning_config | .
69 qq|ORDER BY dunning_level|;
70 $form->{DUNNING} = selectall_hashref_query($form, $dbh, $query);
72 foreach my $ref (@{ $form->{DUNNING} }) {
73 $ref->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
74 $ref->{interest_rate} = $form->format_amount($myconfig, ($ref->{interest_rate} * 100));
78 qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar, dunning_creator
80 ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}, $form->{dunning_creator})
81 = selectrow_query($form, $dbh, $query);
83 $main::lxdebug->leave_sub();
87 my ($self, $myconfig, $form) = @_;
88 $main::lxdebug->enter_sub();
90 my $rc = SL::DB->client->with_transaction(\&_save_config, $self, $myconfig, $form);
92 $::lxdebug->leave_sub;
97 my ($self, $myconfig, $form) = @_;
99 my $dbh = SL::DB->client->dbh;
101 my ($query, @values);
103 for my $i (1 .. $form->{rowcount}) {
104 $form->{"fee_$i"} = $form->parse_amount($myconfig, $form->{"fee_$i"}) * 1;
105 $form->{"interest_rate_$i"} = $form->parse_amount($myconfig, $form->{"interest_rate_$i"}) / 100;
107 if (($form->{"dunning_level_$i"} ne "") &&
108 ($form->{"dunning_description_$i"} ne "")) {
109 @values = (conv_i($form->{"dunning_level_$i"}), $form->{"dunning_description_$i"},
110 $form->{"email_subject_$i"}, $form->{"email_body_$i"},
111 $form->{"template_$i"}, $form->{"fee_$i"}, $form->{"interest_rate_$i"},
112 $form->{"active_$i"} ? 't' : 'f', $form->{"auto_$i"} ? 't' : 'f', $form->{"email_$i"} ? 't' : 'f',
113 $form->{"email_attachment_$i"} ? 't' : 'f', conv_i($form->{"payment_terms_$i"}), conv_i($form->{"terms_$i"}),
114 $form->{"create_invoices_for_fees_$i"} ? 't' : 'f');
115 if ($form->{"id_$i"}) {
117 qq|UPDATE dunning_config SET
118 dunning_level = ?, dunning_description = ?,
119 email_subject = ?, email_body = ?,
120 template = ?, fee = ?, interest_rate = ?,
121 active = ?, auto = ?, email = ?,
122 email_attachment = ?, payment_terms = ?, terms = ?,
123 create_invoices_for_fees = ?
125 push(@values, conv_i($form->{"id_$i"}));
128 qq|INSERT INTO dunning_config
129 (dunning_level, dunning_description, email_subject, email_body,
130 template, fee, interest_rate, active, auto, email,
131 email_attachment, payment_terms, terms, create_invoices_for_fees)
132 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
134 do_query($form, $dbh, $query, @values);
137 if (($form->{"dunning_description_$i"} eq "") && ($form->{"id_$i"})) {
138 $query = qq|DELETE FROM dunning_config WHERE id = ?|;
139 do_query($form, $dbh, $query, $form->{"id_$i"});
143 $query = qq|UPDATE defaults SET dunning_ar_amount_fee = ?, dunning_ar_amount_interest = ?, dunning_ar = ?,
144 dunning_creator = ?|;
145 @values = (conv_i($form->{AR_amount_fee}), conv_i($form->{AR_amount_interest}), conv_i($form->{AR}),
146 $form->{dunning_creator});
147 do_query($form, $dbh, $query, @values);
152 sub create_invoice_for_fees {
153 $main::lxdebug->enter_sub();
155 my ($self, $myconfig, $form, $dbh, $dunning_id) = @_;
157 my ($query, @values, $sth, $ref);
159 $query = qq|SELECT dcfg.create_invoices_for_fees
161 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
162 WHERE d.dunning_id = ?|;
163 my ($create_invoices_for_fees) = selectrow_query($form, $dbh, $query, $dunning_id);
165 if (!$create_invoices_for_fees) {
166 $main::lxdebug->leave_sub();
170 $query = qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar FROM defaults|;
171 ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}) = selectrow_query($form, $dbh, $query);
177 SELECT MAX(d_fee.fee)
179 WHERE (d_fee.trans_id = d.trans_id)
180 AND (d_fee.dunning_id <> ?)
181 AND NOT (d_fee.fee_interest_ar_id ISNULL)
186 SELECT MAX(d_interest.interest)
187 FROM dunning d_interest
188 WHERE (d_interest.trans_id = d.trans_id)
189 AND (d_interest.dunning_id <> ?)
190 AND NOT (d_interest.fee_interest_ar_id ISNULL)
192 AS max_previous_interest
194 WHERE dunning_id = ?|;
195 @values = ($dunning_id, $dunning_id, $dunning_id);
196 $sth = prepare_execute_query($form, $dbh, $query, @values);
198 my ($fee_remaining, $interest_remaining) = (0, 0);
199 my ($fee_total, $interest_total) = (0, 0);
201 while (my $ref = $sth->fetchrow_hashref()) {
202 $fee_remaining += $form->round_amount($ref->{fee}, 2);
203 $fee_remaining -= $form->round_amount($ref->{max_previous_fee}, 2);
204 $fee_total += $form->round_amount($ref->{fee}, 2);
205 $interest_remaining += $form->round_amount($ref->{interest}, 2);
206 $interest_remaining -= $form->round_amount($ref->{max_previous_interest}, 2);
207 $interest_total += $form->round_amount($ref->{interest}, 2);
212 my $amount = $fee_remaining + $interest_remaining;
215 $main::lxdebug->leave_sub();
219 my ($ar_id) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
220 my $curr = $form->get_default_currency($myconfig);
221 my $trans_number = SL::TransNumber->new(type => 'invoice', dbh => $dbh);
224 qq|INSERT INTO ar (id, invnumber, transdate, gldate, customer_id,
225 taxincluded, amount, netamount, paid, duedate,
226 invoice, currency_id, taxzone_id, notes,
231 current_date, -- transdate
232 current_date, -- gldate
234 (SELECT ar.customer_id
236 LEFT JOIN ar ON (dn.trans_id = ar.id)
237 WHERE dn.dunning_id = ?
244 (SELECT duedate FROM dunning WHERE dunning_id = ? LIMIT 1),
246 (SELECT id FROM currencies WHERE name = ?), -- curr
248 (SELECT taxzone_id FROM customer WHERE id =
249 (SELECT ar.customer_id
251 LEFT JOIN ar ON (dn.trans_id = ar.id)
252 WHERE dn.dunning_id = ?
257 (SELECT id FROM employee WHERE login = ?)
259 @values = ($ar_id, # id
260 $trans_number->create_unique, # invnumber
261 $dunning_id, # customer_id
264 $dunning_id, # duedate
265 $curr, # default currency
266 $dunning_id, # taxzone_id
267 sprintf($main::locale->text('Automatically created invoice for fee and interest for dunning %s'), $dunning_id), # notes
268 $::myconfig{login}); # employee_id
269 do_query($form, $dbh, $query, @values);
272 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, taxkey, tax_id, chart_link)
273 VALUES (?, ?, ?, current_date, current_date, 0,
274 (SELECT id FROM tax WHERE (taxkey = 0) AND (rate = 0)),
275 (SELECT link FROM chart WHERE id = ?))|;
276 $sth = prepare_query($form, $dbh, $query);
278 @values = ($ar_id, conv_i($form->{AR_amount_fee}), $fee_remaining, conv_i($form->{AR_amount_fee}));
279 do_statement($form, $sth, $query, @values);
281 if ($interest_remaining) {
282 @values = ($ar_id, conv_i($form->{AR_amount_interest}), $interest_remaining, conv_i($form->{AR_amount_interest}));
283 do_statement($form, $sth, $query, @values);
286 @values = ($ar_id, conv_i($form->{AR}), -1 * $amount, conv_i($form->{AR}));
287 do_statement($form, $sth, $query, @values);
291 $query = qq|UPDATE dunning SET fee_interest_ar_id = ? WHERE dunning_id = ?|;
292 do_query($form, $dbh, $query, $ar_id, $dunning_id);
294 $main::lxdebug->leave_sub();
299 my ($self, $myconfig, $form, $rows) = @_;
300 $main::lxdebug->enter_sub();
302 my $rc = SL::DB->client->with_transaction(\&_save_dunning, $self, $myconfig, $form, $rows);
305 die SL::DB->client->error
307 $::lxdebug->leave_sub;
314 my ($self, $myconfig, $form, $rows) = @_;
316 my $dbh = SL::DB->client->dbh;
318 my ($query, @values);
320 my ($dunning_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
322 my $q_update_ar = qq|UPDATE ar SET dunning_config_id = ? WHERE id = ?|;
323 my $h_update_ar = prepare_query($form, $dbh, $q_update_ar);
325 my $q_insert_dunning =
326 qq|INSERT INTO dunning (dunning_id, dunning_config_id, dunning_level, trans_id,
327 fee, interest, transdate, duedate)
329 (SELECT dunning_level FROM dunning_config WHERE id = ?),
333 WHERE dunning_level <= (SELECT dunning_level FROM dunning_config WHERE id = ?)),
334 (SELECT (amount - paid) * (current_date - duedate) FROM ar WHERE id = ?)
335 * (SELECT interest_rate FROM dunning_config WHERE id = ?)
338 current_date + (SELECT payment_terms FROM dunning_config WHERE id = ?))|;
339 my $h_insert_dunning = prepare_query($form, $dbh, $q_insert_dunning);
342 my ($next_dunning_config_id, $customer_id);
343 my ($send_email, $print_invoice) = (0, 0);
345 foreach my $row (@{ $rows }) {
346 push @invoice_ids, $row->{invoice_id};
347 $next_dunning_config_id = $row->{next_dunning_config_id};
348 $customer_id = $row->{customer_id};
350 @values = ($row->{next_dunning_config_id}, $row->{invoice_id});
351 do_statement($form, $h_update_ar, $q_update_ar, @values);
353 $send_email |= $row->{email};
354 $print_invoice |= $row->{print_invoice};
356 my $next_config_id = conv_i($row->{next_dunning_config_id});
357 my $invoice_id = conv_i($row->{invoice_id});
359 @values = ($dunning_id, $next_config_id, $next_config_id,
360 $invoice_id, $next_config_id, $invoice_id,
361 $next_config_id, $next_config_id);
362 do_statement($form, $h_insert_dunning, $q_insert_dunning, @values);
365 $h_update_ar->finish();
366 $h_insert_dunning->finish();
368 $form->{DUNNING_PDFS_EMAIL} = [];
370 $form->{dunning_id} = $dunning_id;
372 $self->create_invoice_for_fees($myconfig, $form, $dbh, $dunning_id);
374 $self->print_invoice_for_fees($myconfig, $form, $dunning_id, $dbh);
375 $self->print_dunning($myconfig, $form, $dunning_id, $dbh);
377 if ($print_invoice) {
378 $self->print_original_invoices($myconfig, $form, $_, $dbh) for @invoice_ids;
382 $self->send_email($myconfig, $form, $dunning_id, $dbh);
389 $main::lxdebug->enter_sub();
391 my ($self, $myconfig, $form, $dunning_id, $dbh) = @_;
395 dcfg.email_body, dcfg.email_subject, dcfg.email_attachment,
396 COALESCE (NULLIF(c.invoice_mail, ''), c.email) AS recipient, c.name,
397 (SELECT login from employee where id = ar.employee_id) as invoice_employee_login
399 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
400 LEFT JOIN ar ON (d.trans_id = ar.id)
401 LEFT JOIN customer c ON (ar.customer_id = c.id)
402 WHERE (d.dunning_id = ?)
404 my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
406 # without a recipient, we cannot send a mail
407 if (!$ref || !$ref->{recipient}) {
408 $main::lxdebug->leave_sub();
409 die $main::locale->text("No email recipient for customer #1 defined.", $ref->{name});
412 # without a sender we cannot send a mail
413 # two cases: check mail from 1. current user OR 2. employee who created the invoice
415 if ($::instance_conf->get_dunning_creator eq 'current_employee') {
416 $from = $myconfig->{email};
417 die $main::locale->text('No email for current user #1 defined.', $myconfig->{name}) unless $from;
420 $from = SL::DB::Manager::AuthUser->find_by(login => $ref->{invoice_employee_login})->get_config_value("email");
421 $sign = SL::DB::Manager::AuthUser->find_by(login => $ref->{invoice_employee_login})->get_config_value("signature");
424 } or die $main::locale->text('No email for user with login #1 defined.', $ref->{invoice_employee_login});
427 my $template = SL::Template::create(type => 'PlainText', form => $form, myconfig => $myconfig);
428 my $mail = Mailer->new();
429 $mail->{bcc} = $form->get_bcc_defaults($myconfig, $form->{bcc});
430 $mail->{from} = $from;
431 $mail->{to} = $ref->{recipient};
432 $mail->{subject} = $template->parse_block($ref->{email_subject});
433 $mail->{message} = $template->parse_block($ref->{email_body});
434 my $sign_backup = $::myconfig{signature};
435 $::myconfig{signature} = $sign if $sign;
436 $mail->{message} .= $form->create_email_signature();
437 $::myconfig{signature} = $sign_backup if $sign;
439 $mail->{message} =~ s/\r\n/\n/g;
441 if ($ref->{email_attachment} && @{ $form->{DUNNING_PDFS_EMAIL} }) {
442 $mail->{attachments} = $form->{DUNNING_PDFS_EMAIL};
447 $main::lxdebug->leave_sub();
450 sub set_template_options {
451 $main::lxdebug->enter_sub();
453 my ($self, $myconfig, $form) = @_;
455 my $defaults = SL::DB::Default->get;
456 $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
457 $form->{templates} = $defaults->templates;
458 $form->{language} = $form->get_template_language($myconfig);
459 $form->{printer_code} = $form->get_printer_code($myconfig);
461 if ($form->{language} ne "") {
462 $form->{language} = "_" . $form->{language};
465 if ($form->{printer_code} ne "") {
466 $form->{printer_code} = "_" . $form->{printer_code};
469 my $extension = 'html';
470 if ($form->{format} eq 'postscript') {
471 $form->{postscript} = 1;
474 } elsif ($form->{"format"} =~ /pdf/) {
476 $extension = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
478 } elsif ($form->{"format"} =~ /opendocument/) {
479 $form->{opendocument} = 1;
481 } elsif ($form->{"format"} =~ /excel/) {
487 # search for the template
489 push @template_files, "$form->{formname}_email$form->{language}$form->{printer_code}.$extension" if $form->{media} eq 'email';
490 push @template_files, "$form->{formname}$form->{language}$form->{printer_code}.$extension";
491 push @template_files, "$form->{formname}.$extension";
492 push @template_files, "default.$extension";
495 for my $filename (@template_files) {
496 if (-f ($defaults->templates . "/$filename")) {
497 $form->{IN} = $filename;
502 if (!defined $form->{IN}) {
503 $::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));
506 # prepare meta information for template introspection
507 $form->{template_meta} = {
508 formname => $form->{formname},
509 language => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
510 format => $form->{format},
511 media => $form->{media},
512 extension => $extension,
513 printer => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
514 today => DateTime->today,
517 $main::lxdebug->leave_sub();
522 $main::lxdebug->enter_sub();
524 my ($self, $myconfig, $form) = @_;
526 # connect to database
527 my $dbh = SL::DB->client->dbh;
532 $form->{customer_id} = $1 if ($form->{customer} =~ /--(\d+)$/);
534 if ($form->{customer_id}) {
535 $where .= qq| AND (a.customer_id = ?)|;
536 push(@values, $form->{customer_id});
538 } elsif ($form->{customer}) {
539 $where .= qq| AND (ct.name ILIKE ?)|;
540 push(@values, like($form->{customer}));
543 if ($form->{department_id}) {
544 $where .= qq| AND (a.department_id = ?)|;
545 push(@values, $form->{department_id});
549 "ordnumber" => "a.ordnumber",
550 "invnumber" => "a.invnumber",
551 "notes" => "a.notes",
552 "country" => "ct.country",
554 foreach my $key (keys(%columns)) {
555 next unless ($form->{$key});
556 $where .= qq| AND $columns{$key} ILIKE ?|;
557 push(@values, like($form->{$key}));
560 if ($form->{dunning_level}) {
561 $where .= qq| AND nextcfg.id = ?|;
562 push(@values, conv_i($form->{dunning_level}));
565 $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
566 if ($form->{minamount}) {
567 $where .= qq| AND ((a.amount - a.paid) > ?) |;
568 push(@values, trim($form->{minamount}));
574 WHERE dunning_level = (SELECT MAX(dunning_level) FROM dunning_config)|;
575 my ($id_for_max_dunning_level) = selectrow_query($form, $dbh, $query);
577 if (!$form->{l_include_direct_debit}) {
578 $where .= qq| AND NOT COALESCE(a.direct_debit, FALSE) |;
583 a.id, a.invoice, a.ordnumber, a.transdate, a.invnumber, a.amount, a.language_id,
584 ct.name AS customername, a.customer_id, a.duedate,
585 a.amount - a.paid AS open_amount,
587 dep.description as departmentname,
589 cfg.dunning_description, cfg.dunning_level,
591 d.transdate AS dunning_date, d.duedate AS dunning_duedate,
594 a.duedate + cfg.terms - current_date AS nextlevel,
595 current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
596 current_date + cfg.payment_terms AS next_duedate,
598 nextcfg.dunning_description AS next_dunning_description,
599 nextcfg.id AS next_dunning_config_id,
600 nextcfg.terms, nextcfg.active, nextcfg.email
604 LEFT JOIN customer ct ON (a.customer_id = ct.id)
605 LEFT JOIN department dep ON (a.department_id = dep.id)
606 LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
607 LEFT JOIN dunning_config nextcfg ON
612 WHERE dunning_level >
613 COALESCE((SELECT dunning_level
615 WHERE id = a.dunning_config_id
616 ORDER BY dunning_level DESC
619 ORDER BY dunning_level ASC
622 LEFT JOIN dunning d ON (d.id = (
625 WHERE (d2.trans_id = a.id)
626 AND (d2.dunning_level = cfg.dunning_level)
629 WHERE (a.paid < a.amount)
630 AND (a.duedate < current_date)
634 ORDER BY a.id, transdate, duedate, name|;
635 my $sth = prepare_execute_query($form, $dbh, $query, $id_for_max_dunning_level, @values);
637 $form->{DUNNINGS} = [];
639 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
640 next if ($ref->{pastdue} < $ref->{terms});
642 $ref->{interest} = $form->round_amount($ref->{interest}, 2);
643 push(@{ $form->{DUNNINGS} }, $ref);
648 $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
649 $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
651 $main::lxdebug->leave_sub();
656 $main::lxdebug->enter_sub();
658 my ($self, $myconfig, $form) = @_;
660 # connect to database
661 my $dbh = SL::DB->client->dbh;
663 my $where = qq| WHERE (da.trans_id = a.id)|;
667 if ($form->{customer_id}) {
668 $where .= qq| AND (a.customer_id = ?)|;
669 push(@values, $form->{customer_id});
671 } elsif ($form->{customer}) {
672 $where .= qq| AND (ct.name ILIKE ?)|;
673 push(@values, like($form->{customer}));
677 "ordnumber" => "a.ordnumber",
678 "invnumber" => "a.invnumber",
679 "notes" => "a.notes",
681 foreach my $key (keys(%columns)) {
682 next unless ($form->{$key});
683 $where .= qq| AND $columns{$key} ILIKE ?|;
684 push(@values, like($form->{$key}));
687 if ($form->{dunning_level}) {
688 $where .= qq| AND a.dunning_config_id = ?|;
689 push(@values, conv_i($form->{dunning_level}));
692 if ($form->{department_id}) {
693 $where .= qq| AND a.department_id = ?|;
694 push @values, conv_i($form->{department_id});
697 $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
698 if ($form->{minamount}) {
699 $where .= qq| AND ((a.amount - a.paid) > ?) |;
700 push(@values, $form->{minamount});
703 if (!$form->{showold}) {
704 $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
707 if ($form->{transdatefrom}) {
708 $where .= qq| AND a.transdate >= ?|;
709 push(@values, $form->{transdatefrom});
711 if ($form->{transdateto}) {
712 $where .= qq| AND a.transdate <= ?|;
713 push(@values, $form->{transdateto});
715 if ($form->{dunningfrom}) {
716 $where .= qq| AND da.transdate >= ?|;
717 push(@values, $form->{dunningfrom});
719 if ($form->{dunningto}) {
720 $where .= qq| AND da.transdate >= ?|;
721 push(@values, $form->{dunningto});
724 if ($form->{salesman_id}) {
725 $where .= qq| AND a.salesman_id = ?|;
726 push(@values, conv_i($form->{salesman_id}));
730 'dunning_description' => [ qw(dn.dunning_description customername invnumber) ],
731 'customername' => [ qw(customername invnumber) ],
732 'invnumber' => [ qw(a.invnumber) ],
733 'transdate' => [ qw(a.transdate a.invnumber) ],
734 'duedate' => [ qw(a.duedate a.invnumber) ],
735 'dunning_date' => [ qw(dunning_date a.invnumber) ],
736 'dunning_duedate' => [ qw(dunning_duedate a.invnumber) ],
737 'salesman' => [ qw(salesman) ],
740 my $sortdir = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
741 my $sortkey = $sort_columns{$form->{sort}} ? $form->{sort} : 'customername';
742 my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
745 qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount, a.language_id,
746 ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
747 da.interest, dn.dunning_description, da.transdate AS dunning_date,
748 da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id,
751 JOIN customer ct ON (a.customer_id = ct.id)
752 LEFT JOIN employee e2 ON (a.salesman_id = e2.id), dunning da
753 LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
755 ORDER BY $sortorder|;
757 $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
759 foreach my $ref (@{ $form->{DUNNINGS} }) {
760 map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
763 $main::lxdebug->leave_sub();
768 $main::lxdebug->enter_sub();
770 my ($self, $myconfig, $form, $copies) = @_;
772 # Don't allow access outside of $spool.
773 map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
776 $copies = 1 unless $copies;
777 my $spool = $::lx_office_conf{paths}->{spool};
778 my $inputfiles = join " ", map { "$spool/$_ " x $copies } @{ $form->{DUNNING_PDFS} };
779 my $dunning_id = $form->{dunning_id};
781 $dunning_id =~ s|[^\d]||g;
783 my $in = IO::File->new($::lx_office_conf{applications}->{ghostscript} . " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=- $inputfiles |");
784 $form->error($main::locale->text('Could not spawn ghostscript.')) unless $in;
786 if ($form->{media} eq 'printer') {
787 $form->get_printer_code($myconfig);
789 if ($form->{printer_command}) {
790 $out = IO::File->new("| $form->{printer_command}");
793 $::locale->with_raw_io($out, sub { $out->print($_) while <$in> });
795 $form->error($main::locale->text('Could not spawn the printer command.')) unless $out;
798 my $dunning_filename = $form->get_formname_translation('dunning');
799 print qq|Content-Type: Application/PDF\n| .
800 qq|Content-Disposition: attachment; filename="${dunning_filename}_${dunning_id}.pdf"\n\n|;
802 $::locale->with_raw_io(\*STDOUT, sub { print while <$in> });
807 map { unlink("$spool/$_") } @{ $form->{DUNNING_PDFS} };
809 $main::lxdebug->leave_sub();
813 $main::lxdebug->enter_sub();
815 my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
817 # connect to database
818 my $dbh = $provided_dbh || SL::DB->client->dbh;
820 $dunning_id =~ s|[^\d]||g;
822 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
823 if ($form->{"language_id"}) {
824 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
825 AM->get_language_details($myconfig, $form, $form->{language_id});
827 $output_dateformat = $myconfig->{dateformat};
828 $output_numberformat = $myconfig->{numberformat};
829 $output_longdates = 1;
835 da.transdate AS dunning_date,
836 da.duedate AS dunning_duedate,
838 dcfg.template AS formname,
839 dcfg.email_subject, dcfg.email_body, dcfg.email_attachment,
841 ar.transdate, ar.duedate, ar.customer_id,
842 ar.invnumber, ar.ordnumber, ar.cp_id,
843 ar.amount, ar.netamount, ar.paid,
844 ar.employee_id, ar.salesman_id,
845 (SELECT cu.name FROM currencies cu WHERE cu.id = ar.currency_id) AS curr,
846 (SELECT description from department WHERE id = ar.department_id) AS department,
847 ar.amount - ar.paid AS open_amount,
848 ar.amount - ar.paid + da.fee + da.interest AS linetotal
851 LEFT JOIN dunning_config dcfg ON (dcfg.id = da.dunning_config_id)
852 LEFT JOIN ar ON (ar.id = da.trans_id)
853 WHERE (da.dunning_id = ?)|;
855 my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
857 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
859 $form->{TEMPLATE_ARRAYS} = {};
860 map({ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} = []; } keys(%{$ref}));
863 map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest linetotal);
864 map { $form->{$_} = $ref->{$_} } keys %$ref;
865 map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $ref->{$_} } keys %$ref;
871 c.id AS customer_id, c.name, c.street, c.zipcode, c.city,
872 c.country, c.department_1, c.department_2, c.email, c.customernumber,
873 c.greeting, c.contact, c.phone, c.fax, c.homepage,
874 c.email, c.taxincluded, c.business_id, c.taxnumber, c.iban,
879 LEFT JOIN ar ON (d.trans_id = ar.id)
880 LEFT JOIN customer c ON (ar.customer_id = c.id)
881 LEFT JOIN contacts co ON (ar.cp_id = co.cp_id)
882 LEFT JOIN employee e ON (ar.salesman_id = e.id)
883 WHERE (d.dunning_id = ?)
885 my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
886 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
890 cfg.interest_rate, cfg.template AS formname, cfg.dunning_level,
891 cfg.email_subject, cfg.email_body, cfg.email_attachment,
892 d.transdate AS dunning_date,
895 WHERE dunning_id = ?)
897 (SELECT SUM(interest)
899 WHERE dunning_id = ?)
901 (SELECT SUM(amount) - SUM(paid)
906 WHERE dunning_id = ?))
909 LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
910 WHERE d.dunning_id = ?
912 $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id, $dunning_id);
913 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
915 $form->{interest_rate} = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
916 $form->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
917 $form->{total_interest} = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
918 $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{total_open_amount}, 2), 2);
919 $form->{total_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $ref->{total_open_amount}, 2), 2);
921 $::form->format_dates($output_dateformat, $output_longdates,
922 qw(dn_dunning_date dn_dunning_duedate dn_transdate dn_duedate
923 dunning_date dunning_duedate transdate duedate)
925 $::form->reformat_numbers($output_numberformat, 2, qw(
926 dn_amount dn_netamount dn_paid dn_open_amount dn_fee dn_interest dn_linetotal
927 amount netamount paid open_amount fee interest linetotal
928 total_interest total_open_interest total_amount total_open_amount
930 $::form->reformat_numbers($output_numberformat, undef, qw(interest_rate));
932 $self->set_customer_cvars($myconfig, $form);
933 $self->set_template_options($myconfig, $form);
935 my $filename = "dunning_${dunning_id}_" . Common::unique_id() . ".pdf";
936 my $spool = $::lx_office_conf{paths}->{spool};
937 $form->{OUT} = "${spool}/$filename";
938 $form->{keep_tmpfile} = 1;
940 delete $form->{tmpfile};
942 push @{ $form->{DUNNING_PDFS} }, $filename;
943 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$filename",
944 'name' => $form->get_formname_translation('dunning') . "_${dunning_id}.pdf" };
946 my $employee_id = ($::instance_conf->get_dunning_creator eq 'invoice_employee') ?
947 $form->{employee_id} :
948 SL::DB::Manager::Employee->current->id;
950 $form->get_employee_data('prefix' => 'employee', 'id' => $employee_id);
951 $form->get_employee_data('prefix' => 'salesman', 'id' => $form->{salesman_id});
953 $form->{attachment_type} = "dunning";
954 if ( $form->{dunning_level} ) {
955 $form->{attachment_type} .= $form->{dunning_level} if $form->{dunning_level} < 4;
957 $form->{attachment_filename} = $form->get_formname_translation($form->{attachment_type}) . "_${dunning_id}.pdf";
958 $form->{attachment_id} = $form->{invoice_id};
959 $form->parse_template($myconfig);
961 $main::lxdebug->leave_sub();
964 sub print_invoice_for_fees {
965 $main::lxdebug->enter_sub();
967 my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
969 my $dbh = $provided_dbh || SL::DB->client->dbh;
971 my ($query, @values, $sth);
975 d.fee_interest_ar_id,
976 d.trans_id AS invoice_id,
980 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
981 WHERE d.dunning_id = ?|;
982 my ($ar_id, $invoice_id, $template, $dunning_level) = selectrow_query($form, $dbh, $query, $dunning_id);
985 $main::lxdebug->leave_sub();
989 my $saved_form = save_form();
991 $query = qq|SELECT SUM(fee), SUM(interest) FROM dunning WHERE id = ?|;
992 my ($fee_total, $interest_total) = selectrow_query($form, $dbh, $query, $dunning_id);
996 ar.invnumber, ar.transdate AS invdate, ar.amount, ar.netamount,
997 ar.duedate, ar.notes, ar.notes AS invoicenotes, ar.customer_id,
999 c.name, c.department_1, c.department_2, c.street, c.zipcode, c.city, c.country,
1000 c.contact, c.customernumber, c.phone, c.fax, c.email,
1001 c.taxnumber, c.greeting
1004 LEFT JOIN customer c ON (ar.customer_id = c.id)
1006 my $ref = selectfirst_hashref_query($form, $dbh, $query, $ar_id);
1007 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1009 $query = qq|SELECT * FROM employee WHERE login = ?|;
1010 $ref = selectfirst_hashref_query($form, $dbh, $query, $::myconfig{login});
1011 map { $form->{"employee_${_}"} = $ref->{$_} } keys %{ $ref };
1013 $query = qq|SELECT * FROM acc_trans WHERE trans_id = ? ORDER BY acc_trans_id ASC|;
1014 $sth = prepare_execute_query($form, $dbh, $query, $ar_id);
1016 my ($row, $fee, $interest) = (0, 0, 0);
1018 while ($ref = $sth->fetchrow_hashref()) {
1019 next if ($ref->{amount} < 0);
1024 $fee = $ref->{amount};
1026 $interest = $ref->{amount};
1030 $form->{fee} = $form->round_amount($fee, 2);
1031 $form->{interest} = $form->round_amount($interest, 2);
1032 $form->{invamount} = $form->round_amount($fee + $interest, 2);
1033 $form->{dunning_id} = $dunning_id;
1034 $form->{formname} = "${template}_invoice";
1036 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) } qw(fee interest invamount);
1038 $self->set_customer_cvars($myconfig, $form);
1039 $self->set_template_options($myconfig, $form);
1041 my $filename = Common::unique_id() . "dunning_invoice_${dunning_id}.pdf";
1043 my $spool = $::lx_office_conf{paths}->{spool};
1044 $form->{OUT} = "$spool/$filename";
1045 $form->{keep_tmpfile} = 1;
1046 delete $form->{tmpfile};
1048 map { delete $form->{$_} } grep /^[a-z_]+_\d+$/, keys %{ $form };
1050 $form->{attachment_filename} = $form->get_formname_translation('dunning_invoice') . "_${dunning_id}.pdf";
1051 $form->{attachment_type} = "dunning";
1052 $form->{attachment_id} = $form->{invoice_id};
1053 $form->parse_template($myconfig);
1055 restore_form($saved_form);
1057 push @{ $form->{DUNNING_PDFS} }, $filename;
1058 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${spool}/$filename",
1059 'name' => "dunning_invoice_${dunning_id}.pdf" };
1061 $main::lxdebug->leave_sub();
1064 sub set_customer_cvars {
1065 my ($self, $myconfig, $form) = @_;
1067 my $custom_variables = CVar->get_custom_variables(dbh => $form->get_standard_dbh,
1069 trans_id => $form->{customer_id});
1070 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1072 $form->{cp_greeting} = GenericTranslations->get(dbh => $form->get_standard_dbh,
1073 translation_type => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1074 language_id => $form->{language_id},
1075 allow_fallback => 1);
1076 if ($form->{cp_id}) {
1077 $custom_variables = CVar->get_custom_variables(dbh => $form->get_standard_dbh,
1078 module => 'Contacts',
1079 trans_id => $form->{cp_id});
1080 $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1085 sub print_original_invoices {
1086 my ($self, $myconfig, $form, $invoice_id) = @_;
1087 # get one invoice as object and print to pdf
1088 my $invoice = SL::DB::Invoice->new(id => $invoice_id)->load;
1090 die "Invalid invoice object" unless ref($invoice) eq 'SL::DB::Invoice';
1092 my $print_form = Form->new('');
1093 $print_form->{type} = 'invoice';
1094 $print_form->{formname} = 'invoice',
1095 $print_form->{format} = 'pdf',
1096 $print_form->{media} = 'file';
1097 # no language override, should always be the object's language
1098 $invoice->flatten_to_form($print_form, format_amounts => 1);
1099 $print_form->prepare_for_printing;
1101 my $filename = SL::Helper::CreatePDF->create_pdf(
1102 template => 'invoice.tex',
1103 variables => $print_form,
1104 return => 'file_name',
1107 my $spool = $::lx_office_conf{paths}->{spool};
1108 my ($volume, $directory, $file_name) = File::Spec->splitpath($filename);
1109 my $full_file_name = File::Spec->catfile($spool, $file_name);
1111 move($filename, $full_file_name) or die "The move operation failed: $!";
1113 # form get_formname_translation should use language_id_$i
1114 my $saved_reicpient_locale = $form->{recipient_locale};
1115 $form->{recipient_locale} = $invoice->language;
1117 push @{ $form->{DUNNING_PDFS} }, $file_name;
1118 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$file_name",
1119 'name' => $form->get_formname_translation('invoice') . "_" . $invoice->invnumber . ".pdf" };
1121 $form->{recipient_locale} = $saved_reicpient_locale;