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