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