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