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