Mahnungen erzeugen - nach Abteilung filtern und anzeigen
[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   if ($form->{department_id}) {
538     $where .= qq| AND (a.department_id = ?)|;
539     push(@values, $form->{department_id});
540   }
541
542   my %columns = (
543     "ordnumber" => "a.ordnumber",
544     "invnumber" => "a.invnumber",
545     "notes"     => "a.notes",
546     "country"   => "ct.country",
547     );
548   foreach my $key (keys(%columns)) {
549     next unless ($form->{$key});
550     $where .= qq| AND $columns{$key} ILIKE ?|;
551     push(@values, like($form->{$key}));
552   }
553
554   if ($form->{dunning_level}) {
555     $where .= qq| AND nextcfg.id = ?|;
556     push(@values, conv_i($form->{dunning_level}));
557   }
558
559   $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
560   if ($form->{minamount}) {
561     $where .= qq| AND ((a.amount - a.paid) > ?) |;
562     push(@values, trim($form->{minamount}));
563   }
564
565   my $query =
566     qq|SELECT id
567        FROM dunning_config
568        WHERE dunning_level = (SELECT MAX(dunning_level) FROM dunning_config)|;
569   my ($id_for_max_dunning_level) = selectrow_query($form, $dbh, $query);
570
571   if (!$form->{l_include_direct_debit}) {
572     $where .= qq| AND NOT COALESCE(a.direct_debit, FALSE) |;
573   }
574
575   $query =
576     qq|SELECT
577          a.id, a.invoice, a.ordnumber, a.transdate, a.invnumber, a.amount, a.language_id,
578          ct.name AS customername, a.customer_id, a.duedate,
579          a.amount - a.paid AS open_amount,
580          a.direct_debit,
581          dep.description as departmentname,
582
583          cfg.dunning_description, cfg.dunning_level,
584
585          d.transdate AS dunning_date, d.duedate AS dunning_duedate,
586          d.fee, d.interest,
587
588          a.duedate + cfg.terms - current_date AS nextlevel,
589          current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
590          current_date + cfg.payment_terms AS next_duedate,
591
592          nextcfg.dunning_description AS next_dunning_description,
593          nextcfg.id AS next_dunning_config_id,
594          nextcfg.terms, nextcfg.active, nextcfg.email
595
596        FROM ar a
597
598        LEFT JOIN customer ct ON (a.customer_id = ct.id)
599        LEFT JOIN department dep ON (a.department_id = dep.id)
600        LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
601        LEFT JOIN dunning_config nextcfg ON
602          (nextcfg.id =
603            COALESCE(
604              (SELECT id
605               FROM dunning_config
606               WHERE dunning_level >
607                 COALESCE((SELECT dunning_level
608                           FROM dunning_config
609                           WHERE id = a.dunning_config_id
610                           ORDER BY dunning_level DESC
611                           LIMIT 1),
612                          0)
613               ORDER BY dunning_level ASC
614               LIMIT 1)
615              , ?))
616        LEFT JOIN dunning d ON (d.id = (
617          SELECT MAX(d2.id)
618          FROM dunning d2
619          WHERE (d2.trans_id      = a.id)
620            AND (d2.dunning_level = cfg.dunning_level)
621        ))
622
623        WHERE (a.paid < a.amount)
624          AND (a.duedate < current_date)
625
626        $where
627
628        ORDER BY a.id, transdate, duedate, name|;
629   my $sth = prepare_execute_query($form, $dbh, $query, $id_for_max_dunning_level, @values);
630
631   $form->{DUNNINGS} = [];
632
633   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
634     next if ($ref->{pastdue} < $ref->{terms});
635
636     $ref->{interest} = $form->round_amount($ref->{interest}, 2);
637     push(@{ $form->{DUNNINGS} }, $ref);
638   }
639
640   $sth->finish;
641
642   $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
643   $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
644
645   $main::lxdebug->leave_sub();
646 }
647
648 sub get_dunning {
649
650   $main::lxdebug->enter_sub();
651
652   my ($self, $myconfig, $form) = @_;
653
654   # connect to database
655   my $dbh = SL::DB->client->dbh;
656
657   my $where = qq| WHERE (da.trans_id = a.id)|;
658
659   my @values;
660
661   if ($form->{customer_id}) {
662     $where .= qq| AND (a.customer_id = ?)|;
663     push(@values, $form->{customer_id});
664
665   } elsif ($form->{customer}) {
666     $where .= qq| AND (ct.name ILIKE ?)|;
667     push(@values, like($form->{customer}));
668   }
669
670   my %columns = (
671     "ordnumber" => "a.ordnumber",
672     "invnumber" => "a.invnumber",
673     "notes" => "a.notes",
674     );
675   foreach my $key (keys(%columns)) {
676     next unless ($form->{$key});
677     $where .= qq| AND $columns{$key} ILIKE ?|;
678     push(@values, like($form->{$key}));
679   }
680
681   if ($form->{dunning_level}) {
682     $where .= qq| AND a.dunning_config_id = ?|;
683     push(@values, conv_i($form->{dunning_level}));
684   }
685
686   if ($form->{department_id}) {
687     $where .= qq| AND a.department_id = ?|;
688     push @values, conv_i($form->{department_id});
689   }
690
691   $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
692   if ($form->{minamount}) {
693     $where .= qq| AND ((a.amount - a.paid) > ?) |;
694     push(@values, $form->{minamount});
695   }
696
697   if (!$form->{showold}) {
698     $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
699   }
700
701   if ($form->{transdatefrom}) {
702     $where .= qq| AND a.transdate >= ?|;
703     push(@values, $form->{transdatefrom});
704   }
705   if ($form->{transdateto}) {
706     $where .= qq| AND a.transdate <= ?|;
707     push(@values, $form->{transdateto});
708   }
709   if ($form->{dunningfrom}) {
710     $where .= qq| AND da.transdate >= ?|;
711     push(@values, $form->{dunningfrom});
712   }
713   if ($form->{dunningto}) {
714     $where .= qq| AND da.transdate >= ?|;
715     push(@values, $form->{dunningto});
716   }
717
718   if ($form->{salesman_id}) {
719     $where .= qq| AND a.salesman_id = ?|;
720     push(@values, conv_i($form->{salesman_id}));
721   }
722
723   my %sort_columns = (
724     'dunning_description' => [ qw(dn.dunning_description customername invnumber) ],
725     'customername'        => [ qw(customername invnumber) ],
726     'invnumber'           => [ qw(a.invnumber) ],
727     'transdate'           => [ qw(a.transdate a.invnumber) ],
728     'duedate'             => [ qw(a.duedate a.invnumber) ],
729     'dunning_date'        => [ qw(dunning_date a.invnumber) ],
730     'dunning_duedate'     => [ qw(dunning_duedate a.invnumber) ],
731     'salesman'            => [ qw(salesman) ],
732     );
733
734   my $sortdir   = !defined $form->{sortdir}    ? 'ASC'         : $form->{sortdir} ? 'ASC' : 'DESC';
735   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'customername';
736   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
737
738   my $query =
739     qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount, a.language_id,
740          ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
741          da.interest, dn.dunning_description, da.transdate AS dunning_date,
742          da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id,
743          e2.name AS salesman
744        FROM ar a
745        JOIN customer ct ON (a.customer_id = ct.id)
746        LEFT JOIN employee e2 ON (a.salesman_id = e2.id), dunning da
747        LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
748        $where
749        ORDER BY $sortorder|;
750
751   $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
752
753   foreach my $ref (@{ $form->{DUNNINGS} }) {
754     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
755   }
756
757   $main::lxdebug->leave_sub();
758 }
759
760 sub melt_pdfs {
761
762   $main::lxdebug->enter_sub();
763
764   my ($self, $myconfig, $form, $copies) = @_;
765
766   # Don't allow access outside of $spool.
767   map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
768
769   $copies        *= 1;
770   $copies         = 1 unless $copies;
771   my $spool       = $::lx_office_conf{paths}->{spool};
772   my $inputfiles  = join " ", map { "$spool/$_ " x $copies } @{ $form->{DUNNING_PDFS} };
773   my $dunning_id  = $form->{dunning_id};
774
775   $dunning_id     =~ s|[^\d]||g;
776
777   my $in = IO::File->new($::lx_office_conf{applications}->{ghostscript} . " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=- $inputfiles |");
778   $form->error($main::locale->text('Could not spawn ghostscript.')) unless $in;
779
780   if ($form->{media} eq 'printer') {
781     $form->get_printer_code($myconfig);
782     my $out;
783     if ($form->{printer_command}) {
784       $out = IO::File->new("| $form->{printer_command}");
785     }
786
787     $::locale->with_raw_io($out, sub { $out->print($_) while <$in> });
788
789     $form->error($main::locale->text('Could not spawn the printer command.')) unless $out;
790
791   } else {
792     my $dunning_filename = $form->get_formname_translation('dunning');
793     print qq|Content-Type: Application/PDF\n| .
794           qq|Content-Disposition: attachment; filename="${dunning_filename}_${dunning_id}.pdf"\n\n|;
795
796     $::locale->with_raw_io(\*STDOUT, sub { print while <$in> });
797   }
798
799   $in->close();
800
801   map { unlink("$spool/$_") } @{ $form->{DUNNING_PDFS} };
802
803   $main::lxdebug->leave_sub();
804 }
805
806 sub print_dunning {
807   $main::lxdebug->enter_sub();
808
809   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
810
811   # connect to database
812   my $dbh = $provided_dbh || SL::DB->client->dbh;
813
814   $dunning_id =~ s|[^\d]||g;
815
816   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
817   if ($form->{"language_id"}) {
818     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
819       AM->get_language_details($myconfig, $form, $form->{language_id});
820   } else {
821     $output_dateformat = $myconfig->{dateformat};
822     $output_numberformat = $myconfig->{numberformat};
823     $output_longdates = 1;
824   }
825
826   my $query =
827     qq|SELECT
828          da.fee, da.interest,
829          da.transdate  AS dunning_date,
830          da.duedate    AS dunning_duedate,
831
832          dcfg.template AS formname,
833          dcfg.email_subject, dcfg.email_body, dcfg.email_attachment,
834
835          ar.transdate,       ar.duedate,      ar.customer_id,
836          ar.invnumber,       ar.ordnumber,    ar.cp_id,
837          ar.amount,          ar.netamount,    ar.paid,
838          ar.employee_id,     ar.salesman_id,
839          (SELECT cu.name FROM currencies cu WHERE cu.id = ar.currency_id) AS curr,
840          (SELECT description from department WHERE id = ar.department_id) AS department,
841          ar.amount - ar.paid AS open_amount,
842          ar.amount - ar.paid + da.fee + da.interest AS linetotal
843
844        FROM dunning da
845        LEFT JOIN dunning_config dcfg ON (dcfg.id = da.dunning_config_id)
846        LEFT JOIN ar ON (ar.id = da.trans_id)
847        WHERE (da.dunning_id = ?)|;
848
849   my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
850   my $first = 1;
851   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
852     if ($first) {
853       $form->{TEMPLATE_ARRAYS} = {};
854       map({ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} = []; } keys(%{$ref}));
855       $first = 0;
856     }
857     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest linetotal);
858     map { $form->{$_} = $ref->{$_} } keys %$ref;
859     map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $ref->{$_} } keys %$ref;
860   }
861   $sth->finish();
862
863   $query =
864     qq|SELECT
865          c.id AS customer_id, c.name,         c.street,       c.zipcode,   c.city,
866          c.country,           c.department_1, c.department_2, c.email,     c.customernumber,
867          c.greeting,          c.contact,      c.phone,        c.fax,       c.homepage,
868          c.email,             c.taxincluded,  c.business_id,  c.taxnumber, c.iban,
869          c.ustid,
870          ar.id AS invoice_id,
871          co.*
872        FROM dunning d
873        LEFT JOIN ar          ON (d.trans_id = ar.id)
874        LEFT JOIN customer c  ON (ar.customer_id = c.id)
875        LEFT JOIN contacts co ON (ar.cp_id = co.cp_id)
876        LEFT JOIN employee e  ON (ar.salesman_id = e.id)
877        WHERE (d.dunning_id = ?)
878        LIMIT 1|;
879   my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
880   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
881
882   $query =
883     qq|SELECT
884          cfg.interest_rate, cfg.template AS formname, cfg.dunning_level,
885          cfg.email_subject, cfg.email_body, cfg.email_attachment,
886          d.transdate AS dunning_date,
887          (SELECT SUM(fee)
888           FROM dunning
889           WHERE dunning_id = ?)
890          AS fee,
891          (SELECT SUM(interest)
892           FROM dunning
893           WHERE dunning_id = ?)
894          AS total_interest,
895          (SELECT SUM(amount) - SUM(paid)
896           FROM ar
897           WHERE id IN
898             (SELECT trans_id
899              FROM dunning
900              WHERE dunning_id = ?))
901          AS total_open_amount
902        FROM dunning d
903        LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
904        WHERE d.dunning_id = ?
905        LIMIT 1|;
906   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id, $dunning_id);
907   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
908
909   $form->{interest_rate}     = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
910   $form->{fee}               = $form->format_amount($myconfig, $ref->{fee}, 2);
911   $form->{total_interest}    = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
912   $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{total_open_amount}, 2), 2);
913   $form->{total_amount}      = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $ref->{total_open_amount}, 2), 2);
914
915   $::form->format_dates($output_dateformat, $output_longdates,
916     qw(dn_dunning_date dn_dunning_duedate dn_transdate dn_duedate
917           dunning_date    dunning_duedate    transdate    duedate)
918   );
919   $::form->reformat_numbers($output_numberformat, 2, qw(
920     dn_amount dn_netamount dn_paid dn_open_amount dn_fee dn_interest dn_linetotal
921        amount    netamount    paid    open_amount    fee    interest    linetotal
922     total_interest total_open_interest total_amount total_open_amount
923   ));
924   $::form->reformat_numbers($output_numberformat, undef, qw(interest_rate));
925
926   $self->set_customer_cvars($myconfig, $form);
927   $self->set_template_options($myconfig, $form);
928
929   my $filename          = "dunning_${dunning_id}_" . Common::unique_id() . ".pdf";
930   my $spool             = $::lx_office_conf{paths}->{spool};
931   $form->{OUT}          = "${spool}/$filename";
932   $form->{keep_tmpfile} = 1;
933
934   delete $form->{tmpfile};
935
936   push @{ $form->{DUNNING_PDFS} }, $filename;
937   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'path' => "${spool}/$filename",
938                                            'name'     => $form->get_formname_translation('dunning') . "_${dunning_id}.pdf" };
939
940   my $employee_id = ($::instance_conf->get_dunning_creator eq 'invoice_employee') ?
941                       $form->{employee_id}                                        :
942                       SL::DB::Manager::Employee->current->id;
943
944   $form->get_employee_data('prefix' => 'employee', 'id' => $employee_id);
945   $form->get_employee_data('prefix' => 'salesman', 'id' => $form->{salesman_id});
946
947   $form->{attachment_type}    = "dunning";
948   if ( $form->{dunning_level} ) {
949     $form->{attachment_type} .= $form->{dunning_level} if $form->{dunning_level} < 4;
950   }
951   $form->{attachment_filename} = $form->get_formname_translation($form->{attachment_type}) . "_${dunning_id}.pdf";
952   $form->{attachment_id} = $form->{invoice_id};
953   $form->parse_template($myconfig);
954
955   $main::lxdebug->leave_sub();
956 }
957
958 sub print_invoice_for_fees {
959   $main::lxdebug->enter_sub();
960
961   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
962
963   my $dbh = $provided_dbh || SL::DB->client->dbh;
964
965   my ($query, @values, $sth);
966
967   $query =
968     qq|SELECT
969          d.fee_interest_ar_id,
970          d.trans_id AS invoice_id,
971          dcfg.template,
972          dcfg.dunning_level
973        FROM dunning d
974        LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
975        WHERE d.dunning_id = ?|;
976   my ($ar_id, $invoice_id, $template, $dunning_level) = selectrow_query($form, $dbh, $query, $dunning_id);
977
978   if (!$ar_id) {
979     $main::lxdebug->leave_sub();
980     return;
981   }
982
983   my $saved_form = save_form();
984
985   $query = qq|SELECT SUM(fee), SUM(interest) FROM dunning WHERE id = ?|;
986   my ($fee_total, $interest_total) = selectrow_query($form, $dbh, $query, $dunning_id);
987
988   $query =
989     qq|SELECT
990          ar.invnumber, ar.transdate AS invdate, ar.amount, ar.netamount,
991          ar.duedate,   ar.notes,     ar.notes AS invoicenotes, ar.customer_id,
992
993          c.name,      c.department_1,   c.department_2, c.street, c.zipcode, c.city, c.country,
994          c.contact,   c.customernumber, c.phone,        c.fax,    c.email,
995          c.taxnumber, c.greeting
996
997        FROM ar
998        LEFT JOIN customer c ON (ar.customer_id = c.id)
999        WHERE ar.id = ?|;
1000   my $ref = selectfirst_hashref_query($form, $dbh, $query, $ar_id);
1001   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1002
1003   $query = qq|SELECT * FROM employee WHERE login = ?|;
1004   $ref = selectfirst_hashref_query($form, $dbh, $query, $::myconfig{login});
1005   map { $form->{"employee_${_}"} = $ref->{$_} } keys %{ $ref };
1006
1007   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ? ORDER BY acc_trans_id ASC|;
1008   $sth   = prepare_execute_query($form, $dbh, $query, $ar_id);
1009
1010   my ($row, $fee, $interest) = (0, 0, 0);
1011
1012   while ($ref = $sth->fetchrow_hashref()) {
1013     next if ($ref->{amount} < 0);
1014
1015     $row++;
1016
1017     if ($row == 1) {
1018       $fee = $ref->{amount};
1019     } else {
1020       $interest = $ref->{amount};
1021     }
1022   }
1023
1024   $form->{fee}        = $form->round_amount($fee,             2);
1025   $form->{interest}   = $form->round_amount($interest,        2);
1026   $form->{invamount}  = $form->round_amount($fee + $interest, 2);
1027   $form->{dunning_id} = $dunning_id;
1028   $form->{formname}   = "${template}_invoice";
1029
1030   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) } qw(fee interest invamount);
1031
1032   $self->set_customer_cvars($myconfig, $form);
1033   $self->set_template_options($myconfig, $form);
1034
1035   my $filename = Common::unique_id() . "dunning_invoice_${dunning_id}.pdf";
1036
1037   my $spool             = $::lx_office_conf{paths}->{spool};
1038   $form->{OUT}          = "$spool/$filename";
1039   $form->{keep_tmpfile} = 1;
1040   delete $form->{tmpfile};
1041
1042   map { delete $form->{$_} } grep /^[a-z_]+_\d+$/, keys %{ $form };
1043
1044   $form->{attachment_filename} = $form->get_formname_translation('dunning_invoice') . "_${dunning_id}.pdf";
1045   $form->{attachment_type}     = "dunning";
1046   $form->{attachment_id}       = $form->{invoice_id};
1047   $form->parse_template($myconfig);
1048
1049   restore_form($saved_form);
1050
1051   push @{ $form->{DUNNING_PDFS} }, $filename;
1052   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${spool}/$filename",
1053                                            'name'     => "dunning_invoice_${dunning_id}.pdf" };
1054
1055   $main::lxdebug->leave_sub();
1056 }
1057
1058 sub set_customer_cvars {
1059   my ($self, $myconfig, $form) = @_;
1060
1061   my $custom_variables = CVar->get_custom_variables(dbh      => $form->get_standard_dbh,
1062                                                     module   => 'CT',
1063                                                     trans_id => $form->{customer_id});
1064   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1065
1066   $form->{cp_greeting} = GenericTranslations->get(dbh              => $form->get_standard_dbh,
1067                                                   translation_type => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1068                                                   language_id      => $form->{language_id},
1069                                                   allow_fallback   => 1);
1070   if ($form->{cp_id}) {
1071     $custom_variables = CVar->get_custom_variables(dbh      => $form->get_standard_dbh,
1072                                                    module   => 'Contacts',
1073                                                    trans_id => $form->{cp_id});
1074     $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1075   }
1076
1077 }
1078
1079 1;