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