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