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