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