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