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