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