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