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