Den Rest von dn.pl auf die Verwendung von HTML-Vorlagen umgestellt.
[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::Template;
38 use SL::IS;
39 use SL::Common;
40 use SL::DBUtils;
41 use Data::Dumper;
42
43 sub get_config {
44   $main::lxdebug->enter_sub();
45
46   my ($self, $myconfig, $form) = @_;
47
48   # connect to database
49   my $dbh = $form->dbconnect($myconfig);
50
51   my $query =
52     qq|SELECT * | .
53     qq|FROM dunning_config | .
54     qq|ORDER BY dunning_level|;
55   $form->{DUNNING} = selectall_hashref_query($form, $dbh, $query);
56
57   foreach my $ref (@{ $form->{DUNNING} }) {
58     $ref->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
59     $ref->{interest_rate} = $form->format_amount($myconfig, ($ref->{interest_rate} * 100));
60   }
61
62   $dbh->disconnect();
63
64   $main::lxdebug->leave_sub();
65 }
66
67 sub save_config {
68   $main::lxdebug->enter_sub();
69
70   my ($self, $myconfig, $form) = @_;
71
72   # connect to database
73   my $dbh = $form->dbconnect_noauto($myconfig);
74
75   my ($query, @values);
76
77   for my $i (1 .. $form->{rowcount}) {
78     $form->{"fee_$i"} = $form->parse_amount($myconfig, $form->{"fee_$i"}) * 1;
79     $form->{"interest_rate_$i"} = $form->parse_amount($myconfig, $form->{"interest_rate_$i"}) / 100;
80
81     if (($form->{"dunning_level_$i"} ne "") &&
82         ($form->{"dunning_description_$i"} ne "")) {
83       @values = (conv_i($form->{"dunning_level_$i"}), $form->{"dunning_description_$i"},
84                  $form->{"email_subject_$i"}, $form->{"email_body_$i"},
85                  $form->{"template_$i"}, $form->{"fee_$i"}, $form->{"interest_rate_$i"},
86                  $form->{"active_$i"} ? 't' : 'f', $form->{"auto_$i"} ? 't' : 'f', $form->{"email_$i"} ? 't' : 'f',
87                  $form->{"email_attachment_$i"} ? 't' : 'f', conv_i($form->{"payment_terms_$i"}), conv_i($form->{"terms_$i"}));
88       if ($form->{"id_$i"}) {
89         $query =
90           qq|UPDATE dunning_config SET
91                dunning_level = ?, dunning_description = ?,
92                email_subject = ?, email_body = ?,
93                template = ?, fee = ?, interest_rate = ?,
94                active = ?, auto = ?, email = ?,
95                email_attachment = ?, payment_terms = ?, terms = ?
96              WHERE id = ?|;
97         push(@values, conv_i($form->{"id_$i"}));
98       } else {
99         $query =
100           qq|INSERT INTO dunning_config
101                (dunning_level, dunning_description, email_subject, email_body,
102                 template, fee, interest_rate, active, auto, email,
103                 email_attachment, payment_terms, terms)
104              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
105       }
106       do_query($form, $dbh, $query, @values);
107     }
108
109     if (($form->{"dunning_description_$i"} eq "") && ($form->{"id_$i"})) {
110       $query = qq|DELETE FROM dunning_config WHERE id = ?|;
111       do_query($form, $dbh, $query, $form->{"id_$i"});
112     }
113   }
114
115   $dbh->commit;
116   $dbh->disconnect;
117
118   $main::lxdebug->leave_sub();
119 }
120
121 sub save_dunning {
122   $main::lxdebug->enter_sub();
123
124   my ($self, $myconfig, $form, $rows, $userspath, $spool, $sendmail) = @_;
125   # connect to database
126   my $dbh = $form->dbconnect_noauto($myconfig);
127
128   my ($query, @values);
129
130   my ($dunning_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
131
132   my $q_update_ar = qq|UPDATE ar SET dunning_config_id = ? WHERE id = ?|;
133   my $h_update_ar = prepare_query($form, $dbh, $q_update_ar);
134
135   my $q_insert_dunning =
136     qq|INSERT INTO dunning (dunning_id, dunning_config_id, dunning_level,
137                             trans_id, fee, interest, transdate, duedate)
138        VALUES (?, ?,
139                (SELECT dunning_level FROM dunning_config WHERE id = ?),
140                ?,
141                (SELECT SUM(fee)
142                 FROM dunning_config
143                 WHERE dunning_level <= (SELECT dunning_level FROM dunning_config WHERE id = ?)),
144                (SELECT (amount - paid) * (current_date - transdate) FROM ar WHERE id = ?)
145                  * (SELECT interest_rate FROM dunning_config WHERE id = ?)
146                  / 360,
147                current_date,
148                current_date + (SELECT payment_terms FROM dunning_config WHERE id = ?))|;
149   my $h_insert_dunning = prepare_query($form, $dbh, $q_insert_dunning);
150
151   my @invoice_ids;
152   my ($next_dunning_config_id, $customer_id);
153   my $send_email = 0;
154
155   foreach my $row (@{ $rows }) {
156     push @invoice_ids, $row->{invoice_id};
157     $next_dunning_config_id = $row->{next_dunning_config_id};
158     $customer_id            = $row->{customer_id};
159
160     @values = ($row->{next_dunning_config_id}, $row->{invoice_id});
161     do_statement($form, $h_update_ar, $q_update_ar, @values);
162
163     $send_email |= $row->{email};
164
165     my $next_config_id = conv_i($row->{next_dunning_config_id});
166     my $invoice_id     = conv_i($row->{invoice_id});
167
168     @values = ($dunning_id,     $next_config_id, $next_config_id,
169                $invoice_id,     $next_config_id, $invoice_id,
170                $next_config_id, $next_config_id);
171     do_statement($form, $h_insert_dunning, $q_insert_dunning, @values);
172   }
173
174   $h_update_ar->finish();
175   $h_insert_dunning->finish();
176
177   my $query =
178     qq|SELECT
179          ar.invnumber, ar.ordnumber, ar.amount, ar.netamount,
180          ar.transdate, ar.duedate, ar.paid, ar.amount - ar.paid AS open_amount,
181          da.fee, da.interest, da.transdate AS dunning_date, da.duedate AS dunning_duedate
182        FROM ar
183        LEFT JOIN dunning_config cfg ON (cfg.id = ar.dunning_config_id)
184        LEFT JOIN dunning da ON (ar.id = da.trans_id AND cfg.dunning_level = da.dunning_level)
185        WHERE ar.id IN (|
186        . join(", ", map { "?" } @invoice_ids) . qq|)|;
187
188   my $sth = prepare_execute_query($form, $dbh, $query, @invoice_ids);
189   my $first = 1;
190   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
191     if ($first) {
192       map({ $form->{"dn_$_"} = []; } keys(%{$ref}));
193       $first = 0;
194     }
195
196     $ref->{interest_rate} = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
197     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest);
198     map { push(@{ $form->{"dn_$_"} }, $ref->{$_})} keys %$ref;
199     map { $form->{$_} = $ref->{$_} } keys %{ $ref };
200   }
201   $sth->finish;
202
203   $query =
204     qq|SELECT id AS customer_id, name, street, zipcode, city, country, department_1, department_2, email
205        FROM customer
206        WHERE id = ?|;
207   $ref = selectfirst_hashref_query($form, $dbh, $query, $customer_id);
208   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
209
210   $query =
211     qq|SELECT
212          cfg.interest_rate, cfg.template AS formname,
213          cfg.email_subject, cfg.email_body, cfg.email_attachment,
214          (SELECT fee
215           FROM dunning
216           WHERE dunning_id = ?
217           LIMIT 1)
218          AS fee,
219          (SELECT SUM(interest)
220           FROM dunning
221           WHERE dunning_id = ?)
222          AS total_interest,
223          (SELECT SUM(amount) - SUM(paid)
224           FROM ar
225           WHERE id IN (| . join(", ", map { "?" } @invoice_ids) . qq|))
226          AS total_open_amount
227        FROM dunning_config cfg
228        WHERE id = ?|;
229   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, @invoice_ids, $next_dunning_config_id);
230   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
231
232   $form->{interest_rate}     = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
233   $form->{fee}               = $form->format_amount($myconfig, $ref->{fee}, 2);
234   $form->{total_interest}    = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
235   $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{total_open_amount}, 2), 2);
236   $form->{total_amount}      = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $ref->{total_open_amount}, 2), 2);
237
238   $form->{templates}    = "$myconfig->{templates}";
239   $form->{language}     = $form->get_template_language(\%myconfig);
240   $form->{printer_code} = $form->get_printer_code(\%myconfig);
241
242   if ($form->{language} ne "") {
243     $form->{language} = "_" . $form->{language};
244   }
245
246   if ($form->{printer_code} ne "") {
247     $form->{printer_code} = "_" . $form->{printer_code};
248   }
249
250   $form->{IN} = "$form->{formname}$form->{language}$form->{printer_code}.html";
251   if ($form->{format} eq 'postscript') {
252     $form->{postscript} = 1;
253     $form->{IN} =~ s/html$/tex/;
254   } elsif ($form->{"format"} =~ /pdf/) {
255     $form->{pdf} = 1;
256     if ($form->{"format"} =~ /opendocument/) {
257       $form->{IN} =~ s/html$/odt/;
258     } else {
259       $form->{IN} =~ s/html$/tex/;
260     }
261   } elsif ($form->{"format"} =~ /opendocument/) {
262     $form->{"opendocument"} = 1;
263     $form->{"IN"} =~ s/html$/odt/;
264   }
265
266   if ($send_email && ($form->{email} ne "")) {
267     $form->{media} = 'email';
268   }
269
270   $form->{keep_tmpfile} = 0;
271   if ($form->{media} eq 'email') {
272     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
273       unless $form->{subject};
274     if (!$form->{email_attachment}) {
275       $form->{do_not_attach} = 1;
276     } else {
277       $form->{do_not_attach} = 0;
278     }
279     $form->{subject} = parse_strings($myconfig, $form, $userspath, $form->{email_subject});
280     $form->{message} = parse_strings($myconfig, $form, $userspath, $form->{email_body});
281
282     $form->{OUT} = "$sendmail";
283
284   } else {
285
286     my $filename = Common::unique_id() . $form->{login} . ".pdf";
287     $form->{OUT} = ">$spool/$filename";
288     push(@{ $form->{DUNNING_PDFS} }, $filename);
289     $form->{keep_tmpfile} = 1;
290   }
291
292   delete($form->{tmpfile});
293   $form->parse_template($myconfig, $userspath);
294
295   $dbh->commit;
296   $dbh->disconnect;
297
298   $main::lxdebug->leave_sub();
299 }
300
301 sub get_invoices {
302
303   $main::lxdebug->enter_sub();
304
305   my ($self, $myconfig, $form) = @_;
306
307   # connect to database
308   my $dbh = $form->dbconnect($myconfig);
309
310   my $where;
311   my @values;
312
313   $form->{customer_id} = $1 if ($form->{customer} =~ /--(\d+)$/);
314
315   if ($form->{customer_id}) {
316     $where .= qq| AND (a.customer_id = ?)|;
317     push(@values, $form->{customer_id});
318
319   } elsif ($form->{customer}) {
320     $where .= qq| AND (ct.name ILIKE ?)|;
321     push(@values, '%' . $form->{customer} . '%');
322   }
323
324   my %columns = (
325     "ordnumber" => "a.ordnumber",
326     "invnumber" => "a.invnumber",
327     "notes"     => "a.notes",
328     );
329   foreach my $key (keys(%columns)) {
330     next unless ($form->{$key});
331     $where .= qq| AND $columns{$key} ILIKE ?|;
332     push(@values, '%' . $form->{$key} . '%');
333   }
334
335   if ($form->{dunning_level}) {
336     $where .= qq| AND nextcfg.id = ?|;
337     push(@values, conv_i($form->{dunning_level}));
338   }
339
340   $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
341   if ($form->{minamount}) {
342     $where .= qq| AND ((a.amount - a.paid) > ?) |;
343     push(@values, $form->{minamount});
344   }
345
346   $query =
347     qq|SELECT
348          a.id, a.ordnumber, a.transdate, a.invnumber, a.amount,
349          ct.name AS customername, a.customer_id, a.duedate,
350
351          cfg.dunning_description, cfg.dunning_level,
352
353          d.transdate AS dunning_date, d.duedate AS dunning_duedate,
354          d.fee, d.interest,
355
356          a.duedate + cfg.terms - current_date AS nextlevel,
357          current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
358          current_date + cfg.payment_terms AS next_duedate,
359
360          nextcfg.dunning_description AS next_dunning_description,
361          nextcfg.id AS next_dunning_config_id,
362          nextcfg.terms, nextcfg.active, nextcfg.email
363
364        FROM ar a
365
366        LEFT JOIN customer ct ON (a.customer_id = ct.id)
367        LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
368        LEFT JOIN dunning_config nextcfg ON
369          (nextcfg.id =
370            (SELECT id
371             FROM dunning_config
372             WHERE dunning_level >
373               COALESCE((SELECT dunning_level
374                         FROM dunning_config
375                         WHERE id = a.dunning_config_id
376                         ORDER BY dunning_level DESC
377                         LIMIT 1),
378                        0)
379             LIMIT 1))
380        LEFT JOIN dunning d ON ((d.trans_id = a.id) AND (cfg.dunning_level = d.dunning_level))
381
382        WHERE (a.paid < a.amount)
383          AND (a.duedate < current_date)
384
385        $where
386
387        ORDER BY a.id, transdate, duedate, name|;
388   my $sth = prepare_execute_query($form, $dbh, $query, @values);
389
390   $form->{DUNNINGS} = [];
391
392   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
393     next if !$ref->{terms} || ($ref->{pastdue} < $ref->{terms});
394
395     $ref->{interest} = $form->round_amount($ref->{interest}, 2);
396     push(@{ $form->{DUNNINGS} }, $ref);
397   }
398
399   $sth->finish;
400
401   $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
402   $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
403
404   $dbh->disconnect;
405   $main::lxdebug->leave_sub();
406 }
407
408 sub get_dunning {
409
410   $main::lxdebug->enter_sub();
411
412   my ($self, $myconfig, $form) = @_;
413
414   # connect to database
415   my $dbh = $form->dbconnect($myconfig);
416
417   $where = qq| WHERE (da.trans_id = a.id)|;
418
419   my @values;
420
421   if ($form->{customer_id}) {
422     $where .= qq| AND (a.customer_id = ?)|;
423     push(@values, $form->{customer_id});
424
425   } elsif ($form->{customer}) {
426     $where .= qq| AND (ct.name ILIKE ?)|;
427     push(@values, '%' . $form->{customer} . '%');
428   }
429
430   my %columns = (
431     "ordnumber" => "a.ordnumber",
432     "invnumber" => "a.invnumber",
433     "notes" => "a.notes",
434     );
435   foreach my $key (keys(%columns)) {
436     next unless ($form->{$key});
437     $where .= qq| AND $columns{$key} ILIKE ?|;
438     push(@values, '%' . $form->{$key} . '%');
439   }
440
441   if ($form->{dunning_level}) {
442     $where .= qq| AND a.dunning_config_id = ?|;
443     push(@values, conv_i($form->{dunning_level}));
444   }
445
446   if ($form->{department_id}) {
447     $where .= qq| AND a.department_id = ?|;
448     push @values, conv_i($form->{department_id});
449   }
450
451   $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
452   if ($form->{minamount}) {
453     $where .= qq| AND ((a.amount - a.paid) > ?) |;
454     push(@values, $form->{minamount});
455   }
456
457   if (!$form->{showold}) {
458     $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
459   }
460
461   if ($form->{transdatefrom}) {
462     $where .= qq| AND a.transdate >= ?|;
463     push(@values, $form->{transdatefrom});
464   }
465   if ($form->{transdateto}) {
466     $where .= qq| AND a.transdate <= ?|;
467     push(@values, $form->{transdateto});
468   }
469   if ($form->{dunningfrom}) {
470     $where .= qq| AND da.transdate >= ?|;
471     push(@values, $form->{dunningfrom});
472   }
473   if ($form->{dunningto}) {
474     $where .= qq| AND da.transdate >= ?|;
475     push(@values, $form->{dunningto});
476   }
477
478   $query =
479     qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount,
480          ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
481          da.interest, dn.dunning_description, da.transdate AS dunning_date,
482          da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id
483        FROM ar a
484        JOIN customer ct ON (a.customer_id = ct.id), dunning da
485        LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
486        $where
487        ORDER BY name, a.id|;
488
489   $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
490
491   foreach my $ref (@{ $form->{DUNNINGS} }) {
492     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
493   }
494
495   $dbh->disconnect;
496   $main::lxdebug->leave_sub();
497 }
498
499 sub parse_strings {
500
501   $main::lxdebug->enter_sub();
502
503   my ($myconfig, $form, $userspath, $string) = @_;
504
505   local (*IN, *OUT);
506
507   my $format = $form->{format};
508   $form->{format} = "html";
509
510   $tmpstring = "parse_string.html";
511   $tmpfile = "$myconfig->{templates}/$tmpstring";
512   open(OUT, ">", $tmpfile) or $form->error("$tmpfile : $!");
513
514   print(OUT $string);
515   close(OUT);
516
517   my $in = $form->{IN};
518   $form->{IN} = $tmpstring;
519   $template = HTMLTemplate->new($tmpstring, $form, $myconfig, $userspath);
520
521   my $fileid = time;
522   $form->{tmpfile} = "$userspath/${fileid}.$tmpstring";
523
524   open(OUT, ">", $form->{tmpfile}) or $form->error("$form->{OUT} : $!");
525   if (!$template->parse(*OUT)) {
526     $form->cleanup();
527     $form->error("$form->{IN} : " . $template->get_error());
528   }
529
530   close(OUT);
531   my $result = "";
532   open(IN, "<", $form->{tmpfile}) or $form->error($form->cleanup . "$form->{tmpfile} : $!");
533
534   while (<IN>) {
535     $result .= $_;
536   }
537
538   close(IN);
539 #   unlink($tmpfile);
540 #   unlink($form->{tmpfile});
541   $form->{IN} = $in;
542   $form->{format} = $format;
543
544   $main::lxdebug->leave_sub();
545   return $result;
546 }
547
548 sub melt_pdfs {
549
550   $main::lxdebug->enter_sub();
551
552   my ($self, $myconfig, $form, $userspath) = @_;
553
554   local (*IN, *OUT);
555
556   # Don't allow access outside of $userspath.
557   map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
558
559   my $inputfiles = join " ", map { "$userspath/$_" } @{ $form->{DUNNING_PDFS} };
560   my $outputfile = "$userspath/dunning.pdf";
561
562   system("gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=$outputfile $inputfiles");
563
564   map { unlink("$userspath/$_") } @{ $form->{DUNNING_PDFS} };
565
566   my $numbytes = (-s $outputfile);
567   open(IN, $outputfile) || $form->error($self->cleanup() . "$outputfile : $!");
568
569   $form->{copies} = 1 unless $form->{media} eq 'printer';
570
571   chdir($self->{cwd});
572
573   for my $i (1 .. $form->{copies}) {
574     # launch application
575     print qq|Content-Type: Application/PDF
576 Content-Disposition: attachment; filename="$outputfile"
577 Content-Length: $numbytes
578
579 |;
580
581     open(OUT, ">-") or $form->error($form->cleanup . "$!: STDOUT");
582
583     while (<IN>) {
584       print OUT $_;
585     }
586
587     close(OUT);
588
589     seek(IN, 0, 0);
590   }
591
592   close(IN);
593   unlink($outputfile);
594
595   $main::lxdebug->leave_sub();
596 }
597
598 sub print_dunning {
599   $main::lxdebug->enter_sub();
600
601   my ($self, $myconfig, $form, $dunning_id, $userspath, $spool, $sendmail) = @_;
602   # connect to database
603   my $dbh = $form->dbconnect_noauto($myconfig);
604
605   my $query =
606     qq|SELECT invnumber, ordnumber, customer_id, amount, netamount,
607          ar.transdate, ar.duedate, paid, amount - paid AS open_amount,
608          template AS formname, email_subject, email_body, email_attachment,
609          da.fee, da.interest, da.transdate AS dunning_date, da.duedate AS dunning_duedate
610        FROM dunning da
611        LEFT JOIN dunning_config ON (dunning_config.id = da.dunning_config_id)
612        LEFT JOIN ar ON (ar.id = da.trans_id)
613        WHERE (da.dunning_id = ?)|;
614
615   my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
616   my $first = 1;
617   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
618     if ($first) {
619       map({ $form->{"dn_$_"} = []; } keys(%{$ref}));
620       $first = 0;
621     }
622     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest);
623     map { $form->{$_} = $ref->{$_} } keys %$ref;
624     map { push @{ $form->{"dn_$_"} }, $ref->{$_}} keys %$ref;
625   }
626   $sth->finish;
627
628   $query =
629     qq|SELECT id AS customer_id, name, street, zipcode, city, country, department_1, department_2, email
630        FROM customer
631        WHERE id =
632          (SELECT customer_id
633           FROM dunning d
634           LEFT JOIN ar ON (d.trans_id = ar.id)
635           WHERE d.id = ?)|;
636   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
637   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
638
639   $query =
640     qq|SELECT
641          cfg.interest_rate, cfg.template AS formname,
642          cfg.email_subject, cfg.email_body, cfg.email_attachment,
643          d.fee, d.transdate AS dunning_date,
644          (SELECT SUM(interest)
645           FROM dunning
646           WHERE dunning_id = ?)
647          AS total_interest,
648          (SELECT SUM(amount) - SUM(paid)
649           FROM ar
650           WHERE id IN
651             (SELECT trans_id
652              FROM dunning
653              WHERE dunning_id = ?))
654          AS total_open_amount
655        FROM dunning d
656        LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
657        WHERE d.dunning_id = ?
658        LIMIT 1|;
659   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id);
660   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
661
662   $form->{interest_rate}     = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
663   $form->{fee}               = $form->format_amount($myconfig, $ref->{fee}, 2);
664   $form->{total_interest}    = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
665   $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{total_open_amount}, 2), 2);
666   $form->{total_amount}      = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $ref->{total_open_amount}, 2), 2);
667
668
669   $form->{templates} = "$myconfig->{templates}";
670
671   $form->{language} = $form->get_template_language(\%myconfig);
672   $form->{printer_code} = $form->get_printer_code(\%myconfig);
673
674   if ($form->{language} ne "") {
675     $form->{language} = "_" . $form->{language};
676   }
677
678   if ($form->{printer_code} ne "") {
679     $form->{printer_code} = "_" . $form->{printer_code};
680   }
681
682   $form->{IN} = "$form->{formname}$form->{language}$form->{printer_code}.html";
683   if ($form->{format} eq 'postscript') {
684     $form->{postscript} = 1;
685     $form->{IN} =~ s/html$/tex/;
686   } elsif ($form->{"format"} =~ /pdf/) {
687     $form->{pdf} = 1;
688     if ($form->{"format"} =~ /opendocument/) {
689       $form->{IN} =~ s/html$/odt/;
690     } else {
691       $form->{IN} =~ s/html$/tex/;
692     }
693   } elsif ($form->{"format"} =~ /opendocument/) {
694     $form->{"opendocument"} = 1;
695     $form->{"IN"} =~ s/html$/odt/;
696   }
697
698   if ($form->{"send_email"} && ($form->{email} ne "")) {
699     $form->{media} = 'email';
700   }
701
702   $form->{keep_tmpfile} = 0;
703   if ($form->{media} eq 'email') {
704     $form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
705       unless $form->{subject};
706     if (!$form->{email_attachment}) {
707       $form->{do_not_attach} = 1;
708     } else {
709       $form->{do_not_attach} = 0;
710     }
711     $form->{subject} = parse_strings($myconfig, $form, $userspath, $form->{email_subject});
712     $form->{message} = parse_strings($myconfig, $form, $userspath, $form->{email_body});
713
714     $form->{OUT} = "$sendmail";
715
716   } else {
717
718     my $filename = Common::unique_id() . $form->{login} . ".pdf";
719
720     push(@{ $form->{DUNNING_PDFS} }, $filename);
721     $form->{keep_tmpfile} = 1;
722   }
723
724   $form->parse_template($myconfig, $userspath);
725
726   $dbh->commit;
727   $dbh->disconnect;
728
729   $main::lxdebug->leave_sub();
730 }
731
732 1;