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