1 #======================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  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.
 
  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 #======================================================================
 
  31 # Dunning process module
 
  33 #======================================================================
 
  40 use SL::GenericTranslations;
 
  48 use SL::Util qw(trim);
 
  54   $main::lxdebug->enter_sub();
 
  56   my ($self, $myconfig, $form) = @_;
 
  59   my $dbh = SL::DB->client->dbh;
 
  63     qq|FROM dunning_config | .
 
  64     qq|ORDER BY dunning_level|;
 
  65   $form->{DUNNING} = selectall_hashref_query($form, $dbh, $query);
 
  67   foreach my $ref (@{ $form->{DUNNING} }) {
 
  68     $ref->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
 
  69     $ref->{interest_rate} = $form->format_amount($myconfig, ($ref->{interest_rate} * 100));
 
  73     qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar
 
  75   ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}) = selectrow_query($form, $dbh, $query);
 
  77   $main::lxdebug->leave_sub();
 
  81   my ($self, $myconfig, $form) = @_;
 
  82   $main::lxdebug->enter_sub();
 
  84   my $rc = SL::DB->client->with_transaction(\&_save_config, $self, $myconfig, $form);
 
  86   $::lxdebug->leave_sub;
 
  91   my ($self, $myconfig, $form) = @_;
 
  93   my $dbh = SL::DB->client->dbh;
 
  97   for my $i (1 .. $form->{rowcount}) {
 
  98     $form->{"fee_$i"} = $form->parse_amount($myconfig, $form->{"fee_$i"}) * 1;
 
  99     $form->{"interest_rate_$i"} = $form->parse_amount($myconfig, $form->{"interest_rate_$i"}) / 100;
 
 101     if (($form->{"dunning_level_$i"} ne "") &&
 
 102         ($form->{"dunning_description_$i"} ne "")) {
 
 103       @values = (conv_i($form->{"dunning_level_$i"}), $form->{"dunning_description_$i"},
 
 104                  $form->{"email_subject_$i"}, $form->{"email_body_$i"},
 
 105                  $form->{"template_$i"}, $form->{"fee_$i"}, $form->{"interest_rate_$i"},
 
 106                  $form->{"active_$i"} ? 't' : 'f', $form->{"auto_$i"} ? 't' : 'f', $form->{"email_$i"} ? 't' : 'f',
 
 107                  $form->{"email_attachment_$i"} ? 't' : 'f', conv_i($form->{"payment_terms_$i"}), conv_i($form->{"terms_$i"}),
 
 108                  $form->{"create_invoices_for_fees_$i"} ? 't' : 'f');
 
 109       if ($form->{"id_$i"}) {
 
 111           qq|UPDATE dunning_config SET
 
 112                dunning_level = ?, dunning_description = ?,
 
 113                email_subject = ?, email_body = ?,
 
 114                template = ?, fee = ?, interest_rate = ?,
 
 115                active = ?, auto = ?, email = ?,
 
 116                email_attachment = ?, payment_terms = ?, terms = ?,
 
 117                create_invoices_for_fees = ?
 
 119         push(@values, conv_i($form->{"id_$i"}));
 
 122           qq|INSERT INTO dunning_config
 
 123                (dunning_level, dunning_description, email_subject, email_body,
 
 124                 template, fee, interest_rate, active, auto, email,
 
 125                 email_attachment, payment_terms, terms, create_invoices_for_fees)
 
 126              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
 128       do_query($form, $dbh, $query, @values);
 
 131     if (($form->{"dunning_description_$i"} eq "") && ($form->{"id_$i"})) {
 
 132       $query = qq|DELETE FROM dunning_config WHERE id = ?|;
 
 133       do_query($form, $dbh, $query, $form->{"id_$i"});
 
 137   $query  = qq|UPDATE defaults SET dunning_ar_amount_fee = ?, dunning_ar_amount_interest = ?, dunning_ar = ?|;
 
 138   @values = (conv_i($form->{AR_amount_fee}), conv_i($form->{AR_amount_interest}), conv_i($form->{AR}));
 
 139   do_query($form, $dbh, $query, @values);
 
 144 sub create_invoice_for_fees {
 
 145   $main::lxdebug->enter_sub();
 
 147   my ($self, $myconfig, $form, $dbh, $dunning_id) = @_;
 
 149   my ($query, @values, $sth, $ref);
 
 151   $query = qq|SELECT dcfg.create_invoices_for_fees
 
 153               LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
 
 154               WHERE d.dunning_id = ?|;
 
 155   my ($create_invoices_for_fees) = selectrow_query($form, $dbh, $query, $dunning_id);
 
 157   if (!$create_invoices_for_fees) {
 
 158     $main::lxdebug->leave_sub();
 
 162   $query = qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar FROM defaults|;
 
 163   ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}) = selectrow_query($form, $dbh, $query);
 
 169            SELECT MAX(d_fee.fee)
 
 171            WHERE (d_fee.trans_id   =  d.trans_id)
 
 172              AND (d_fee.dunning_id <> ?)
 
 173              AND NOT (d_fee.fee_interest_ar_id ISNULL)
 
 178            SELECT MAX(d_interest.interest)
 
 179            FROM dunning d_interest
 
 180            WHERE (d_interest.trans_id   =  d.trans_id)
 
 181              AND (d_interest.dunning_id <> ?)
 
 182              AND NOT (d_interest.fee_interest_ar_id ISNULL)
 
 184          AS max_previous_interest
 
 186        WHERE dunning_id = ?|;
 
 187   @values = ($dunning_id, $dunning_id, $dunning_id);
 
 188   $sth = prepare_execute_query($form, $dbh, $query, @values);
 
 190   my ($fee_remaining, $interest_remaining) = (0, 0);
 
 191   my ($fee_total, $interest_total) = (0, 0);
 
 193   while (my $ref = $sth->fetchrow_hashref()) {
 
 194     $fee_remaining      += $form->round_amount($ref->{fee}, 2);
 
 195     $fee_remaining      -= $form->round_amount($ref->{max_previous_fee}, 2);
 
 196     $fee_total          += $form->round_amount($ref->{fee}, 2);
 
 197     $interest_remaining += $form->round_amount($ref->{interest}, 2);
 
 198     $interest_remaining -= $form->round_amount($ref->{max_previous_interest}, 2);
 
 199     $interest_total     += $form->round_amount($ref->{interest}, 2);
 
 204   my $amount = $fee_remaining + $interest_remaining;
 
 207     $main::lxdebug->leave_sub();
 
 211   my ($ar_id) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 212   my $curr = $form->get_default_currency($myconfig);
 
 213   my $trans_number = SL::TransNumber->new(type => 'invoice', dbh => $dbh);
 
 216     qq|INSERT INTO ar (id,          invnumber, transdate, gldate, customer_id,
 
 217                        taxincluded, amount,    netamount, paid,   duedate,
 
 218                        invoice,     currency_id, taxzone_id,      notes,
 
 223          current_date,          -- transdate
 
 224          current_date,          -- gldate
 
 226          (SELECT ar.customer_id
 
 228           LEFT JOIN ar ON (dn.trans_id = ar.id)
 
 229           WHERE dn.dunning_id = ?
 
 236          (SELECT duedate FROM dunning WHERE dunning_id = ? LIMIT 1),
 
 238          (SELECT id FROM currencies WHERE name = ?), -- curr
 
 240          (SELECT taxzone_id FROM customer WHERE id =
 
 241           (SELECT ar.customer_id
 
 243            LEFT JOIN ar ON (dn.trans_id = ar.id)
 
 244            WHERE dn.dunning_id = ?
 
 249          (SELECT id FROM employee WHERE login = ?)
 
 251   @values = ($ar_id,            # id
 
 252              $trans_number->create_unique, # invnumber
 
 253              $dunning_id,       # customer_id
 
 256              $dunning_id,       # duedate
 
 257              $curr,             # default currency
 
 258              $dunning_id,       # taxzone_id
 
 259              sprintf($main::locale->text('Automatically created invoice for fee and interest for dunning %s'), $dunning_id), # notes
 
 260              $::myconfig{login});   # employee_id
 
 261   do_query($form, $dbh, $query, @values);
 
 264     qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, taxkey, tax_id, chart_link)
 
 265        VALUES (?, ?, ?, current_date, current_date, 0,
 
 266                (SELECT id   FROM tax   WHERE (taxkey = 0) AND (rate = 0)),
 
 267                (SELECT link FROM chart WHERE id = ?))|;
 
 268   $sth = prepare_query($form, $dbh, $query);
 
 270   @values = ($ar_id, conv_i($form->{AR_amount_fee}), $fee_remaining, conv_i($form->{AR_amount_fee}));
 
 271   do_statement($form, $sth, $query, @values);
 
 273   if ($interest_remaining) {
 
 274     @values = ($ar_id, conv_i($form->{AR_amount_interest}), $interest_remaining, conv_i($form->{AR_amount_interest}));
 
 275     do_statement($form, $sth, $query, @values);
 
 278   @values = ($ar_id, conv_i($form->{AR}), -1 * $amount, conv_i($form->{AR}));
 
 279   do_statement($form, $sth, $query, @values);
 
 283   $query = qq|UPDATE dunning SET fee_interest_ar_id = ? WHERE dunning_id = ?|;
 
 284   do_query($form, $dbh, $query, $ar_id, $dunning_id);
 
 286   $main::lxdebug->leave_sub();
 
 291   my ($self, $myconfig, $form, $rows) = @_;
 
 292   $main::lxdebug->enter_sub();
 
 294   my $rc = SL::DB->client->with_transaction(\&_save_dunning, $self, $myconfig, $form, $rows);
 
 295   $::lxdebug->leave_sub;
 
 302   my ($self, $myconfig, $form, $rows) = @_;
 
 304   my $dbh = SL::DB->client->dbh;
 
 306   my ($query, @values);
 
 308   my ($dunning_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 310   my $q_update_ar = qq|UPDATE ar SET dunning_config_id = ? WHERE id = ?|;
 
 311   my $h_update_ar = prepare_query($form, $dbh, $q_update_ar);
 
 313   my $q_insert_dunning =
 
 314     qq|INSERT INTO dunning (dunning_id, dunning_config_id, dunning_level, trans_id,
 
 315                             fee,        interest,          transdate,     duedate)
 
 317                (SELECT dunning_level FROM dunning_config WHERE id = ?),
 
 321                 WHERE dunning_level <= (SELECT dunning_level FROM dunning_config WHERE id = ?)),
 
 322                (SELECT (amount - paid) * (current_date - duedate) FROM ar WHERE id = ?)
 
 323                  * (SELECT interest_rate FROM dunning_config WHERE id = ?)
 
 326                current_date + (SELECT payment_terms FROM dunning_config WHERE id = ?))|;
 
 327   my $h_insert_dunning = prepare_query($form, $dbh, $q_insert_dunning);
 
 330   my ($next_dunning_config_id, $customer_id);
 
 333   foreach my $row (@{ $rows }) {
 
 334     push @invoice_ids, $row->{invoice_id};
 
 335     $next_dunning_config_id = $row->{next_dunning_config_id};
 
 336     $customer_id            = $row->{customer_id};
 
 338     @values = ($row->{next_dunning_config_id}, $row->{invoice_id});
 
 339     do_statement($form, $h_update_ar, $q_update_ar, @values);
 
 341     $send_email |= $row->{email};
 
 343     my $next_config_id = conv_i($row->{next_dunning_config_id});
 
 344     my $invoice_id     = conv_i($row->{invoice_id});
 
 346     @values = ($dunning_id,     $next_config_id, $next_config_id,
 
 347                $invoice_id,     $next_config_id, $invoice_id,
 
 348                $next_config_id, $next_config_id);
 
 349     do_statement($form, $h_insert_dunning, $q_insert_dunning, @values);
 
 352   $h_update_ar->finish();
 
 353   $h_insert_dunning->finish();
 
 355   $form->{DUNNING_PDFS_EMAIL} = [];
 
 357   $form->{dunning_id} = $dunning_id;
 
 359   $self->create_invoice_for_fees($myconfig, $form, $dbh, $dunning_id);
 
 361   $self->print_invoice_for_fees($myconfig, $form, $dunning_id, $dbh);
 
 362   $self->print_dunning($myconfig, $form, $dunning_id, $dbh);
 
 366     $self->send_email($myconfig, $form, $dunning_id, $dbh);
 
 373   $main::lxdebug->enter_sub();
 
 375   my ($self, $myconfig, $form, $dunning_id, $dbh) = @_;
 
 379          dcfg.email_body,     dcfg.email_subject, dcfg.email_attachment,
 
 383        LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
 
 384        LEFT JOIN ar                  ON (d.trans_id          = ar.id)
 
 385        LEFT JOIN customer c          ON (ar.customer_id      = c.id)
 
 386        WHERE (d.dunning_id = ?)
 
 388   my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
 
 390   if (!$ref || !$ref->{recipient} || !$myconfig->{email}) {
 
 391     $main::lxdebug->leave_sub();
 
 395   my $template     = SL::Template::create(type => 'PlainText', form => $form, myconfig => $myconfig);
 
 396   my $mail         = Mailer->new();
 
 397   $mail->{from}    = $myconfig->{email};
 
 398   $mail->{to}      = $ref->{recipient};
 
 399   $mail->{subject} = $template->parse_block($ref->{email_subject});
 
 400   $mail->{message} = $template->parse_block($ref->{email_body});
 
 402   $mail->{message} .= $form->create_email_signature();
 
 404   $mail->{message} =~ s/\r\n/\n/g;
 
 406   if ($ref->{email_attachment} && @{ $form->{DUNNING_PDFS_EMAIL} }) {
 
 407     $mail->{attachments} = $form->{DUNNING_PDFS_EMAIL};
 
 412   $main::lxdebug->leave_sub();
 
 415 sub set_template_options {
 
 416   $main::lxdebug->enter_sub();
 
 418   my ($self, $myconfig, $form) = @_;
 
 420   my $defaults = SL::DB::Default->get;
 
 421   $form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
 
 422   $form->{templates}    = $defaults->templates;
 
 423   $form->{language}     = $form->get_template_language($myconfig);
 
 424   $form->{printer_code} = $form->get_printer_code($myconfig);
 
 426   if ($form->{language} ne "") {
 
 427     $form->{language} = "_" . $form->{language};
 
 430   if ($form->{printer_code} ne "") {
 
 431     $form->{printer_code} = "_" . $form->{printer_code};
 
 434   my $extension = 'html';
 
 435   if ($form->{format} eq 'postscript') {
 
 436     $form->{postscript}   = 1;
 
 439   } elsif ($form->{"format"} =~ /pdf/) {
 
 441     $extension            = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
 
 443   } elsif ($form->{"format"} =~ /opendocument/) {
 
 444     $form->{opendocument} = 1;
 
 446   } elsif ($form->{"format"} =~ /excel/) {
 
 452   # search for the template
 
 454   push @template_files, "$form->{formname}_email$form->{language}$form->{printer_code}.$extension" if $form->{media} eq 'email';
 
 455   push @template_files, "$form->{formname}$form->{language}$form->{printer_code}.$extension";
 
 456   push @template_files, "$form->{formname}.$extension";
 
 457   push @template_files, "default.$extension";
 
 460   for my $filename (@template_files) {
 
 461     if (-f ($defaults->templates . "/$filename")) {
 
 462       $form->{IN} = $filename;
 
 467   if (!defined $form->{IN}) {
 
 468     $::form->error($::locale->text('Cannot find matching template for this print request. Please contact your template maintainer. I tried these: #1.', join ', ', map { "'$_'"} @template_files));
 
 471   # prepare meta information for template introspection
 
 472   $form->{template_meta} = {
 
 473     formname  => $form->{formname},
 
 474     language  => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id}),
 
 475     format    => $form->{format},
 
 476     media     => $form->{media},
 
 477     extension => $extension,
 
 478     printer   => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id}),
 
 479     today     => DateTime->today,
 
 482   $main::lxdebug->leave_sub();
 
 487   $main::lxdebug->enter_sub();
 
 489   my ($self, $myconfig, $form) = @_;
 
 491   # connect to database
 
 492   my $dbh = SL::DB->client->dbh;
 
 497   $form->{customer_id} = $1 if ($form->{customer} =~ /--(\d+)$/);
 
 499   if ($form->{customer_id}) {
 
 500     $where .= qq| AND (a.customer_id = ?)|;
 
 501     push(@values, $form->{customer_id});
 
 503   } elsif ($form->{customer}) {
 
 504     $where .= qq| AND (ct.name ILIKE ?)|;
 
 505     push(@values, like($form->{customer}));
 
 509     "ordnumber" => "a.ordnumber",
 
 510     "invnumber" => "a.invnumber",
 
 511     "notes"     => "a.notes",
 
 512     "country"   => "ct.country",
 
 514   foreach my $key (keys(%columns)) {
 
 515     next unless ($form->{$key});
 
 516     $where .= qq| AND $columns{$key} ILIKE ?|;
 
 517     push(@values, like($form->{$key}));
 
 520   if ($form->{dunning_level}) {
 
 521     $where .= qq| AND nextcfg.id = ?|;
 
 522     push(@values, conv_i($form->{dunning_level}));
 
 525   $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
 
 526   if ($form->{minamount}) {
 
 527     $where .= qq| AND ((a.amount - a.paid) > ?) |;
 
 528     push(@values, trim($form->{minamount}));
 
 534        WHERE dunning_level = (SELECT MAX(dunning_level) FROM dunning_config)|;
 
 535   my ($id_for_max_dunning_level) = selectrow_query($form, $dbh, $query);
 
 537   if (!$form->{l_include_direct_debit}) {
 
 538     $where .= qq| AND NOT COALESCE(a.direct_debit, FALSE) |;
 
 543          a.id, a.invoice, a.ordnumber, a.transdate, a.invnumber, a.amount, a.language_id,
 
 544          ct.name AS customername, a.customer_id, a.duedate,
 
 545          a.amount - a.paid AS open_amount,
 
 548          cfg.dunning_description, cfg.dunning_level,
 
 550          d.transdate AS dunning_date, d.duedate AS dunning_duedate,
 
 553          a.duedate + cfg.terms - current_date AS nextlevel,
 
 554          current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
 
 555          current_date + cfg.payment_terms AS next_duedate,
 
 557          nextcfg.dunning_description AS next_dunning_description,
 
 558          nextcfg.id AS next_dunning_config_id,
 
 559          nextcfg.terms, nextcfg.active, nextcfg.email
 
 563        LEFT JOIN customer ct ON (a.customer_id = ct.id)
 
 564        LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
 
 565        LEFT JOIN dunning_config nextcfg ON
 
 570               WHERE dunning_level >
 
 571                 COALESCE((SELECT dunning_level
 
 573                           WHERE id = a.dunning_config_id
 
 574                           ORDER BY dunning_level DESC
 
 577               ORDER BY dunning_level ASC
 
 580        LEFT JOIN dunning d ON (d.id = (
 
 583          WHERE (d2.trans_id      = a.id)
 
 584            AND (d2.dunning_level = cfg.dunning_level)
 
 587        WHERE (a.paid < a.amount)
 
 588          AND (a.duedate < current_date)
 
 592        ORDER BY a.id, transdate, duedate, name|;
 
 593   my $sth = prepare_execute_query($form, $dbh, $query, $id_for_max_dunning_level, @values);
 
 595   $form->{DUNNINGS} = [];
 
 597   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 598     next if ($ref->{pastdue} < $ref->{terms});
 
 600     $ref->{interest} = $form->round_amount($ref->{interest}, 2);
 
 601     push(@{ $form->{DUNNINGS} }, $ref);
 
 606   $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
 
 607   $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
 
 609   $main::lxdebug->leave_sub();
 
 614   $main::lxdebug->enter_sub();
 
 616   my ($self, $myconfig, $form) = @_;
 
 618   # connect to database
 
 619   my $dbh = SL::DB->client->dbh;
 
 621   my $where = qq| WHERE (da.trans_id = a.id)|;
 
 625   if ($form->{customer_id}) {
 
 626     $where .= qq| AND (a.customer_id = ?)|;
 
 627     push(@values, $form->{customer_id});
 
 629   } elsif ($form->{customer}) {
 
 630     $where .= qq| AND (ct.name ILIKE ?)|;
 
 631     push(@values, like($form->{customer}));
 
 635     "ordnumber" => "a.ordnumber",
 
 636     "invnumber" => "a.invnumber",
 
 637     "notes" => "a.notes",
 
 639   foreach my $key (keys(%columns)) {
 
 640     next unless ($form->{$key});
 
 641     $where .= qq| AND $columns{$key} ILIKE ?|;
 
 642     push(@values, like($form->{$key}));
 
 645   if ($form->{dunning_level}) {
 
 646     $where .= qq| AND a.dunning_config_id = ?|;
 
 647     push(@values, conv_i($form->{dunning_level}));
 
 650   if ($form->{department_id}) {
 
 651     $where .= qq| AND a.department_id = ?|;
 
 652     push @values, conv_i($form->{department_id});
 
 655   $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
 
 656   if ($form->{minamount}) {
 
 657     $where .= qq| AND ((a.amount - a.paid) > ?) |;
 
 658     push(@values, $form->{minamount});
 
 661   if (!$form->{showold}) {
 
 662     $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
 
 665   if ($form->{transdatefrom}) {
 
 666     $where .= qq| AND a.transdate >= ?|;
 
 667     push(@values, $form->{transdatefrom});
 
 669   if ($form->{transdateto}) {
 
 670     $where .= qq| AND a.transdate <= ?|;
 
 671     push(@values, $form->{transdateto});
 
 673   if ($form->{dunningfrom}) {
 
 674     $where .= qq| AND da.transdate >= ?|;
 
 675     push(@values, $form->{dunningfrom});
 
 677   if ($form->{dunningto}) {
 
 678     $where .= qq| AND da.transdate >= ?|;
 
 679     push(@values, $form->{dunningto});
 
 682   if ($form->{salesman_id}) {
 
 683     $where .= qq| AND a.salesman_id = ?|;
 
 684     push(@values, conv_i($form->{salesman_id}));
 
 688     'dunning_description' => [ qw(dn.dunning_description customername invnumber) ],
 
 689     'customername'        => [ qw(customername invnumber) ],
 
 690     'invnumber'           => [ qw(a.invnumber) ],
 
 691     'transdate'           => [ qw(a.transdate a.invnumber) ],
 
 692     'duedate'             => [ qw(a.duedate a.invnumber) ],
 
 693     'dunning_date'        => [ qw(dunning_date a.invnumber) ],
 
 694     'dunning_duedate'     => [ qw(dunning_duedate a.invnumber) ],
 
 695     'salesman'            => [ qw(salesman) ],
 
 698   my $sortdir   = !defined $form->{sortdir}    ? 'ASC'         : $form->{sortdir} ? 'ASC' : 'DESC';
 
 699   my $sortkey   = $sort_columns{$form->{sort}} ? $form->{sort} : 'customername';
 
 700   my $sortorder = join ', ', map { "$_ $sortdir" } @{ $sort_columns{$sortkey} };
 
 703     qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount, a.language_id,
 
 704          ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
 
 705          da.interest, dn.dunning_description, da.transdate AS dunning_date,
 
 706          da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id,
 
 709        JOIN customer ct ON (a.customer_id = ct.id)
 
 710        LEFT JOIN employee e2 ON (a.salesman_id = e2.id), dunning da
 
 711        LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
 
 713        ORDER BY $sortorder|;
 
 715   $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
 
 717   foreach my $ref (@{ $form->{DUNNINGS} }) {
 
 718     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
 
 721   $main::lxdebug->leave_sub();
 
 726   $main::lxdebug->enter_sub();
 
 728   my ($self, $myconfig, $form, $copies) = @_;
 
 730   # Don't allow access outside of $spool.
 
 731   map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
 
 734   $copies         = 1 unless $copies;
 
 735   my $spool       = $::lx_office_conf{paths}->{spool};
 
 736   my $inputfiles  = join " ", map { "$spool/$_ " x $copies } @{ $form->{DUNNING_PDFS} };
 
 737   my $dunning_id  = $form->{dunning_id};
 
 739   $dunning_id     =~ s|[^\d]||g;
 
 741   my $in = IO::File->new($::lx_office_conf{applications}->{ghostscript} . " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=- $inputfiles |");
 
 742   $form->error($main::locale->text('Could not spawn ghostscript.')) unless $in;
 
 744   if ($form->{media} eq 'printer') {
 
 745     $form->get_printer_code($myconfig);
 
 747     if ($form->{printer_command}) {
 
 748       $out = IO::File->new("| $form->{printer_command}");
 
 751     $::locale->with_raw_io($out, sub { $out->print($_) while <$in> });
 
 753     $form->error($main::locale->text('Could not spawn the printer command.')) unless $out;
 
 756     my $dunning_filename = $form->get_formname_translation('dunning');
 
 757     print qq|Content-Type: Application/PDF\n| .
 
 758           qq|Content-Disposition: attachment; filename="${dunning_filename}_${dunning_id}.pdf"\n\n|;
 
 760     $::locale->with_raw_io(\*STDOUT, sub { print while <$in> });
 
 765   map { unlink("$spool/$_") } @{ $form->{DUNNING_PDFS} };
 
 767   $main::lxdebug->leave_sub();
 
 771   $main::lxdebug->enter_sub();
 
 773   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
 
 775   # connect to database
 
 776   my $dbh = $provided_dbh || SL::DB->client->dbh;
 
 778   $dunning_id =~ s|[^\d]||g;
 
 780   my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
 
 781   if ($form->{"language_id"}) {
 
 782     ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
 
 783       AM->get_language_details($myconfig, $form, $form->{language_id});
 
 785     $output_dateformat = $myconfig->{dateformat};
 
 786     $output_numberformat = $myconfig->{numberformat};
 
 787     $output_longdates = 1;
 
 793          da.transdate  AS dunning_date,
 
 794          da.duedate    AS dunning_duedate,
 
 796          dcfg.template AS formname,
 
 797          dcfg.email_subject, dcfg.email_body, dcfg.email_attachment,
 
 799          ar.transdate,       ar.duedate,      ar.customer_id,
 
 800          ar.invnumber,       ar.ordnumber,    ar.cp_id,
 
 801          ar.amount,          ar.netamount,    ar.paid,
 
 802          (SELECT cu.name FROM currencies cu WHERE cu.id=ar.currency_id) AS curr,
 
 803          ar.amount - ar.paid AS open_amount,
 
 804          ar.amount - ar.paid + da.fee + da.interest AS linetotal
 
 807        LEFT JOIN dunning_config dcfg ON (dcfg.id = da.dunning_config_id)
 
 808        LEFT JOIN ar ON (ar.id = da.trans_id)
 
 809        WHERE (da.dunning_id = ?)|;
 
 811   my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
 
 813   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 815       $form->{TEMPLATE_ARRAYS} = {};
 
 816       map({ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} = []; } keys(%{$ref}));
 
 819     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest linetotal);
 
 820     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 821     map { push @{ $form->{TEMPLATE_ARRAYS}->{"dn_$_"} }, $ref->{$_} } keys %$ref;
 
 827          c.id AS customer_id, c.name,         c.street,       c.zipcode,   c.city,
 
 828          c.country,           c.department_1, c.department_2, c.email,     c.customernumber,
 
 829          c.greeting,          c.contact,      c.phone,        c.fax,       c.homepage,
 
 830          c.email,             c.taxincluded,  c.business_id,  c.taxnumber, c.iban,
 
 831          c,ustid,             e.name as salesman_name,
 
 834        LEFT JOIN ar          ON (d.trans_id = ar.id)
 
 835        LEFT JOIN customer c  ON (ar.customer_id = c.id)
 
 836        LEFT JOIN contacts co ON (ar.cp_id = co.cp_id)
 
 837        LEFT JOIN employee e  ON (ar.salesman_id = e.id)
 
 838        WHERE (d.dunning_id = ?)
 
 840   my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
 
 841   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 845          cfg.interest_rate, cfg.template AS formname,
 
 846          cfg.email_subject, cfg.email_body, cfg.email_attachment,
 
 847          d.transdate AS dunning_date,
 
 850           WHERE dunning_id = ?)
 
 852          (SELECT SUM(interest)
 
 854           WHERE dunning_id = ?)
 
 856          (SELECT SUM(amount) - SUM(paid)
 
 861              WHERE dunning_id = ?))
 
 864        LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
 
 865        WHERE d.dunning_id = ?
 
 867   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id, $dunning_id);
 
 868   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 870   $form->{interest_rate}     = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
 
 871   $form->{fee}               = $form->format_amount($myconfig, $ref->{fee}, 2);
 
 872   $form->{total_interest}    = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
 
 873   $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{total_open_amount}, 2), 2);
 
 874   $form->{total_amount}      = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $ref->{total_open_amount}, 2), 2);
 
 876   $::form->format_dates($output_dateformat, $output_longdates,
 
 877     qw(dn_dunning_date dn_dunning_duedate dn_transdate dn_duedate
 
 878           dunning_date    dunning_duedate    transdate    duedate)
 
 880   $::form->reformat_numbers($output_numberformat, 2, qw(
 
 881     dn_amount dn_netamount dn_paid dn_open_amount dn_fee dn_interest dn_linetotal
 
 882        amount    netamount    paid    open_amount    fee    interest    linetotal
 
 883     total_interest total_open_interest total_amount total_open_amount
 
 885   $::form->reformat_numbers($output_numberformat, undef, qw(interest_rate));
 
 887   $self->set_customer_cvars($myconfig, $form);
 
 888   $self->set_template_options($myconfig, $form);
 
 890   my $filename          = "dunning_${dunning_id}_" . Common::unique_id() . ".pdf";
 
 891   my $spool             = $::lx_office_conf{paths}->{spool};
 
 892   $form->{OUT}          = "${spool}/$filename";
 
 893   $form->{keep_tmpfile} = 1;
 
 895   delete $form->{tmpfile};
 
 897   push @{ $form->{DUNNING_PDFS} }, $filename;
 
 898   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${spool}/$filename",
 
 899                                            'name'     => $form->get_formname_translation('dunning') . "_${dunning_id}.pdf" };
 
 901   $form->parse_template($myconfig);
 
 903   $main::lxdebug->leave_sub();
 
 906 sub print_invoice_for_fees {
 
 907   $main::lxdebug->enter_sub();
 
 909   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
 
 911   my $dbh = $provided_dbh || SL::DB->client->dbh;
 
 913   my ($query, @values, $sth);
 
 917          d.fee_interest_ar_id,
 
 920        LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
 
 921        WHERE d.dunning_id = ?|;
 
 922   my ($ar_id, $template) = selectrow_query($form, $dbh, $query, $dunning_id);
 
 925     $main::lxdebug->leave_sub();
 
 929   my $saved_form = save_form();
 
 931   $query = qq|SELECT SUM(fee), SUM(interest) FROM dunning WHERE id = ?|;
 
 932   my ($fee_total, $interest_total) = selectrow_query($form, $dbh, $query, $dunning_id);
 
 936          ar.invnumber, ar.transdate AS invdate, ar.amount, ar.netamount,
 
 937          ar.duedate,   ar.notes,     ar.notes AS invoicenotes, ar.customer_id,
 
 939          c.name,      c.department_1,   c.department_2, c.street, c.zipcode, c.city, c.country,
 
 940          c.contact,   c.customernumber, c.phone,        c.fax,    c.email,
 
 941          c.taxnumber, c.greeting
 
 944        LEFT JOIN customer c ON (ar.customer_id = c.id)
 
 946   my $ref = selectfirst_hashref_query($form, $dbh, $query, $ar_id);
 
 947   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 949   $query = qq|SELECT * FROM employee WHERE login = ?|;
 
 950   $ref = selectfirst_hashref_query($form, $dbh, $query, $::myconfig{login});
 
 951   map { $form->{"employee_${_}"} = $ref->{$_} } keys %{ $ref };
 
 953   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ? ORDER BY acc_trans_id ASC|;
 
 954   $sth   = prepare_execute_query($form, $dbh, $query, $ar_id);
 
 956   my ($row, $fee, $interest) = (0, 0, 0);
 
 958   while ($ref = $sth->fetchrow_hashref()) {
 
 959     next if ($ref->{amount} < 0);
 
 964       $fee = $ref->{amount};
 
 966       $interest = $ref->{amount};
 
 970   $form->{fee}        = $form->round_amount($fee,             2);
 
 971   $form->{interest}   = $form->round_amount($interest,        2);
 
 972   $form->{invamount}  = $form->round_amount($fee + $interest, 2);
 
 973   $form->{dunning_id} = $dunning_id;
 
 974   $form->{formname}   = "${template}_invoice";
 
 976   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) } qw(fee interest invamount);
 
 978   $self->set_customer_cvars($myconfig, $form);
 
 979   $self->set_template_options($myconfig, $form);
 
 981   my $filename = Common::unique_id() . "dunning_invoice_${dunning_id}.pdf";
 
 983   my $spool             = $::lx_office_conf{paths}->{spool};
 
 984   $form->{OUT}          = "$spool/$filename";
 
 985   $form->{keep_tmpfile} = 1;
 
 986   delete $form->{tmpfile};
 
 988   map { delete $form->{$_} } grep /^[a-z_]+_\d+$/, keys %{ $form };
 
 990   $form->parse_template($myconfig);
 
 992   restore_form($saved_form);
 
 994   push @{ $form->{DUNNING_PDFS} }, $filename;
 
 995   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${spool}/$filename",
 
 996                                            'name'     => "dunning_invoice_${dunning_id}.pdf" };
 
 998   $main::lxdebug->leave_sub();
 
1001 sub set_customer_cvars {
 
1002   my ($self, $myconfig, $form) = @_;
 
1004   my $custom_variables = CVar->get_custom_variables(dbh      => $form->get_standard_dbh,
 
1006                                                     trans_id => $form->{customer_id});
 
1007   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
 
1009   $form->{cp_greeting} = GenericTranslations->get(dbh              => $form->get_standard_dbh,
 
1010                                                   translation_type => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
 
1011                                                   language_id      => $form->{language_id},
 
1012                                                   allow_fallback   => 1);