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 $form->{"print_original_invoice_$i"} ? 't' : 'f');
116 if ($form->{"id_$i"}) {
118 qq|UPDATE dunning_config SET
119 dunning_level = ?, dunning_description = ?,
120 email_subject = ?, email_body = ?,
121 template = ?, fee = ?, interest_rate = ?,
122 active = ?, auto = ?, email = ?,
123 email_attachment = ?, payment_terms = ?, terms = ?,
124 create_invoices_for_fees = ?,
125 print_original_invoice = ?
127 push(@values, conv_i($form->{"id_$i"}));
130 qq|INSERT INTO dunning_config
131 (dunning_level, dunning_description, email_subject, email_body,
132 template, fee, interest_rate, active, auto, email,
133 email_attachment, payment_terms, terms, create_invoices_for_fees,
134 print_original_invoice)
135 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
137 do_query($form, $dbh, $query, @values);
140 if (($form->{"dunning_description_$i"} eq "") && ($form->{"id_$i"})) {
141 $query = qq|DELETE FROM dunning_config WHERE id = ?|;
142 do_query($form, $dbh, $query, $form->{"id_$i"});
146 $query = qq|UPDATE defaults SET dunning_ar_amount_fee = ?, dunning_ar_amount_interest = ?, dunning_ar = ?,
147 dunning_creator = ?|;
148 @values = (conv_i($form->{AR_amount_fee}), conv_i($form->{AR_amount_interest}), conv_i($form->{AR}),
149 $form->{dunning_creator});
150 do_query($form, $dbh, $query, @values);
155 sub create_invoice_for_fees {
156 $main::lxdebug->enter_sub();
158 my ($self, $myconfig, $form, $dbh, $dunning_id) = @_;
160 my ($query, @values, $sth, $ref);
162 $query = qq|SELECT dcfg.create_invoices_for_fees
164 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
165 WHERE d.dunning_id = ?|;
166 my ($create_invoices_for_fees) = selectrow_query($form, $dbh, $query, $dunning_id);
168 if (!$create_invoices_for_fees) {
169 $main::lxdebug->leave_sub();
173 $query = qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar FROM defaults|;
174 ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}) = selectrow_query($form, $dbh, $query);
180 SELECT MAX(d_fee.fee)
182 WHERE (d_fee.trans_id = d.trans_id)
183 AND (d_fee.dunning_id <> ?)
184 AND NOT (d_fee.fee_interest_ar_id ISNULL)
189 SELECT MAX(d_interest.interest)
190 FROM dunning d_interest
191 WHERE (d_interest.trans_id = d.trans_id)
192 AND (d_interest.dunning_id <> ?)
193 AND NOT (d_interest.fee_interest_ar_id ISNULL)
195 AS max_previous_interest
197 WHERE dunning_id = ?|;
198 @values = ($dunning_id, $dunning_id, $dunning_id);
199 $sth = prepare_execute_query($form, $dbh, $query, @values);
201 my ($fee_remaining, $interest_remaining) = (0, 0);
202 my ($fee_total, $interest_total) = (0, 0);
204 while (my $ref = $sth->fetchrow_hashref()) {
205 $fee_remaining += $form->round_amount($ref->{fee}, 2);
206 $fee_remaining -= $form->round_amount($ref->{max_previous_fee}, 2);
207 $fee_total += $form->round_amount($ref->{fee}, 2);
208 $interest_remaining += $form->round_amount($ref->{interest}, 2);
209 $interest_remaining -= $form->round_amount($ref->{max_previous_interest}, 2);
210 $interest_total += $form->round_amount($ref->{interest}, 2);
215 my $amount = $fee_remaining + $interest_remaining;
218 $main::lxdebug->leave_sub();
222 my ($ar_id) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
223 my $curr = $form->get_default_currency($myconfig);
224 my $trans_number = SL::TransNumber->new(type => 'invoice', dbh => $dbh);
227 qq|INSERT INTO ar (id, invnumber, transdate, gldate, customer_id,
228 taxincluded, amount, netamount, paid, duedate,
229 invoice, currency_id, taxzone_id, notes,
234 current_date, -- transdate
235 current_date, -- gldate
237 (SELECT ar.customer_id
239 LEFT JOIN ar ON (dn.trans_id = ar.id)
240 WHERE dn.dunning_id = ?
247 (SELECT duedate FROM dunning WHERE dunning_id = ? LIMIT 1),
249 (SELECT id FROM currencies WHERE name = ?), -- curr
251 (SELECT taxzone_id FROM customer WHERE id =
252 (SELECT ar.customer_id
254 LEFT JOIN ar ON (dn.trans_id = ar.id)
255 WHERE dn.dunning_id = ?
260 (SELECT id FROM employee WHERE login = ?)
262 @values = ($ar_id, # id
263 $trans_number->create_unique, # invnumber
264 $dunning_id, # customer_id
267 $dunning_id, # duedate
268 $curr, # default currency
269 $dunning_id, # taxzone_id
270 sprintf($main::locale->text('Automatically created invoice for fee and interest for dunning %s'), $dunning_id), # notes
271 $::myconfig{login}); # employee_id
272 do_query($form, $dbh, $query, @values);
275 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, taxkey, tax_id, chart_link)
276 VALUES (?, ?, ?, current_date, current_date, 0,
277 (SELECT id FROM tax WHERE (taxkey = 0) AND (rate = 0)),
278 (SELECT link FROM chart WHERE id = ?))|;
279 $sth = prepare_query($form, $dbh, $query);
281 @values = ($ar_id, conv_i($form->{AR_amount_fee}), $fee_remaining, conv_i($form->{AR_amount_fee}));
282 do_statement($form, $sth, $query, @values);
284 if ($interest_remaining) {
285 @values = ($ar_id, conv_i($form->{AR_amount_interest}), $interest_remaining, conv_i($form->{AR_amount_interest}));
286 do_statement($form, $sth, $query, @values);
289 @values = ($ar_id, conv_i($form->{AR}), -1 * $amount, conv_i($form->{AR}));
290 do_statement($form, $sth, $query, @values);
294 $query = qq|UPDATE dunning SET fee_interest_ar_id = ? WHERE dunning_id = ?|;
295 do_query($form, $dbh, $query, $ar_id, $dunning_id);
297 $main::lxdebug->leave_sub();
302 my ($self, $myconfig, $form, $rows) = @_;
303 $main::lxdebug->enter_sub();
305 my $rc = SL::DB->client->with_transaction(\&_save_dunning, $self, $myconfig, $form, $rows);
308 die SL::DB->client->error
310 $::lxdebug->leave_sub;
317 my ($self, $myconfig, $form, $rows) = @_;
319 my $dbh = SL::DB->client->dbh;
321 my ($query, @values);
323 my ($dunning_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
325 my $q_update_ar = qq|UPDATE ar SET dunning_config_id = ? WHERE id = ?|;
326 my $h_update_ar = prepare_query($form, $dbh, $q_update_ar);
328 my $q_insert_dunning =
329 qq|INSERT INTO dunning (dunning_id, dunning_config_id, dunning_level, trans_id,
330 fee, interest, transdate, duedate)
332 (SELECT dunning_level FROM dunning_config WHERE id = ?),
336 WHERE dunning_level <= (SELECT dunning_level FROM dunning_config WHERE id = ?)),
337 (SELECT (amount - paid) * (current_date - duedate) FROM ar WHERE id = ?)
338 * (SELECT interest_rate FROM dunning_config WHERE id = ?)
341 current_date + (SELECT payment_terms FROM dunning_config WHERE id = ?))|;
342 my $h_insert_dunning = prepare_query($form, $dbh, $q_insert_dunning);
345 my ($next_dunning_config_id, $customer_id);
346 my ($send_email, $print_invoice) = (0, 0);
348 foreach my $row (@{ $rows }) {
349 push @invoice_ids, $row->{invoice_id};
350 $next_dunning_config_id = $row->{next_dunning_config_id};
351 $customer_id = $row->{customer_id};
353 @values = ($row->{next_dunning_config_id}, $row->{invoice_id});
354 do_statement($form, $h_update_ar, $q_update_ar, @values);
356 $send_email |= $row->{email};
357 $print_invoice |= $row->{print_invoice};
359 my $next_config_id = conv_i($row->{next_dunning_config_id});
360 my $invoice_id = conv_i($row->{invoice_id});
362 @values = ($dunning_id, $next_config_id, $next_config_id,
363 $invoice_id, $next_config_id, $invoice_id,
364 $next_config_id, $next_config_id);
365 do_statement($form, $h_insert_dunning, $q_insert_dunning, @values);
368 $h_update_ar->finish();
369 $h_insert_dunning->finish();
371 $form->{DUNNING_PDFS_EMAIL} = [];
373 $form->{dunning_id} = $dunning_id;
375 $self->create_invoice_for_fees($myconfig, $form, $dbh, $dunning_id);
377 $self->print_invoice_for_fees($myconfig, $form, $dunning_id, $dbh);
378 $self->print_dunning($myconfig, $form, $dunning_id, $dbh);
380 if ($print_invoice) {
381 $self->print_original_invoices($myconfig, $form, $_, $dbh) for @invoice_ids;
385 $self->send_email($myconfig, $form, $dunning_id, $dbh);
392 $main::lxdebug->enter_sub();
394 my ($self, $myconfig, $form, $dunning_id, $dbh) = @_;
398 dcfg.email_body, dcfg.email_subject, dcfg.email_attachment,
399 COALESCE (NULLIF(c.invoice_mail, ''), c.email) AS recipient, c.name,
400 (SELECT login from employee where id = ar.employee_id) as invoice_employee_login
402 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
403 LEFT JOIN ar ON (d.trans_id = ar.id)
404 LEFT JOIN customer c ON (ar.customer_id = c.id)
405 WHERE (d.dunning_id = ?)
407 my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
409 # without a recipient, we cannot send a mail
410 if (!$ref || !$ref->{recipient}) {
411 $main::lxdebug->leave_sub();
412 die $main::locale->text("No email recipient for customer #1 defined.", $ref->{name});
415 # without a sender we cannot send a mail
416 # two cases: check mail from 1. current user OR 2. employee who created the invoice
418 if ($::instance_conf->get_dunning_creator eq 'current_employee') {
419 $from = $myconfig->{email};
420 die $main::locale->text('No email for current user #1 defined.', $myconfig->{name}) unless $from;
423 $from = SL::DB::Manager::AuthUser->find_by(login => $ref->{invoice_employee_login})->get_config_value("email");
424 $sign = SL::DB::Manager::AuthUser->find_by(login => $ref->{invoice_employee_login})->get_config_value("signature");
427 } or die $main::locale->text('No email for user with login #1 defined.', $ref->{invoice_employee_login});
430 my $template = SL::Template::create(type => 'PlainText', form => $form, myconfig => $myconfig);
431 my $mail = Mailer->new();
432 $mail->{bcc} = $form->get_bcc_defaults($myconfig, $form->{bcc});
433 $mail->{from} = $from;
434 $mail->{to} = $ref->{recipient};
435 $mail->{subject} = $template->parse_block($ref->{email_subject});
436 $mail->{message} = $template->parse_block($ref->{email_body});
437 my $sign_backup = $::myconfig{signature};
438 $::myconfig{signature} = $sign if $sign;
439 $mail->{message} .= $form->create_email_signature();
440 $::myconfig{signature} = $sign_backup if $sign;
442 $mail->{message} =~ s/\r\n/\n/g;
444 if ($ref->{email_attachment} && @{ $form->{DUNNING_PDFS_EMAIL} }) {
445 $mail->{attachments} = $form->{DUNNING_PDFS_EMAIL};
450 $main::lxdebug->leave_sub();
453 sub set_template_options {
454 $main::lxdebug->enter_sub();
456 my ($self, $myconfig, $form) = @_;
458 my $defaults = SL::DB::Default->get;
459 $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
460 $form->{templates} = $defaults->templates;
461 $form->{language} = $form->get_template_language($myconfig);
462 $form->{printer_code} = $form->get_printer_code($myconfig);
464 if ($form->{language} ne "") {
465 $form->{language} = "_" . $form->{language};
468 if ($form->{printer_code} ne "") {
469 $form->{printer_code} = "_" . $form->{printer_code};
472 my $extension = 'html';
473 if ($form->{format} eq 'postscript') {
474 $form->{postscript} = 1;
477 } elsif ($form->{"format"} =~ /pdf/) {
479 $extension = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
481 } elsif ($form->{"format"} =~ /opendocument/) {
482 $form->{opendocument} = 1;
484 } elsif ($form->{"format"} =~ /excel/) {
490 # search for the template
492 push @template_files, "$form->{formname}_email$form->{language}$form->{printer_code}.$extension" if $form->{media} eq 'email';
493 push @template_files, "$form->{formname}$form->{language}$form->{printer_code}.$extension";
494 push @template_files, "$form->{formname}.$extension";
495 push @template_files, "default.$extension";
498 for my $filename (@template_files) {
499 if (-f ($defaults->templates . "/$filename")) {
500 $form->{IN} = $filename;
505 if (!defined $form->{IN}) {
506 $::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));
509 # prepare meta information for template introspection
510 $form->{template_meta} = {
511 formname => $form->{formname},
512 language => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
513 format => $form->{format},
514 media => $form->{media},
515 extension => $extension,
516 printer => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
517 today => DateTime->today,
520 $main::lxdebug->leave_sub();
525 $main::lxdebug->enter_sub();
527 my ($self, $myconfig, $form) = @_;
529 # connect to database
530 my $dbh = SL::DB->client->dbh;
535 $form->{customer_id} = $1 if ($form->{customer} =~ /--(\d+)$/);
537 if ($form->{customer_id}) {
538 $where .= qq| AND (a.customer_id = ?)|;
539 push(@values, $form->{customer_id});
541 } elsif ($form->{customer}) {
542 $where .= qq| AND (ct.name ILIKE ?)|;
543 push(@values, like($form->{customer}));
546 if ($form->{department_id}) {
547 $where .= qq| AND (a.department_id = ?)|;
548 push(@values, $form->{department_id});
552 "ordnumber" => "a.ordnumber",
553 "invnumber" => "a.invnumber",
554 "notes" => "a.notes",
555 "country" => "ct.country",
557 foreach my $key (keys(%columns)) {
558 next unless ($form->{$key});
559 $where .= qq| AND $columns{$key} ILIKE ?|;
560 push(@values, like($form->{$key}));
563 if ($form->{dunning_level}) {
564 $where .= qq| AND nextcfg.id = ?|;
565 push(@values, conv_i($form->{dunning_level}));
568 $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
569 if ($form->{minamount}) {
570 $where .= qq| AND ((a.amount - a.paid) > ?) |;
571 push(@values, trim($form->{minamount}));
577 WHERE dunning_level = (SELECT MAX(dunning_level) FROM dunning_config)|;
578 my ($id_for_max_dunning_level) = selectrow_query($form, $dbh, $query);
580 if (!$form->{l_include_direct_debit}) {
581 $where .= qq| AND NOT COALESCE(a.direct_debit, FALSE) |;
586 a.id, a.invoice, a.ordnumber, a.transdate, a.invnumber, a.amount, a.language_id,
587 ct.name AS customername, a.customer_id, a.duedate,
588 a.amount - a.paid AS open_amount,
590 dep.description as departmentname,
592 cfg.dunning_description, cfg.dunning_level,
594 d.transdate AS dunning_date, d.duedate AS dunning_duedate,
597 a.duedate + cfg.terms - current_date AS nextlevel,
598 current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
599 current_date + cfg.payment_terms AS next_duedate,
601 nextcfg.dunning_description AS next_dunning_description,
602 nextcfg.id AS next_dunning_config_id,
603 nextcfg.terms, nextcfg.active, nextcfg.email, nextcfg.print_original_invoice
607 LEFT JOIN customer ct ON (a.customer_id = ct.id)
608 LEFT JOIN department dep ON (a.department_id = dep.id)
609 LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
610 LEFT JOIN dunning_config nextcfg ON
615 WHERE dunning_level >
616 COALESCE((SELECT dunning_level
618 WHERE id = a.dunning_config_id
619 ORDER BY dunning_level DESC
622 ORDER BY dunning_level ASC
625 LEFT JOIN dunning d ON (d.id = (
628 WHERE (d2.trans_id = a.id)
629 AND (d2.dunning_level = cfg.dunning_level)
632 WHERE (a.paid < a.amount)
633 AND (a.duedate < current_date)
637 ORDER BY a.id, transdate, duedate, name|;
638 my $sth = prepare_execute_query($form, $dbh, $query, $id_for_max_dunning_level, @values);
640 $form->{DUNNINGS} = [];
642 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
643 next if ($ref->{pastdue} < $ref->{terms});
645 $ref->{interest} = $form->round_amount($ref->{interest}, 2);
646 push(@{ $form->{DUNNINGS} }, $ref);
651 $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
652 $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
654 $main::lxdebug->leave_sub();
659 $main::lxdebug->enter_sub();
661 my ($self, $myconfig, $form) = @_;
663 # connect to database
664 my $dbh = SL::DB->client->dbh;
666 my $where = qq| WHERE (da.trans_id = a.id)|;
670 if ($form->{customer_id}) {
671 $where .= qq| AND (a.customer_id = ?)|;
672 push(@values, $form->{customer_id});
674 } elsif ($form->{customer}) {
675 $where .= qq| AND (ct.name ILIKE ?)|;
676 push(@values, like($form->{customer}));
680 "ordnumber" => "a.ordnumber",
681 "invnumber" => "a.invnumber",
682 "notes" => "a.notes",
684 foreach my $key (keys(%columns)) {
685 next unless ($form->{$key});
686 $where .= qq| AND $columns{$key} ILIKE ?|;
687 push(@values, like($form->{$key}));
690 if ($form->{dunning_level}) {
691 $where .= qq| AND a.dunning_config_id = ?|;
692 push(@values, conv_i($form->{dunning_level}));
695 if ($form->{department_id}) {
696 $where .= qq| AND a.department_id = ?|;
697 push @values, conv_i($form->{department_id});
700 $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
701 if ($form->{minamount}) {
702 $where .= qq| AND ((a.amount - a.paid) > ?) |;
703 push(@values, $form->{minamount});
706 if (!$form->{showold}) {
707 $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
710 if ($form->{transdatefrom}) {
711 $where .= qq| AND a.transdate >= ?|;
712 push(@values, $form->{transdatefrom});
714 if ($form->{transdateto}) {
715 $where .= qq| AND a.transdate <= ?|;
716 push(@values, $form->{transdateto});
718 if ($form->{dunningfrom}) {
719 $where .= qq| AND da.transdate >= ?|;
720 push(@values, $form->{dunningfrom});
722 if ($form->{dunningto}) {
723 $where .= qq| AND da.transdate >= ?|;
724 push(@values, $form->{dunningto});
727 if ($form->{salesman_id}) {
728 $where .= qq| AND a.salesman_id = ?|;
729 push(@values, conv_i($form->{salesman_id}));
733 'dunning_description' => [ qw(dn.dunning_description customername invnumber) ],
734 'customername' => [ qw(customername invnumber) ],
735 'invnumber' => [ qw(a.invnumber) ],
736 'transdate' => [ qw(a.transdate a.invnumber) ],
737 'duedate' => [ qw(a.duedate a.invnumber) ],
738 'dunning_date' => [ qw(dunning_date a.invnumber) ],
739 'dunning_duedate' => [ qw(dunning_duedate a.invnumber) ],
740 'salesman' => [ qw(salesman) ],
743 my $sortdir = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
744 my $sortkey = $sort_columns{$form->{sort}} ? $form->{sort} : 'customername';
745 my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
748 qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount, a.language_id,
749 ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
750 da.interest, dn.dunning_description, da.transdate AS dunning_date,
751 da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id,
754 JOIN customer ct ON (a.customer_id = ct.id)
755 LEFT JOIN employee e2 ON (a.salesman_id = e2.id), dunning da
756 LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
758 ORDER BY $sortorder|;
760 $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
762 foreach my $ref (@{ $form->{DUNNINGS} }) {
763 map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
766 $main::lxdebug->leave_sub();
771 $main::lxdebug->enter_sub();
773 my ($self, $myconfig, $form, $copies) = @_;
775 # Don't allow access outside of $spool.
776 map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
779 $copies = 1 unless $copies;
780 my $spool = $::lx_office_conf{paths}->{spool};
781 my $inputfiles = join " ", map { "$spool/$_ " x $copies } @{ $form->{DUNNING_PDFS} };
782 my $dunning_id = $form->{dunning_id};
784 $dunning_id =~ s|[^\d]||g;
786 my $in = IO::File->new($::lx_office_conf{applications}->{ghostscript} . " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=- $inputfiles |");
787 $form->error($main::locale->text('Could not spawn ghostscript.')) unless $in;
789 if ($form->{media} eq 'printer') {
790 $form->get_printer_code($myconfig);
792 if ($form->{printer_command}) {
793 $out = IO::File->new("| $form->{printer_command}");
796 $::locale->with_raw_io($out, sub { $out->print($_) while <$in> });
798 $form->error($main::locale->text('Could not spawn the printer command.')) unless $out;
801 my $dunning_filename = $form->get_formname_translation('dunning');
802 print qq|Content-Type: Application/PDF\n| .
803 qq|Content-Disposition: attachment; filename="${dunning_filename}_${dunning_id}.pdf"\n\n|;
805 $::locale->with_raw_io(\*STDOUT, sub { print while <$in> });
810 map { unlink("$spool/$_") } @{ $form->{DUNNING_PDFS} };
812 $main::lxdebug->leave_sub();
816 $main::lxdebug->enter_sub();
818 my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
820 # connect to database
821 my $dbh = $provided_dbh || SL::DB->client->dbh;
823 $dunning_id =~ s|[^\d]||g;
825 my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
826 if ($form->{"language_id"}) {
827 ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
828 AM->get_language_details($myconfig, $form, $form->{language_id});
830 $output_dateformat = $myconfig->{dateformat};
831 $output_numberformat = $myconfig->{numberformat};
832 $output_longdates = 1;
838 da.transdate AS dunning_date,
839 da.duedate AS dunning_duedate,
841 dcfg.template AS formname,
842 dcfg.email_subject, dcfg.email_body, dcfg.email_attachment,
844 ar.transdate, ar.duedate, ar.customer_id,
845 ar.invnumber, ar.ordnumber, ar.cp_id,
846 ar.amount, ar.netamount, ar.paid,
847 ar.employee_id, ar.salesman_id,
848 (SELECT cu.name FROM currencies cu WHERE cu.id = ar.currency_id) AS curr,
849 (SELECT description from department WHERE id = ar.department_id) AS department,
850 ar.amount - ar.paid AS open_amount,
851 ar.amount - ar.paid + da.fee + da.interest AS linetotal
854 LEFT JOIN dunning_config dcfg ON (dcfg.id = da.dunning_config_id)
855 LEFT JOIN ar ON (ar.id = da.trans_id)
856 WHERE (da.dunning_id = ?)|;
858 my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
860 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
862 $form->{TEMPLATE_ARRAYS} = {};
863 map({ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} = []; } keys(%{$ref}));
866 map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest linetotal);
867 map { $form->{$_} = $ref->{$_} } keys %$ref;
868 map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $ref->{$_} } keys %$ref;
874 c.id AS customer_id, c.name, c.street, c.zipcode, c.city,
875 c.country, c.department_1, c.department_2, c.email, c.customernumber,
876 c.greeting, c.contact, c.phone, c.fax, c.homepage,
877 c.email, c.taxincluded, c.business_id, c.taxnumber, c.iban,
882 LEFT JOIN ar ON (d.trans_id = ar.id)
883 LEFT JOIN customer c ON (ar.customer_id = c.id)
884 LEFT JOIN contacts co ON (ar.cp_id = co.cp_id)
885 LEFT JOIN employee e ON (ar.salesman_id = e.id)
886 WHERE (d.dunning_id = ?)
888 my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
889 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
893 cfg.interest_rate, cfg.template AS formname, cfg.dunning_level,
894 cfg.email_subject, cfg.email_body, cfg.email_attachment,
895 d.transdate AS dunning_date,
898 WHERE dunning_id = ?)
900 (SELECT SUM(interest)
902 WHERE dunning_id = ?)
904 (SELECT SUM(amount) - SUM(paid)
909 WHERE dunning_id = ?))
912 LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
913 WHERE d.dunning_id = ?
915 $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id, $dunning_id);
916 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
918 $form->{interest_rate} = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
919 $form->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
920 $form->{total_interest} = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
921 $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{total_open_amount}, 2), 2);
922 $form->{total_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $ref->{total_open_amount}, 2), 2);
924 $::form->format_dates($output_dateformat, $output_longdates,
925 qw(dn_dunning_date dn_dunning_duedate dn_transdate dn_duedate
926 dunning_date dunning_duedate transdate duedate)
928 $::form->reformat_numbers($output_numberformat, 2, qw(
929 dn_amount dn_netamount dn_paid dn_open_amount dn_fee dn_interest dn_linetotal
930 amount netamount paid open_amount fee interest linetotal
931 total_interest total_open_interest total_amount total_open_amount
933 $::form->reformat_numbers($output_numberformat, undef, qw(interest_rate));
935 $self->set_customer_cvars($myconfig, $form);
936 $self->set_template_options($myconfig, $form);
938 my $filename = "dunning_${dunning_id}_" . Common::unique_id() . ".pdf";
939 my $spool = $::lx_office_conf{paths}->{spool};
940 $form->{OUT} = "${spool}/$filename";
941 $form->{keep_tmpfile} = 1;
943 delete $form->{tmpfile};
945 push @{ $form->{DUNNING_PDFS} }, $filename;
946 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$filename",
947 'name' => $form->get_formname_translation('dunning') . "_${dunning_id}.pdf" };
949 my $employee_id = ($::instance_conf->get_dunning_creator eq 'invoice_employee') ?
950 $form->{employee_id} :
951 SL::DB::Manager::Employee->current->id;
953 $form->get_employee_data('prefix' => 'employee', 'id' => $employee_id);
954 $form->get_employee_data('prefix' => 'salesman', 'id' => $form->{salesman_id});
956 $form->{attachment_type} = "dunning";
957 if ( $form->{dunning_level} ) {
958 $form->{attachment_type} .= $form->{dunning_level} if $form->{dunning_level} < 4;
960 $form->{attachment_filename} = $form->get_formname_translation($form->{attachment_type}) . "_${dunning_id}.pdf";
961 $form->{attachment_id} = $form->{invoice_id};
962 $form->parse_template($myconfig);
964 $main::lxdebug->leave_sub();
967 sub print_invoice_for_fees {
968 $main::lxdebug->enter_sub();
970 my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
972 my $dbh = $provided_dbh || SL::DB->client->dbh;
974 my ($query, @values, $sth);
978 d.fee_interest_ar_id,
979 d.trans_id AS invoice_id,
983 LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
984 WHERE d.dunning_id = ?|;
985 my ($ar_id, $invoice_id, $template, $dunning_level) = selectrow_query($form, $dbh, $query, $dunning_id);
988 $main::lxdebug->leave_sub();
992 my $saved_form = save_form();
994 $query = qq|SELECT SUM(fee), SUM(interest) FROM dunning WHERE id = ?|;
995 my ($fee_total, $interest_total) = selectrow_query($form, $dbh, $query, $dunning_id);
999 ar.invnumber, ar.transdate AS invdate, ar.amount, ar.netamount,
1000 ar.duedate, ar.notes, ar.notes AS invoicenotes, ar.customer_id,
1002 c.name, c.department_1, c.department_2, c.street, c.zipcode, c.city, c.country,
1003 c.contact, c.customernumber, c.phone, c.fax, c.email,
1004 c.taxnumber, c.greeting
1007 LEFT JOIN customer c ON (ar.customer_id = c.id)
1009 my $ref = selectfirst_hashref_query($form, $dbh, $query, $ar_id);
1010 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1012 $query = qq|SELECT * FROM employee WHERE login = ?|;
1013 $ref = selectfirst_hashref_query($form, $dbh, $query, $::myconfig{login});
1014 map { $form->{"employee_${_}"} = $ref->{$_} } keys %{ $ref };
1016 $query = qq|SELECT * FROM acc_trans WHERE trans_id = ? ORDER BY acc_trans_id ASC|;
1017 $sth = prepare_execute_query($form, $dbh, $query, $ar_id);
1019 my ($row, $fee, $interest) = (0, 0, 0);
1021 while ($ref = $sth->fetchrow_hashref()) {
1022 next if ($ref->{amount} < 0);
1027 $fee = $ref->{amount};
1029 $interest = $ref->{amount};
1033 $form->{fee} = $form->round_amount($fee, 2);
1034 $form->{interest} = $form->round_amount($interest, 2);
1035 $form->{invamount} = $form->round_amount($fee + $interest, 2);
1036 $form->{dunning_id} = $dunning_id;
1037 $form->{formname} = "${template}_invoice";
1039 map { $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) } qw(fee interest invamount);
1041 $self->set_customer_cvars($myconfig, $form);
1042 $self->set_template_options($myconfig, $form);
1044 my $filename = Common::unique_id() . "dunning_invoice_${dunning_id}.pdf";
1046 my $spool = $::lx_office_conf{paths}->{spool};
1047 $form->{OUT} = "$spool/$filename";
1048 $form->{keep_tmpfile} = 1;
1049 delete $form->{tmpfile};
1051 map { delete $form->{$_} } grep /^[a-z_]+_\d+$/, keys %{ $form };
1053 $form->{attachment_filename} = $form->get_formname_translation('dunning_invoice') . "_${dunning_id}.pdf";
1054 $form->{attachment_type} = "dunning";
1055 $form->{attachment_id} = $form->{invoice_id};
1056 $form->parse_template($myconfig);
1058 restore_form($saved_form);
1060 push @{ $form->{DUNNING_PDFS} }, $filename;
1061 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${spool}/$filename",
1062 'name' => "dunning_invoice_${dunning_id}.pdf" };
1064 $main::lxdebug->leave_sub();
1067 sub set_customer_cvars {
1068 my ($self, $myconfig, $form) = @_;
1070 my $custom_variables = CVar->get_custom_variables(dbh => $form->get_standard_dbh,
1072 trans_id => $form->{customer_id});
1073 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1075 $form->{cp_greeting} = GenericTranslations->get(dbh => $form->get_standard_dbh,
1076 translation_type => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1077 language_id => $form->{language_id},
1078 allow_fallback => 1);
1079 if ($form->{cp_id}) {
1080 $custom_variables = CVar->get_custom_variables(dbh => $form->get_standard_dbh,
1081 module => 'Contacts',
1082 trans_id => $form->{cp_id});
1083 $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1088 sub print_original_invoices {
1089 my ($self, $myconfig, $form, $invoice_id) = @_;
1090 # get one invoice as object and print to pdf
1091 my $invoice = SL::DB::Invoice->new(id => $invoice_id)->load;
1093 die "Invalid invoice object" unless ref($invoice) eq 'SL::DB::Invoice';
1095 my $print_form = Form->new('');
1096 $print_form->{type} = 'invoice';
1097 $print_form->{formname} = 'invoice',
1098 $print_form->{format} = 'pdf',
1099 $print_form->{media} = 'file';
1100 # no language override, should always be the object's language
1101 $invoice->flatten_to_form($print_form, format_amounts => 1);
1102 $print_form->prepare_for_printing;
1104 my $filename = SL::Helper::CreatePDF->create_pdf(
1105 template => 'invoice.tex',
1106 variables => $print_form,
1107 return => 'file_name',
1108 variable_content_types => {
1109 longdescription => 'html',
1110 partnotes => 'html',
1115 my $spool = $::lx_office_conf{paths}->{spool};
1116 my ($volume, $directory, $file_name) = File::Spec->splitpath($filename);
1117 my $full_file_name = File::Spec->catfile($spool, $file_name);
1119 move($filename, $full_file_name) or die "The move operation failed: $!";
1121 # form get_formname_translation should use language_id_$i
1122 my $saved_reicpient_locale = $form->{recipient_locale};
1123 $form->{recipient_locale} = $invoice->language;
1125 push @{ $form->{DUNNING_PDFS} }, $file_name;
1126 push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$file_name",
1127 'name' => $form->get_formname_translation('invoice') . "_" . $invoice->invnumber . ".pdf" };
1129 $form->{recipient_locale} = $saved_reicpient_locale;