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