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