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