Original-Rechnung bei Mahnung Drucken: sellprice aus fxsellprice setzen
[kivitendo-erp.git] / SL / DN.pm
1 #======================================================================
2 # LX-Office ERP
3 # Copyright (C) 2006
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
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.
21 #
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,
29 # MA 02110-1335, USA.
30 #======================================================================
31 #
32 # Dunning process module
33 #
34 #======================================================================
35
36 package DN;
37
38 use SL::Common;
39 use SL::DBUtils;
40 use SL::DB::AuthUser;
41 use SL::DB::Default;
42 use SL::DB::Employee;
43 use SL::GenericTranslations;
44 use SL::IS;
45 use SL::Mailer;
46 use SL::MoreCommon;
47 use SL::Template;
48 use SL::DB::Printer;
49 use SL::DB::Language;
50 use SL::TransNumber;
51 use SL::Util qw(trim);
52 use SL::DB;
53
54 use File::Copy;
55
56 use strict;
57
58 sub get_config {
59   $main::lxdebug->enter_sub();
60
61   my ($self, $myconfig, $form) = @_;
62
63   # connect to database
64   my $dbh = SL::DB->client->dbh;
65
66   my $query =
67     qq|SELECT * | .
68     qq|FROM dunning_config | .
69     qq|ORDER BY dunning_level|;
70   $form->{DUNNING} = selectall_hashref_query($form, $dbh, $query);
71
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));
75   }
76
77   $query =
78     qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar, dunning_creator
79        FROM defaults|;
80   ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}, $form->{dunning_creator})
81     = selectrow_query($form, $dbh, $query);
82
83   $main::lxdebug->leave_sub();
84 }
85
86 sub save_config {
87   my ($self, $myconfig, $form) = @_;
88   $main::lxdebug->enter_sub();
89
90   my $rc = SL::DB->client->with_transaction(\&_save_config, $self, $myconfig, $form);
91
92   $::lxdebug->leave_sub;
93   return $rc;
94 }
95
96 sub _save_config {
97   my ($self, $myconfig, $form) = @_;
98
99   my $dbh = SL::DB->client->dbh;
100
101   my ($query, @values);
102
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;
106
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"}) {
117         $query =
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 = ?
126              WHERE id = ?|;
127         push(@values, conv_i($form->{"id_$i"}));
128       } else {
129         $query =
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
136       }
137       do_query($form, $dbh, $query, @values);
138     }
139
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"});
143     }
144   }
145
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);
151
152   return 1;
153 }
154
155 sub create_invoice_for_fees {
156   $main::lxdebug->enter_sub();
157
158   my ($self, $myconfig, $form, $dbh, $dunning_id) = @_;
159
160   my ($query, @values, $sth, $ref);
161
162   $query = qq|SELECT dcfg.create_invoices_for_fees
163               FROM dunning d
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);
167
168   if (!$create_invoices_for_fees) {
169     $main::lxdebug->leave_sub();
170     return;
171   }
172
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);
175
176   $query =
177     qq|SELECT
178          fee,
179          COALESCE((
180            SELECT MAX(d_fee.fee)
181            FROM dunning d_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)
185          ), 0)
186          AS max_previous_fee,
187          interest,
188          COALESCE((
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)
194          ), 0)
195          AS max_previous_interest
196        FROM dunning d
197        WHERE dunning_id = ?|;
198   @values = ($dunning_id, $dunning_id, $dunning_id);
199   $sth = prepare_execute_query($form, $dbh, $query, @values);
200
201   my ($fee_remaining, $interest_remaining) = (0, 0);
202   my ($fee_total, $interest_total) = (0, 0);
203
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);
211   }
212
213   $sth->finish();
214
215   my $amount = $fee_remaining + $interest_remaining;
216
217   if (!$amount) {
218     $main::lxdebug->leave_sub();
219     return;
220   }
221
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);
225
226   $query =
227     qq|INSERT INTO ar (id,          invnumber, transdate, gldate, customer_id,
228                        taxincluded, amount,    netamount, paid,   duedate,
229                        invoice,     currency_id, taxzone_id,      notes,
230                        employee_id)
231        VALUES (
232          ?,                     -- id
233          ?,                     -- invnumber
234          current_date,          -- transdate
235          current_date,          -- gldate
236          -- customer_id:
237          (SELECT ar.customer_id
238           FROM dunning dn
239           LEFT JOIN ar ON (dn.trans_id = ar.id)
240           WHERE dn.dunning_id = ?
241           LIMIT 1),
242          'f',                   -- taxincluded
243          ?,                     -- amount
244          ?,                     -- netamount
245          0,                     -- paid
246          -- duedate:
247          (SELECT duedate FROM dunning WHERE dunning_id = ? LIMIT 1),
248          'f',                   -- invoice
249          (SELECT id FROM currencies WHERE name = ?), -- curr
250          --taxzone_id:
251          (SELECT taxzone_id FROM customer WHERE id =
252           (SELECT ar.customer_id
253            FROM dunning dn
254            LEFT JOIN ar ON (dn.trans_id = ar.id)
255            WHERE dn.dunning_id = ?
256            LIMIT 1)
257          ),
258          ?,                     -- notes
259          -- employee_id:
260          (SELECT id FROM employee WHERE login = ?)
261        )|;
262   @values = ($ar_id,            # id
263              $trans_number->create_unique, # invnumber
264              $dunning_id,       # customer_id
265              $amount,
266              $amount,
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);
273
274   $query =
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);
280
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);
283
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);
287   }
288
289   @values = ($ar_id, conv_i($form->{AR}), -1 * $amount, conv_i($form->{AR}));
290   do_statement($form, $sth, $query, @values);
291
292   $sth->finish();
293
294   $query = qq|UPDATE dunning SET fee_interest_ar_id = ? WHERE dunning_id = ?|;
295   do_query($form, $dbh, $query, $ar_id, $dunning_id);
296
297   $main::lxdebug->leave_sub();
298 }
299
300
301 sub save_dunning {
302   my ($self, $myconfig, $form, $rows) = @_;
303   $main::lxdebug->enter_sub();
304
305   my $rc = SL::DB->client->with_transaction(\&_save_dunning, $self, $myconfig, $form, $rows);
306
307   if (!$rc) {
308     die SL::DB->client->error
309   }
310   $::lxdebug->leave_sub;
311
312   return $rc;
313 }
314
315
316 sub _save_dunning {
317   my ($self, $myconfig, $form, $rows) = @_;
318
319   my $dbh = SL::DB->client->dbh;
320
321   my ($query, @values);
322
323   my ($dunning_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
324
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);
327
328   my $q_insert_dunning =
329     qq|INSERT INTO dunning (dunning_id, dunning_config_id, dunning_level, trans_id,
330                             fee,        interest,          transdate,     duedate)
331        VALUES (?, ?,
332                (SELECT dunning_level FROM dunning_config WHERE id = ?),
333                ?,
334                (SELECT SUM(fee)
335                 FROM dunning_config
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 = ?)
339                  / 360,
340                current_date,
341                current_date + (SELECT payment_terms FROM dunning_config WHERE id = ?))|;
342   my $h_insert_dunning = prepare_query($form, $dbh, $q_insert_dunning);
343
344   my @invoice_ids;
345   my ($next_dunning_config_id, $customer_id);
346   my ($send_email, $print_invoice) = (0, 0);
347
348   foreach my $row (@{ $rows }) {
349     if ($row->{credit_note}) {
350       my $i = $row->{row};
351       %{ $form->{LIST_CREDIT_NOTES}{$row->{customer_id}}{$row->{invoice_id}} } = (
352         open_amount => $form->{"open_amount_$i"},
353         amount      => $form->{"amount_$i"},
354         invnumber   => $form->{"invnumber_$i"},
355         invdate     => $form->{"invdate_$i"},
356       );
357       next;
358     }
359     push @invoice_ids, $row->{invoice_id};
360     $next_dunning_config_id = $row->{next_dunning_config_id};
361     $customer_id            = $row->{customer_id};
362
363     @values = ($row->{next_dunning_config_id}, $row->{invoice_id});
364     do_statement($form, $h_update_ar, $q_update_ar, @values);
365
366     $send_email       |= $row->{email};
367     $print_invoice    |= $row->{print_invoice};
368
369     my $next_config_id = conv_i($row->{next_dunning_config_id});
370     my $invoice_id     = conv_i($row->{invoice_id});
371
372     @values = ($dunning_id,     $next_config_id, $next_config_id,
373                $invoice_id,     $next_config_id, $invoice_id,
374                $next_config_id, $next_config_id);
375     do_statement($form, $h_insert_dunning, $q_insert_dunning, @values);
376   }
377   # die this transaction, because for this customer only credit notes are
378   # selected ...
379   return unless $customer_id;
380
381   $h_update_ar->finish();
382   $h_insert_dunning->finish();
383
384   $form->{DUNNING_PDFS_EMAIL} = [];
385
386   $form->{dunning_id} = $dunning_id;
387
388   $self->create_invoice_for_fees($myconfig, $form, $dbh, $dunning_id);
389
390   $self->print_invoice_for_fees($myconfig, $form, $dunning_id, $dbh);
391   $self->print_dunning($myconfig, $form, $dunning_id, $dbh);
392
393   if ($print_invoice) {
394     $self->print_original_invoices($myconfig, $form, $_, $dbh) for @invoice_ids;
395   }
396
397   if ($send_email) {
398     $self->send_email($myconfig, $form, $dunning_id, $dbh);
399   }
400
401   return 1;
402 }
403
404 sub send_email {
405   $main::lxdebug->enter_sub();
406
407   my ($self, $myconfig, $form, $dunning_id, $dbh) = @_;
408
409   my $query =
410     qq|SELECT
411          dcfg.email_body,     dcfg.email_subject, dcfg.email_attachment,
412          COALESCE (NULLIF(c.invoice_mail, ''), c.email) AS recipient, c.name,
413          (SELECT login from employee where id = ar.employee_id) as invoice_employee_login
414        FROM dunning d
415        LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
416        LEFT JOIN ar                  ON (d.trans_id          = ar.id)
417        LEFT JOIN customer c          ON (ar.customer_id      = c.id)
418        WHERE (d.dunning_id = ?)
419        LIMIT 1|;
420   my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
421
422   # without a recipient, we cannot send a mail
423   if (!$ref || !$ref->{recipient}) {
424     $main::lxdebug->leave_sub();
425     die $main::locale->text("No email recipient for customer #1 defined.", $ref->{name});
426   }
427
428   # without a sender we cannot send a mail
429   # two cases: check mail from 1. current user OR  2. employee who created the invoice
430   my ($from, $sign);
431   if ($::instance_conf->get_dunning_creator eq 'current_employee') {
432     $from = $myconfig->{email};
433     die $main::locale->text('No email for current user #1 defined.', $myconfig->{name}) unless $from;
434   } else {
435     eval {
436       $from = SL::DB::Manager::AuthUser->find_by(login =>  $ref->{invoice_employee_login})->get_config_value("email");
437       $sign = SL::DB::Manager::AuthUser->find_by(login =>  $ref->{invoice_employee_login})->get_config_value("signature");
438       die unless ($from);
439       1;
440     } or die $main::locale->text('No email for user with login #1 defined.', $ref->{invoice_employee_login});
441   }
442
443   my $template     = SL::Template::create(type => 'PlainText', form => $form, myconfig => $myconfig);
444   my $mail         = Mailer->new();
445   $mail->{bcc}     = $form->get_bcc_defaults($myconfig, $form->{bcc});
446   $mail->{from}    = $from;
447   $mail->{to}      = $ref->{recipient};
448   $mail->{subject} = $template->parse_block($ref->{email_subject});
449   $mail->{message} = $template->parse_block($ref->{email_body});
450   my $sign_backup  = $::myconfig{signature};
451   $::myconfig{signature} = $sign if $sign;
452   $mail->{message} .= $form->create_email_signature();
453   $::myconfig{signature} = $sign_backup if $sign;
454
455   $mail->{message} =~ s/\r\n/\n/g;
456
457   if ($ref->{email_attachment} && @{ $form->{DUNNING_PDFS_EMAIL} }) {
458     $mail->{attachments} = $form->{DUNNING_PDFS_EMAIL};
459   }
460
461   $mail->send();
462
463   $main::lxdebug->leave_sub();
464 }
465
466 sub set_template_options {
467   $main::lxdebug->enter_sub();
468
469   my ($self, $myconfig, $form) = @_;
470
471   my $defaults = SL::DB::Default->get;
472   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
473   $form->{templates}    = $defaults->templates;
474   $form->{language}     = $form->get_template_language($myconfig);
475   $form->{printer_code} = $form->get_printer_code($myconfig);
476
477   if ($form->{language} ne "") {
478     $form->{language} = "_" . $form->{language};
479   }
480
481   if ($form->{printer_code} ne "") {
482     $form->{printer_code} = "_" . $form->{printer_code};
483   }
484
485   my $extension = 'html';
486   if ($form->{format} eq 'postscript') {
487     $form->{postscript}   = 1;
488     $extension            = 'tex';
489
490   } elsif ($form->{"format"} =~ /pdf/) {
491     $form->{pdf}          = 1;
492     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
493
494   } elsif ($form->{"format"} =~ /opendocument/) {
495     $form->{opendocument} = 1;
496     $extension            = 'odt';
497   } elsif ($form->{"format"} =~ /excel/) {
498     $form->{excel} = 1;
499     $extension            = 'xls';
500   }
501
502
503   # search for the template
504   my @template_files;
505   push @template_files, "$form->{formname}_email$form->{language}$form->{printer_code}.$extension" if $form->{media} eq 'email';
506   push @template_files, "$form->{formname}$form->{language}$form->{printer_code}.$extension";
507   push @template_files, "$form->{formname}.$extension";
508   push @template_files, "default.$extension";
509
510   $form->{IN} = undef;
511   for my $filename (@template_files) {
512     if (-f ($defaults->templates . "/$filename")) {
513       $form->{IN} = $filename;
514       last;
515     }
516   }
517
518   if (!defined $form->{IN}) {
519     $::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));
520   }
521
522   # prepare meta information for template introspection
523   $form->{template_meta} = {
524     formname  => $form->{formname},
525     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
526     format    => $form->{format},
527     media     => $form->{media},
528     extension => $extension,
529     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
530     today     => DateTime->today,
531   };
532
533   $main::lxdebug->leave_sub();
534 }
535
536 sub get_invoices {
537
538   $main::lxdebug->enter_sub();
539
540   my ($self, $myconfig, $form) = @_;
541
542   # connect to database
543   my $dbh = SL::DB->client->dbh;
544
545   my $where;
546   my @values;
547
548   $form->{customer_id} = $1 if ($form->{customer} =~ /--(\d+)$/);
549
550   if ($form->{customer_id}) {
551     $where .= qq| AND (a.customer_id = ?)|;
552     push(@values, $form->{customer_id});
553
554   } elsif ($form->{customer}) {
555     $where .= qq| AND (ct.name ILIKE ?)|;
556     push(@values, like($form->{customer}));
557   }
558
559   if ($form->{department_id}) {
560     $where .= qq| AND (a.department_id = ?)|;
561     push(@values, $form->{department_id});
562   }
563
564   my %columns = (
565     "ordnumber" => "a.ordnumber",
566     "invnumber" => "a.invnumber",
567     "notes"     => "a.notes",
568     "country"   => "ct.country",
569     );
570   foreach my $key (keys(%columns)) {
571     next unless ($form->{$key});
572     $where .= qq| AND $columns{$key} ILIKE ?|;
573     push(@values, like($form->{$key}));
574   }
575
576   if ($form->{dunning_level}) {
577     $where .= qq| AND nextcfg.id = ?|;
578     push(@values, conv_i($form->{dunning_level}));
579   }
580
581   $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
582   if ($form->{minamount}) {
583     $where .= qq| AND ((a.amount - a.paid) > ?) |;
584     push(@values, trim($form->{minamount}));
585   }
586
587   my $query =
588     qq|SELECT id
589        FROM dunning_config
590        WHERE dunning_level = (SELECT MAX(dunning_level) FROM dunning_config)|;
591   my ($id_for_max_dunning_level) = selectrow_query($form, $dbh, $query);
592
593   if (!$form->{l_include_direct_debit}) {
594     $where .= qq| AND NOT COALESCE(a.direct_debit, FALSE) |;
595   }
596   my $paid = ($form->{l_include_credit_notes}) ? "WHERE (a.paid <> a.amount)" : "WHERE (a.paid < a.amount)";
597
598   $query =
599     qq|SELECT
600          a.id, a.invoice, a.ordnumber, a.transdate, a.invnumber, a.amount, a.language_id,
601          ct.name AS customername, a.customer_id, a.duedate,
602          a.amount - a.paid AS open_amount,
603          a.direct_debit,
604          dep.description as departmentname,
605
606          cfg.dunning_description, cfg.dunning_level,
607
608          d.transdate AS dunning_date, d.duedate AS dunning_duedate,
609          d.fee, d.interest,
610
611          a.duedate + cfg.terms - current_date AS nextlevel,
612          current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
613          current_date + cfg.payment_terms AS next_duedate,
614
615          nextcfg.dunning_description AS next_dunning_description,
616          nextcfg.id AS next_dunning_config_id,
617          nextcfg.terms, nextcfg.active, nextcfg.email, nextcfg.print_original_invoice
618
619        FROM ar a
620
621        LEFT JOIN customer ct ON (a.customer_id = ct.id)
622        LEFT JOIN department dep ON (a.department_id = dep.id)
623        LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
624        LEFT JOIN dunning_config nextcfg ON
625          (nextcfg.id =
626            COALESCE(
627              (SELECT id
628               FROM dunning_config
629               WHERE dunning_level >
630                 COALESCE((SELECT dunning_level
631                           FROM dunning_config
632                           WHERE id = a.dunning_config_id
633                           ORDER BY dunning_level DESC
634                           LIMIT 1),
635                          0)
636               ORDER BY dunning_level ASC
637               LIMIT 1)
638              , ?))
639        LEFT JOIN dunning d ON (d.id = (
640          SELECT MAX(d2.id)
641          FROM dunning d2
642          WHERE (d2.trans_id      = a.id)
643            AND (d2.dunning_level = cfg.dunning_level)
644        ))
645         $paid
646         AND (a.duedate < current_date)
647
648        $where
649
650        ORDER BY a.id, transdate, duedate, name|;
651   my $sth = prepare_execute_query($form, $dbh, $query, $id_for_max_dunning_level, @values);
652
653   $form->{DUNNINGS} = [];
654
655   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
656     next if ($ref->{pastdue} < $ref->{terms});
657     $ref->{credit_note} = 1 if ($ref->{amount} < 0 && $form->{l_include_credit_notes});
658     $ref->{interest} = $form->round_amount($ref->{interest}, 2);
659     push(@{ $form->{DUNNINGS} }, $ref);
660   }
661
662   $sth->finish;
663
664   $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
665   $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
666
667   $main::lxdebug->leave_sub();
668 }
669
670 sub get_dunning {
671
672   $main::lxdebug->enter_sub();
673
674   my ($self, $myconfig, $form) = @_;
675
676   # connect to database
677   my $dbh = SL::DB->client->dbh;
678
679   my $where = qq| WHERE (da.trans_id = a.id)|;
680
681   my @values;
682
683   if ($form->{customer_id}) {
684     $where .= qq| AND (a.customer_id = ?)|;
685     push(@values, $form->{customer_id});
686
687   } elsif ($form->{customer}) {
688     $where .= qq| AND (ct.name ILIKE ?)|;
689     push(@values, like($form->{customer}));
690   }
691
692   my %columns = (
693     "ordnumber" => "a.ordnumber",
694     "invnumber" => "a.invnumber",
695     "notes" => "a.notes",
696     );
697   foreach my $key (keys(%columns)) {
698     next unless ($form->{$key});
699     $where .= qq| AND $columns{$key} ILIKE ?|;
700     push(@values, like($form->{$key}));
701   }
702
703   if ($form->{dunning_level}) {
704     $where .= qq| AND a.dunning_config_id = ?|;
705     push(@values, conv_i($form->{dunning_level}));
706   }
707
708   if ($form->{department_id}) {
709     $where .= qq| AND a.department_id = ?|;
710     push @values, conv_i($form->{department_id});
711   }
712
713   $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
714   if ($form->{minamount}) {
715     $where .= qq| AND ((a.amount - a.paid) > ?) |;
716     push(@values, $form->{minamount});
717   }
718
719   if (!$form->{showold}) {
720     $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
721   }
722
723   if ($form->{transdatefrom}) {
724     $where .= qq| AND a.transdate >= ?|;
725     push(@values, $form->{transdatefrom});
726   }
727   if ($form->{transdateto}) {
728     $where .= qq| AND a.transdate <= ?|;
729     push(@values, $form->{transdateto});
730   }
731   if ($form->{dunningfrom}) {
732     $where .= qq| AND da.transdate >= ?|;
733     push(@values, $form->{dunningfrom});
734   }
735   if ($form->{dunningto}) {
736     $where .= qq| AND da.transdate >= ?|;
737     push(@values, $form->{dunningto});
738   }
739
740   if ($form->{salesman_id}) {
741     $where .= qq| AND a.salesman_id = ?|;
742     push(@values, conv_i($form->{salesman_id}));
743   }
744
745   my %sort_columns = (
746     'dunning_description' => [ qw(dn.dunning_description customername invnumber) ],
747     'customername'        => [ qw(customername invnumber) ],
748     'invnumber'           => [ qw(a.invnumber) ],
749     'transdate'           => [ qw(a.transdate a.invnumber) ],
750     'duedate'             => [ qw(a.duedate a.invnumber) ],
751     'dunning_date'        => [ qw(dunning_date a.invnumber) ],
752     'dunning_duedate'     => [ qw(dunning_duedate a.invnumber) ],
753     'salesman'            => [ qw(salesman) ],
754     );
755
756   my $sortdir   = !defined $form->{sortdir}    ? 'ASC'         : $form->{sortdir} ? 'ASC' : 'DESC';
757   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'customername';
758   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
759
760   my $query =
761     qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount, a.language_id,
762          ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
763          da.interest, dn.dunning_description, da.transdate AS dunning_date,
764          da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id,
765          e2.name AS salesman
766        FROM ar a
767        JOIN customer ct ON (a.customer_id = ct.id)
768        LEFT JOIN employee e2 ON (a.salesman_id = e2.id), dunning da
769        LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
770        $where
771        ORDER BY $sortorder|;
772
773   $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
774
775   foreach my $ref (@{ $form->{DUNNINGS} }) {
776     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
777   }
778
779   $main::lxdebug->leave_sub();
780 }
781
782 sub melt_pdfs {
783
784   $main::lxdebug->enter_sub();
785
786   my ($self, $myconfig, $form, $copies) = @_;
787
788   # Don't allow access outside of $spool.
789   map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
790
791   $copies        *= 1;
792   $copies         = 1 unless $copies;
793   my $spool       = $::lx_office_conf{paths}->{spool};
794   my $inputfiles  = join " ", map { "$spool/$_ " x $copies } @{ $form->{DUNNING_PDFS} };
795   my $dunning_id  = $form->{dunning_id};
796
797   $dunning_id     =~ s|[^\d]||g;
798
799   my $in = IO::File->new($::lx_office_conf{applications}->{ghostscript} . " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=- $inputfiles |");
800   $form->error($main::locale->text('Could not spawn ghostscript.')) unless $in;
801
802   if ($form->{media} eq 'printer') {
803     $form->get_printer_code($myconfig);
804     my $out;
805     if ($form->{printer_command}) {
806       $out = IO::File->new("| $form->{printer_command}");
807     }
808
809     $::locale->with_raw_io($out, sub { $out->print($_) while <$in> });
810
811     $form->error($main::locale->text('Could not spawn the printer command.')) unless $out;
812
813   } else {
814     my $dunning_filename = $form->get_formname_translation('dunning');
815     print qq|Content-Type: Application/PDF\n| .
816           qq|Content-Disposition: attachment; filename="${dunning_filename}_${dunning_id}.pdf"\n\n|;
817
818     $::locale->with_raw_io(\*STDOUT, sub { print while <$in> });
819   }
820
821   $in->close();
822
823   map { unlink("$spool/$_") } @{ $form->{DUNNING_PDFS} };
824
825   $main::lxdebug->leave_sub();
826 }
827
828 sub print_dunning {
829   $main::lxdebug->enter_sub();
830
831   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
832
833   # connect to database
834   my $dbh = $provided_dbh || SL::DB->client->dbh;
835
836   $dunning_id =~ s|[^\d]||g;
837
838   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
839   if ($form->{"language_id"}) {
840     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
841       AM->get_language_details($myconfig, $form, $form->{language_id});
842   } else {
843     $output_dateformat = $myconfig->{dateformat};
844     $output_numberformat = $myconfig->{numberformat};
845     $output_longdates = 1;
846   }
847
848   my $query =
849     qq|SELECT
850          da.fee, da.interest,
851          da.transdate  AS dunning_date,
852          da.duedate    AS dunning_duedate,
853
854          dcfg.template AS formname,
855          dcfg.email_subject, dcfg.email_body, dcfg.email_attachment,
856
857          ar.transdate,       ar.duedate,      ar.customer_id,
858          ar.invnumber,       ar.ordnumber,    ar.cp_id,
859          ar.amount,          ar.netamount,    ar.paid,
860          ar.employee_id,     ar.salesman_id,
861          (SELECT cu.name FROM currencies cu WHERE cu.id = ar.currency_id) AS curr,
862          (SELECT description from department WHERE id = ar.department_id) AS department,
863          ar.amount - ar.paid AS open_amount,
864          ar.amount - ar.paid + da.fee + da.interest AS linetotal
865
866        FROM dunning da
867        LEFT JOIN dunning_config dcfg ON (dcfg.id = da.dunning_config_id)
868        LEFT JOIN ar ON (ar.id = da.trans_id)
869        WHERE (da.dunning_id = ?)|;
870
871   my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
872   my $first = 1;
873   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
874     if ($first) {
875       $form->{TEMPLATE_ARRAYS} = {};
876       map({ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} = []; } keys(%{$ref}));
877       $first = 0;
878     }
879     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest linetotal);
880     map { $form->{$_} = $ref->{$_} } keys %$ref;
881     map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $ref->{$_} } keys %$ref;
882   }
883   $sth->finish();
884
885   # if we have some credit notes to add, do a safety check on the first customer id
886   # and add one entry for each credit note
887   if ($form->{LIST_CREDIT_NOTES} && $form->{LIST_CREDIT_NOTES}->{$form->{TEMPLATE_ARRAYS}->{"dn_customer_id"}[0]}) {
888     my $first_customer_id = $form->{TEMPLATE_ARRAYS}->{"dn_customer_id"}[0];
889     while ( my ($cred_id, $value) = each(%{ $form->{LIST_CREDIT_NOTES}->{$first_customer_id} } ) ) {
890       map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $value->{$_} } keys %{ $value };
891     }
892   }
893   $query =
894     qq|SELECT
895          c.id AS customer_id, c.name,         c.street,       c.zipcode,   c.city,
896          c.country,           c.department_1, c.department_2, c.email,     c.customernumber,
897          c.greeting,          c.contact,      c.phone,        c.fax,       c.homepage,
898          c.email,             c.taxincluded,  c.business_id,  c.taxnumber, c.iban,
899          c.ustid,
900          ar.id AS invoice_id,
901          co.*
902        FROM dunning d
903        LEFT JOIN ar          ON (d.trans_id = ar.id)
904        LEFT JOIN customer c  ON (ar.customer_id = c.id)
905        LEFT JOIN contacts co ON (ar.cp_id = co.cp_id)
906        LEFT JOIN employee e  ON (ar.salesman_id = e.id)
907        WHERE (d.dunning_id = ?)
908        LIMIT 1|;
909   my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
910   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
911
912   $query =
913     qq|SELECT
914          cfg.interest_rate, cfg.template AS formname, cfg.dunning_level,
915          cfg.email_subject, cfg.email_body, cfg.email_attachment,
916          d.transdate AS dunning_date,
917          (SELECT SUM(fee)
918           FROM dunning
919           WHERE dunning_id = ?)
920          AS fee,
921          (SELECT SUM(interest)
922           FROM dunning
923           WHERE dunning_id = ?)
924          AS total_interest,
925          (SELECT SUM(amount) - SUM(paid)
926           FROM ar
927           WHERE id IN
928             (SELECT trans_id
929              FROM dunning
930              WHERE dunning_id = ?))
931          AS total_open_amount
932        FROM dunning d
933        LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
934        WHERE d.dunning_id = ?
935        LIMIT 1|;
936   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id, $dunning_id);
937   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
938
939   $form->{interest_rate}     = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
940   $form->{fee}               = $form->format_amount($myconfig, $ref->{fee}, 2);
941   $form->{total_interest}    = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
942   my $total_open_amount      = $ref->{total_open_amount};
943   if ($form->{l_include_credit_notes}) {
944     # a bit stupid, but redo calc because of credit notes
945     $total_open_amount      = 0;
946     foreach my $amount (@{ $form->{TEMPLATE_ARRAYS}->{dn_open_amount} }) {
947       $total_open_amount += $form->parse_amount($myconfig, $amount, 2);
948     }
949   }
950   $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($total_open_amount, 2), 2);
951   $form->{total_amount}      = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $total_open_amount, 2), 2);
952
953   $::form->format_dates($output_dateformat, $output_longdates,
954     qw(dn_dunning_date dn_dunning_duedate dn_transdate dn_duedate
955           dunning_date    dunning_duedate    transdate    duedate)
956   );
957   $::form->reformat_numbers($output_numberformat, 2, qw(
958     dn_amount dn_netamount dn_paid dn_open_amount dn_fee dn_interest dn_linetotal
959        amount    netamount    paid    open_amount    fee    interest    linetotal
960     total_interest total_open_interest total_amount total_open_amount
961   ));
962   $::form->reformat_numbers($output_numberformat, undef, qw(interest_rate));
963
964   $self->set_customer_cvars($myconfig, $form);
965   $self->set_template_options($myconfig, $form);
966
967   my $filename          = "dunning_${dunning_id}_" . Common::unique_id() . ".pdf";
968   my $spool             = $::lx_office_conf{paths}->{spool};
969   $form->{OUT}          = "${spool}/$filename";
970   $form->{keep_tmpfile} = 1;
971
972   delete $form->{tmpfile};
973
974   push @{ $form->{DUNNING_PDFS} }, $filename;
975   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$filename",
976                                            'name'     => $form->get_formname_translation('dunning') . "_${dunning_id}.pdf" };
977
978   my $employee_id = ($::instance_conf->get_dunning_creator eq 'invoice_employee') ?
979                       $form->{employee_id}                                        :
980                       SL::DB::Manager::Employee->current->id;
981
982   $form->get_employee_data('prefix' => 'employee', 'id' => $employee_id);
983   $form->get_employee_data('prefix' => 'salesman', 'id' => $form->{salesman_id});
984
985   $form->{attachment_type}    = "dunning";
986   if ( $form->{dunning_level} ) {
987     $form->{attachment_type} .= $form->{dunning_level} if $form->{dunning_level} < 4;
988   }
989   $form->{attachment_filename} = $form->get_formname_translation($form->{attachment_type}) . "_${dunning_id}.pdf";
990   $form->{attachment_id} = $form->{invoice_id};
991   $form->parse_template($myconfig);
992
993   $main::lxdebug->leave_sub();
994 }
995
996 sub print_invoice_for_fees {
997   $main::lxdebug->enter_sub();
998
999   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
1000
1001   my $dbh = $provided_dbh || SL::DB->client->dbh;
1002
1003   my ($query, @values, $sth);
1004
1005   $query =
1006     qq|SELECT
1007          d.fee_interest_ar_id,
1008          d.trans_id AS invoice_id,
1009          dcfg.template,
1010          dcfg.dunning_level
1011        FROM dunning d
1012        LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
1013        WHERE d.dunning_id = ?|;
1014   my ($ar_id, $invoice_id, $template, $dunning_level) = selectrow_query($form, $dbh, $query, $dunning_id);
1015
1016   if (!$ar_id) {
1017     $main::lxdebug->leave_sub();
1018     return;
1019   }
1020
1021   my $saved_form = save_form();
1022
1023   $query = qq|SELECT SUM(fee), SUM(interest) FROM dunning WHERE id = ?|;
1024   my ($fee_total, $interest_total) = selectrow_query($form, $dbh, $query, $dunning_id);
1025
1026   $query =
1027     qq|SELECT
1028          ar.invnumber, ar.transdate AS invdate, ar.amount, ar.netamount,
1029          ar.duedate,   ar.notes,     ar.notes AS invoicenotes, ar.customer_id,
1030
1031          c.name,      c.department_1,   c.department_2, c.street, c.zipcode, c.city, c.country,
1032          c.contact,   c.customernumber, c.phone,        c.fax,    c.email,
1033          c.taxnumber, c.greeting
1034
1035        FROM ar
1036        LEFT JOIN customer c ON (ar.customer_id = c.id)
1037        WHERE ar.id = ?|;
1038   my $ref = selectfirst_hashref_query($form, $dbh, $query, $ar_id);
1039   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1040
1041   $query = qq|SELECT * FROM employee WHERE login = ?|;
1042   $ref = selectfirst_hashref_query($form, $dbh, $query, $::myconfig{login});
1043   map { $form->{"employee_${_}"} = $ref->{$_} } keys %{ $ref };
1044
1045   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ? ORDER BY acc_trans_id ASC|;
1046   $sth   = prepare_execute_query($form, $dbh, $query, $ar_id);
1047
1048   my ($row, $fee, $interest) = (0, 0, 0);
1049
1050   while ($ref = $sth->fetchrow_hashref()) {
1051     next if ($ref->{amount} < 0);
1052
1053     $row++;
1054
1055     if ($row == 1) {
1056       $fee = $ref->{amount};
1057     } else {
1058       $interest = $ref->{amount};
1059     }
1060   }
1061
1062   $form->{fee}        = $form->round_amount($fee,             2);
1063   $form->{interest}   = $form->round_amount($interest,        2);
1064   $form->{invamount}  = $form->round_amount($fee + $interest, 2);
1065   $form->{dunning_id} = $dunning_id;
1066   $form->{formname}   = "${template}_invoice";
1067
1068   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) } qw(fee interest invamount);
1069
1070   $self->set_customer_cvars($myconfig, $form);
1071   $self->set_template_options($myconfig, $form);
1072
1073   my $filename = Common::unique_id() . "dunning_invoice_${dunning_id}.pdf";
1074
1075   my $spool             = $::lx_office_conf{paths}->{spool};
1076   $form->{OUT}          = "$spool/$filename";
1077   $form->{keep_tmpfile} = 1;
1078   delete $form->{tmpfile};
1079
1080   map { delete $form->{$_} } grep /^[a-z_]+_\d+$/, keys %{ $form };
1081
1082   $form->{attachment_filename} = $form->get_formname_translation('dunning_invoice') . "_${dunning_id}.pdf";
1083   $form->{attachment_type}     = "dunning";
1084   $form->{attachment_id}       = $form->{invoice_id};
1085   $form->parse_template($myconfig);
1086
1087   restore_form($saved_form);
1088
1089   push @{ $form->{DUNNING_PDFS} }, $filename;
1090   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${spool}/$filename",
1091                                            'name'     => "dunning_invoice_${dunning_id}.pdf" };
1092
1093   $main::lxdebug->leave_sub();
1094 }
1095
1096 sub set_customer_cvars {
1097   my ($self, $myconfig, $form) = @_;
1098
1099   my $custom_variables = CVar->get_custom_variables(dbh      => $form->get_standard_dbh,
1100                                                     module   => 'CT',
1101                                                     trans_id => $form->{customer_id});
1102   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1103
1104   $form->{cp_greeting} = GenericTranslations->get(dbh              => $form->get_standard_dbh,
1105                                                   translation_type => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1106                                                   language_id      => $form->{language_id},
1107                                                   allow_fallback   => 1);
1108   if ($form->{cp_id}) {
1109     $custom_variables = CVar->get_custom_variables(dbh      => $form->get_standard_dbh,
1110                                                    module   => 'Contacts',
1111                                                    trans_id => $form->{cp_id});
1112     $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1113   }
1114
1115 }
1116
1117 sub print_original_invoices {
1118   my ($self, $myconfig, $form, $invoice_id) = @_;
1119   # get one invoice as object and print to pdf
1120   my $invoice = SL::DB::Invoice->new(id => $invoice_id)->load;
1121
1122   die "Invalid invoice object" unless ref($invoice) eq 'SL::DB::Invoice';
1123
1124   my $print_form          = Form->new('');
1125   $print_form->{type}     = 'invoice';
1126   $print_form->{formname} = 'invoice',
1127   $print_form->{format}   = 'pdf',
1128   $print_form->{media}    = 'file';
1129   # no language override, should always be the object's language
1130   $invoice->flatten_to_form($print_form, format_amounts => 1);
1131   for my $i (1 .. $print_form->{rowcount}) {
1132     $print_form->{"sellprice_$i"} = $print_form->{"fxsellprice_$i"};
1133   }
1134   $print_form->prepare_for_printing;
1135
1136   my $filename = SL::Helper::CreatePDF->create_pdf(
1137                    template               => 'invoice.tex',
1138                    variables              => $print_form,
1139                    return                 => 'file_name',
1140                    variable_content_types => {
1141                      longdescription => 'html',
1142                      partnotes       => 'html',
1143                      notes           => 'html',
1144                    },
1145   );
1146
1147   my $spool       = $::lx_office_conf{paths}->{spool};
1148   my ($volume, $directory, $file_name) = File::Spec->splitpath($filename);
1149   my $full_file_name                   = File::Spec->catfile($spool, $file_name);
1150
1151   move($filename, $full_file_name) or die "The move operation failed: $!";
1152
1153   # form get_formname_translation should use language_id_$i
1154   my $saved_reicpient_locale = $form->{recipient_locale};
1155   $form->{recipient_locale}  = $invoice->language;
1156
1157   push @{ $form->{DUNNING_PDFS} }, $file_name;
1158   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$file_name",
1159                                            'name' => $form->get_formname_translation('invoice') . "_" . $invoice->invnumber . ".pdf" };
1160
1161   $form->{recipient_locale}  = $saved_reicpient_locale;
1162 }
1163
1164 1;