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