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