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 #======================================================================
 
  45   $main::lxdebug->enter_sub();
 
  47   my ($self, $myconfig, $form) = @_;
 
  50   my $dbh = $form->dbconnect($myconfig);
 
  54     qq|FROM dunning_config | .
 
  55     qq|ORDER BY dunning_level|;
 
  56   $form->{DUNNING} = selectall_hashref_query($form, $dbh, $query);
 
  58   foreach my $ref (@{ $form->{DUNNING} }) {
 
  59     $ref->{fee} = $form->format_amount($myconfig, $ref->{fee}, 2);
 
  60     $ref->{interest_rate} = $form->format_amount($myconfig, ($ref->{interest_rate} * 100));
 
  64     qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar
 
  66   ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}) = selectrow_query($form, $dbh, $query);
 
  70   $main::lxdebug->leave_sub();
 
  74   $main::lxdebug->enter_sub();
 
  76   my ($self, $myconfig, $form) = @_;
 
  79   my $dbh = $form->dbconnect_noauto($myconfig);
 
  83   for my $i (1 .. $form->{rowcount}) {
 
  84     $form->{"fee_$i"} = $form->parse_amount($myconfig, $form->{"fee_$i"}) * 1;
 
  85     $form->{"interest_rate_$i"} = $form->parse_amount($myconfig, $form->{"interest_rate_$i"}) / 100;
 
  87     if (($form->{"dunning_level_$i"} ne "") &&
 
  88         ($form->{"dunning_description_$i"} ne "")) {
 
  89       @values = (conv_i($form->{"dunning_level_$i"}), $form->{"dunning_description_$i"},
 
  90                  $form->{"email_subject_$i"}, $form->{"email_body_$i"},
 
  91                  $form->{"template_$i"}, $form->{"fee_$i"}, $form->{"interest_rate_$i"},
 
  92                  $form->{"active_$i"} ? 't' : 'f', $form->{"auto_$i"} ? 't' : 'f', $form->{"email_$i"} ? 't' : 'f',
 
  93                  $form->{"email_attachment_$i"} ? 't' : 'f', conv_i($form->{"payment_terms_$i"}), conv_i($form->{"terms_$i"}),
 
  94                  $form->{"create_invoices_for_fees_$i"} ? 't' : 'f');
 
  95       if ($form->{"id_$i"}) {
 
  97           qq|UPDATE dunning_config SET
 
  98                dunning_level = ?, dunning_description = ?,
 
  99                email_subject = ?, email_body = ?,
 
 100                template = ?, fee = ?, interest_rate = ?,
 
 101                active = ?, auto = ?, email = ?,
 
 102                email_attachment = ?, payment_terms = ?, terms = ?,
 
 103                create_invoices_for_fees = ?
 
 105         push(@values, conv_i($form->{"id_$i"}));
 
 108           qq|INSERT INTO dunning_config
 
 109                (dunning_level, dunning_description, email_subject, email_body,
 
 110                 template, fee, interest_rate, active, auto, email,
 
 111                 email_attachment, payment_terms, terms, create_invoices_for_fees)
 
 112              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
 
 114       do_query($form, $dbh, $query, @values);
 
 117     if (($form->{"dunning_description_$i"} eq "") && ($form->{"id_$i"})) {
 
 118       $query = qq|DELETE FROM dunning_config WHERE id = ?|;
 
 119       do_query($form, $dbh, $query, $form->{"id_$i"});
 
 123   $query  = qq|UPDATE defaults SET dunning_ar_amount_fee = ?, dunning_ar_amount_interest = ?, dunning_ar = ?|;
 
 124   @values = (conv_i($form->{AR_amount_fee}), conv_i($form->{AR_amount_interest}), conv_i($form->{AR}));
 
 125   do_query($form, $dbh, $query, @values);
 
 130   $main::lxdebug->leave_sub();
 
 133 sub create_invoice_for_fees {
 
 134   $main::lxdebug->enter_sub();
 
 136   my ($self, $myconfig, $form, $dbh, $dunning_id) = @_;
 
 138   my ($query, @values, $sth, $ref);
 
 140   $query = qq|SELECT dcfg.create_invoices_for_fees
 
 142               LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
 
 143               WHERE d.dunning_id = ?|;
 
 144   my ($create_invoices_for_fees) = selectrow_query($form, $dbh, $query, $dunning_id);
 
 146   if (!$create_invoices_for_fees) {
 
 147     $main::lxdebug->leave_sub();
 
 151   $query = qq|SELECT dunning_ar_amount_fee, dunning_ar_amount_interest, dunning_ar FROM defaults|;
 
 152   ($form->{AR_amount_fee}, $form->{AR_amount_interest}, $form->{AR}) = selectrow_query($form, $dbh, $query);
 
 158            SELECT MAX(d_fee.fee)
 
 160            WHERE (d_fee.trans_id   =  d.trans_id)
 
 161              AND (d_fee.dunning_id <> ?)
 
 162              AND NOT (d_fee.fee_interest_ar_id ISNULL)
 
 167            SELECT MAX(d_interest.interest)
 
 168            FROM dunning d_interest
 
 169            WHERE (d_interest.trans_id   =  d.trans_id)
 
 170              AND (d_interest.dunning_id <> ?)
 
 171              AND NOT (d_interest.fee_interest_ar_id ISNULL)
 
 173          AS max_previous_interest
 
 175        WHERE dunning_id = ?|;
 
 176   @values = ($dunning_id, $dunning_id, $dunning_id);
 
 177   $sth = prepare_execute_query($form, $dbh, $query, @values);
 
 179   my ($fee_remaining, $interest_remaining) = (0, 0);
 
 180   my ($fee_total, $interest_total) = (0, 0);
 
 182   while (my $ref = $sth->fetchrow_hashref()) {
 
 183     $fee_remaining      += $form->round_amount($ref->{fee}, 2);
 
 184     $fee_remaining      -= $form->round_amount($ref->{max_previous_fee}, 2);
 
 185     $fee_total          += $form->round_amount($ref->{fee}, 2);
 
 186     $interest_remaining += $form->round_amount($ref->{interest}, 2);
 
 187     $interest_remaining -= $form->round_amount($ref->{max_previous_interest}, 2);
 
 188     $interest_total     += $form->round_amount($ref->{interest}, 2);
 
 193   my $amount = $fee_remaining + $interest_remaining;
 
 196     $main::lxdebug->leave_sub();
 
 200   my ($ar_id) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
 201   my $curr = $form->get_default_currency($myconfig);
 
 204     qq|INSERT INTO ar (id,          invnumber, transdate, gldate, customer_id,
 
 205                        taxincluded, amount,    netamount, paid,   duedate,
 
 206                        invoice,     curr,      notes,
 
 211          current_date,          -- transdate
 
 212          current_date,          -- gldate
 
 214          (SELECT ar.customer_id
 
 216           LEFT JOIN ar ON (dn.trans_id = ar.id)
 
 217           WHERE dn.dunning_id = ?
 
 224          (SELECT duedate FROM dunning WHERE dunning_id = ? LIMIT 1),
 
 229          (SELECT id FROM employee WHERE login = ?)
 
 231   @values = ($ar_id,            # id
 
 232              $form->update_defaults($myconfig, 'invnumber', $dbh), # invnumber
 
 233              $dunning_id,       # customer_id
 
 236              $dunning_id,       # duedate
 
 237              $curr,             # default currency
 
 238              sprintf($main::locale->text('Automatically created invoice for fee and interest for dunning %s'), $dunning_id), # notes
 
 239              $form->{login});   # employee_id
 
 240   do_query($form, $dbh, $query, @values);
 
 243     qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, taxkey)
 
 244        VALUES (?, ?, ?, current_date, current_date, 0)|;
 
 245   $sth = prepare_query($form, $dbh, $query);
 
 247   @values = ($ar_id, conv_i($form->{AR_amount_fee}), $fee_remaining);
 
 248   do_statement($form, $sth, $query, @values);
 
 250   if ($interest_remaining) {
 
 251     @values = ($ar_id, conv_i($form->{AR_amount_interest}), $interest_remaining);
 
 252     do_statement($form, $sth, $query, @values);
 
 255   @values = ($ar_id, conv_i($form->{AR}), -1 * $amount);
 
 256   do_statement($form, $sth, $query, @values);
 
 260   $query = qq|UPDATE dunning SET fee_interest_ar_id = ? WHERE dunning_id = ?|;
 
 261   do_query($form, $dbh, $query, $ar_id, $dunning_id);
 
 263   $main::lxdebug->leave_sub();
 
 267   $main::lxdebug->enter_sub();
 
 269   my ($self, $myconfig, $form, $rows, $userspath, $spool, $sendmail) = @_;
 
 270   # connect to database
 
 271   my $dbh = $form->dbconnect_noauto($myconfig);
 
 273   my ($query, @values);
 
 275   my ($dunning_id) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
 
 277   my $q_update_ar = qq|UPDATE ar SET dunning_config_id = ? WHERE id = ?|;
 
 278   my $h_update_ar = prepare_query($form, $dbh, $q_update_ar);
 
 280   my $q_insert_dunning =
 
 281     qq|INSERT INTO dunning (dunning_id, dunning_config_id, dunning_level, trans_id,
 
 282                             fee,        interest,          transdate,     duedate)
 
 284                (SELECT dunning_level FROM dunning_config WHERE id = ?),
 
 288                 WHERE dunning_level <= (SELECT dunning_level FROM dunning_config WHERE id = ?)),
 
 289                (SELECT (amount - paid) * (current_date - transdate) FROM ar WHERE id = ?)
 
 290                  * (SELECT interest_rate FROM dunning_config WHERE id = ?)
 
 293                current_date + (SELECT payment_terms FROM dunning_config WHERE id = ?))|;
 
 294   my $h_insert_dunning = prepare_query($form, $dbh, $q_insert_dunning);
 
 297   my ($next_dunning_config_id, $customer_id);
 
 300   foreach my $row (@{ $rows }) {
 
 301     push @invoice_ids, $row->{invoice_id};
 
 302     $next_dunning_config_id = $row->{next_dunning_config_id};
 
 303     $customer_id            = $row->{customer_id};
 
 305     @values = ($row->{next_dunning_config_id}, $row->{invoice_id});
 
 306     do_statement($form, $h_update_ar, $q_update_ar, @values);
 
 308     $send_email |= $row->{email};
 
 310     my $next_config_id = conv_i($row->{next_dunning_config_id});
 
 311     my $invoice_id     = conv_i($row->{invoice_id});
 
 313     @values = ($dunning_id,     $next_config_id, $next_config_id,
 
 314                $invoice_id,     $next_config_id, $invoice_id,
 
 315                $next_config_id, $next_config_id);
 
 316     do_statement($form, $h_insert_dunning, $q_insert_dunning, @values);
 
 319   $h_update_ar->finish();
 
 320   $h_insert_dunning->finish();
 
 322   $form->{DUNNING_PDFS_EMAIL} = [];
 
 324   $self->create_invoice_for_fees($myconfig, $form, $dbh, $dunning_id);
 
 326   $self->print_invoice_for_fees($myconfig, $form, $dunning_id, $dbh);
 
 327   $self->print_dunning($myconfig, $form, $dunning_id, $dbh);
 
 329   $form->{dunning_id} = $dunning_id;
 
 332     $self->send_email($myconfig, $form, $dunning_id, $dbh);
 
 338   $main::lxdebug->leave_sub();
 
 342   $main::lxdebug->enter_sub();
 
 344   my ($self, $myconfig, $form, $dunning_id, $dbh) = @_;
 
 348          dcfg.email_body,     dcfg.email_subject, dcfg.email_attachment,
 
 352        LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
 
 353        LEFT JOIN ar                  ON (d.trans_id          = ar.id)
 
 354        LEFT JOIN customer c          ON (ar.customer_id      = c.id)
 
 355        WHERE (d.dunning_id = ?)
 
 357   my $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
 
 359   if (!$ref || !$ref->{recipient} || !$myconfig->{email}) {
 
 360     $main::lxdebug->leave_sub();
 
 364   my $template     = PlainTextTemplate->new(undef, $form, $myconfig);
 
 365   my $mail         = Mailer->new();
 
 366   $mail->{from}    = $myconfig->{email};
 
 367   $mail->{to}      = $ref->{recipient};
 
 368   $mail->{subject} = $template->parse_block($ref->{email_subject});
 
 369   $mail->{message} = $template->parse_block($ref->{email_body});
 
 371   if ($myconfig->{signature}) {
 
 372     $mail->{message} .= "\n-- \n$myconfig->{signature}";
 
 375   $mail->{message} =~ s/\r\n/\n/g;
 
 377   if ($ref->{email_attachment} && @{ $form->{DUNNING_PDFS_EMAIL} }) {
 
 378     $mail->{attachments} = $form->{DUNNING_PDFS_EMAIL};
 
 383   $main::lxdebug->leave_sub();
 
 386 sub set_template_options {
 
 387   $main::lxdebug->enter_sub();
 
 389   my ($self, $myconfig, $form) = @_;
 
 391   $form->{templates}    = "$myconfig->{templates}";
 
 392   $form->{language}     = $form->get_template_language($myconfig);
 
 393   $form->{printer_code} = $form->get_printer_code($myconfig);
 
 395   if ($form->{language} ne "") {
 
 396     $form->{language} = "_" . $form->{language};
 
 399   if ($form->{printer_code} ne "") {
 
 400     $form->{printer_code} = "_" . $form->{printer_code};
 
 403   $form->{IN}  = "$form->{formname}$form->{language}$form->{printer_code}.html";
 
 406   if ($form->{"format"} =~ /opendocument/) {
 
 407     $form->{IN} =~ s/html$/odt/;
 
 409     $form->{IN} =~ s/html$/tex/;
 
 412   $main::lxdebug->leave_sub();
 
 417   $main::lxdebug->enter_sub();
 
 419   my ($self, $myconfig, $form) = @_;
 
 421   # connect to database
 
 422   my $dbh = $form->dbconnect($myconfig);
 
 427   $form->{customer_id} = $1 if ($form->{customer} =~ /--(\d+)$/);
 
 429   if ($form->{customer_id}) {
 
 430     $where .= qq| AND (a.customer_id = ?)|;
 
 431     push(@values, $form->{customer_id});
 
 433   } elsif ($form->{customer}) {
 
 434     $where .= qq| AND (ct.name ILIKE ?)|;
 
 435     push(@values, '%' . $form->{customer} . '%');
 
 439     "ordnumber" => "a.ordnumber",
 
 440     "invnumber" => "a.invnumber",
 
 441     "notes"     => "a.notes",
 
 443   foreach my $key (keys(%columns)) {
 
 444     next unless ($form->{$key});
 
 445     $where .= qq| AND $columns{$key} ILIKE ?|;
 
 446     push(@values, '%' . $form->{$key} . '%');
 
 449   if ($form->{dunning_level}) {
 
 450     $where .= qq| AND nextcfg.id = ?|;
 
 451     push(@values, conv_i($form->{dunning_level}));
 
 454   $form->{minamount} = $form->parse_amount($myconfig,$form->{minamount});
 
 455   if ($form->{minamount}) {
 
 456     $where .= qq| AND ((a.amount - a.paid) > ?) |;
 
 457     push(@values, $form->{minamount});
 
 463        WHERE dunning_level = (SELECT MAX(dunning_level) FROM dunning_config)|;
 
 464   my ($id_for_max_dunning_level) = selectrow_query($form, $dbh, $query);
 
 468          a.id, a.ordnumber, a.transdate, a.invnumber, a.amount,
 
 469          ct.name AS customername, a.customer_id, a.duedate,
 
 471          cfg.dunning_description, cfg.dunning_level,
 
 473          d.transdate AS dunning_date, d.duedate AS dunning_duedate,
 
 476          a.duedate + cfg.terms - current_date AS nextlevel,
 
 477          current_date - COALESCE(d.duedate, a.duedate) AS pastdue,
 
 478          current_date + cfg.payment_terms AS next_duedate,
 
 480          nextcfg.dunning_description AS next_dunning_description,
 
 481          nextcfg.id AS next_dunning_config_id,
 
 482          nextcfg.terms, nextcfg.active, nextcfg.email
 
 486        LEFT JOIN customer ct ON (a.customer_id = ct.id)
 
 487        LEFT JOIN dunning_config cfg ON (a.dunning_config_id = cfg.id)
 
 488        LEFT JOIN dunning_config nextcfg ON
 
 493               WHERE dunning_level >
 
 494                 COALESCE((SELECT dunning_level
 
 496                           WHERE id = a.dunning_config_id
 
 497                           ORDER BY dunning_level DESC
 
 500               ORDER BY dunning_level ASC
 
 503        LEFT JOIN dunning d ON ((d.trans_id = a.id) AND (cfg.dunning_level = d.dunning_level))
 
 505        WHERE (a.paid < a.amount)
 
 506          AND (a.duedate < current_date)
 
 510        ORDER BY a.id, transdate, duedate, name|;
 
 511   my $sth = prepare_execute_query($form, $dbh, $query, $id_for_max_dunning_level, @values);
 
 513   $form->{DUNNINGS} = [];
 
 515   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 516     next if !$ref->{terms} || ($ref->{pastdue} < $ref->{terms});
 
 518     $ref->{interest} = $form->round_amount($ref->{interest}, 2);
 
 519     push(@{ $form->{DUNNINGS} }, $ref);
 
 524   $query = qq|SELECT id, dunning_description FROM dunning_config ORDER BY dunning_level|;
 
 525   $form->{DUNNING_CONFIG} = selectall_hashref_query($form, $dbh, $query);
 
 528   $main::lxdebug->leave_sub();
 
 533   $main::lxdebug->enter_sub();
 
 535   my ($self, $myconfig, $form) = @_;
 
 537   # connect to database
 
 538   my $dbh = $form->dbconnect($myconfig);
 
 540   $where = qq| WHERE (da.trans_id = a.id)|;
 
 544   if ($form->{customer_id}) {
 
 545     $where .= qq| AND (a.customer_id = ?)|;
 
 546     push(@values, $form->{customer_id});
 
 548   } elsif ($form->{customer}) {
 
 549     $where .= qq| AND (ct.name ILIKE ?)|;
 
 550     push(@values, '%' . $form->{customer} . '%');
 
 554     "ordnumber" => "a.ordnumber",
 
 555     "invnumber" => "a.invnumber",
 
 556     "notes" => "a.notes",
 
 558   foreach my $key (keys(%columns)) {
 
 559     next unless ($form->{$key});
 
 560     $where .= qq| AND $columns{$key} ILIKE ?|;
 
 561     push(@values, '%' . $form->{$key} . '%');
 
 564   if ($form->{dunning_level}) {
 
 565     $where .= qq| AND a.dunning_config_id = ?|;
 
 566     push(@values, conv_i($form->{dunning_level}));
 
 569   if ($form->{department_id}) {
 
 570     $where .= qq| AND a.department_id = ?|;
 
 571     push @values, conv_i($form->{department_id});
 
 574   $form->{minamount} = $form->parse_amount($myconfig, $form->{minamount});
 
 575   if ($form->{minamount}) {
 
 576     $where .= qq| AND ((a.amount - a.paid) > ?) |;
 
 577     push(@values, $form->{minamount});
 
 580   if (!$form->{showold}) {
 
 581     $where .= qq| AND (a.amount > a.paid) AND (da.dunning_config_id = a.dunning_config_id) |;
 
 584   if ($form->{transdatefrom}) {
 
 585     $where .= qq| AND a.transdate >= ?|;
 
 586     push(@values, $form->{transdatefrom});
 
 588   if ($form->{transdateto}) {
 
 589     $where .= qq| AND a.transdate <= ?|;
 
 590     push(@values, $form->{transdateto});
 
 592   if ($form->{dunningfrom}) {
 
 593     $where .= qq| AND da.transdate >= ?|;
 
 594     push(@values, $form->{dunningfrom});
 
 596   if ($form->{dunningto}) {
 
 597     $where .= qq| AND da.transdate >= ?|;
 
 598     push(@values, $form->{dunningto});
 
 602     qq|SELECT a.id, a.ordnumber, a.invoice, a.transdate, a.invnumber, a.amount,
 
 603          ct.name AS customername, ct.id AS customer_id, a.duedate, da.fee,
 
 604          da.interest, dn.dunning_description, da.transdate AS dunning_date,
 
 605          da.duedate AS dunning_duedate, da.dunning_id, da.dunning_config_id
 
 607        JOIN customer ct ON (a.customer_id = ct.id), dunning da
 
 608        LEFT JOIN dunning_config dn ON (da.dunning_config_id = dn.id)
 
 610        ORDER BY name, a.id|;
 
 612   $form->{DUNNINGS} = selectall_hashref_query($form, $dbh, $query, @values);
 
 614   foreach my $ref (@{ $form->{DUNNINGS} }) {
 
 615     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2)} qw(amount fee interest);
 
 619   $main::lxdebug->leave_sub();
 
 624   $main::lxdebug->enter_sub();
 
 626   my ($self, $myconfig, $form, $copies) = @_;
 
 628   # Don't allow access outside of $spool.
 
 629   map { $_ =~ s|.*/||; } @{ $form->{DUNNING_PDFS} };
 
 632   $copies         = 1 unless $copies;
 
 633   my $inputfiles  = join " ", map { "${main::spool}/$_ " x $copies } @{ $form->{DUNNING_PDFS} };
 
 634   my $dunning_id  = $form->{dunning_id};
 
 636   $dunning_id     =~ s|[^\d]||g;
 
 638   my $in = IO::File->new("gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=- $inputfiles |");
 
 639   $form->error($main::locale->text('Could not spawn ghostscript.')) unless $in;
 
 643   if ($form->{media} eq 'printer') {
 
 644     $form->get_printer_code($myconfig);
 
 645     if ($form->{printer_command}) {
 
 646       $out = IO::File->new("| $form->{printer_command}");
 
 649     $form->error($main::locale->text('Could not spawn the printer command.')) unless $out;
 
 652     $out = IO::File->new('>-');
 
 653     $out->print(qq|Content-Type: Application/PDF\n| .
 
 654                 qq|Content-Disposition: attachment; filename="dunning_${dunning_id}.pdf"\n\n|);
 
 657   while (my $line = <$in>) {
 
 664   map { unlink("${main::spool}/$_") } @{ $form->{DUNNING_PDFS} };
 
 666   $main::lxdebug->leave_sub();
 
 670   $main::lxdebug->enter_sub();
 
 672   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
 
 674   # connect to database
 
 675   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
 
 677   $dunning_id =~ s|[^\d]||g;
 
 682          da.transdate  AS dunning_date,
 
 683          da.duedate    AS dunning_duedate,
 
 685          dcfg.template AS formname,
 
 686          dcfg.email_subject, dcfg.email_body, dcfg.email_attachment,
 
 688          ar.transdate,       ar.duedate,      ar.customer_id,
 
 689          ar.invnumber,       ar.ordnumber,    ar.cp_id,
 
 690          ar.amount,          ar.netamount,    ar.paid,
 
 691          ar.amount - ar.paid AS open_amount,
 
 692          ar.amount - ar.paid + da.fee + da.interest AS linetotal
 
 695        LEFT JOIN dunning_config dcfg ON (dcfg.id = da.dunning_config_id)
 
 696        LEFT JOIN ar ON (ar.id = da.trans_id)
 
 697        WHERE (da.dunning_id = ?)|;
 
 699   my $sth = prepare_execute_query($form, $dbh, $query, $dunning_id);
 
 701   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
 703       map({ $form->{"dn_$_"} = []; } keys(%{$ref}));
 
 706     map { $ref->{$_} = $form->format_amount($myconfig, $ref->{$_}, 2) } qw(amount netamount paid open_amount fee interest linetotal);
 
 707     map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 708     map { push @{ $form->{"dn_$_"} }, $ref->{$_}} keys %$ref;
 
 714          c.id AS customer_id, c.name,         c.street,       c.zipcode, c.city,
 
 715          c.country,           c.department_1, c.department_2, c.email, c.customernumber,
 
 716          -- contact information
 
 719        LEFT JOIN ar          ON (d.trans_id = ar.id)
 
 720        LEFT JOIN customer c  ON (ar.customer_id = c.id)
 
 721        LEFT JOIN contacts co ON (ar.cp_id = co.cp_id)
 
 722        WHERE (d.dunning_id = ?)
 
 724   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id);
 
 725   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 729          cfg.interest_rate, cfg.template AS formname,
 
 730          cfg.email_subject, cfg.email_body, cfg.email_attachment,
 
 731          d.transdate AS dunning_date,
 
 734           WHERE dunning_id = ?)
 
 736          (SELECT SUM(interest)
 
 738           WHERE dunning_id = ?)
 
 740          (SELECT SUM(amount) - SUM(paid)
 
 745              WHERE dunning_id = ?))
 
 748        LEFT JOIN dunning_config cfg ON (d.dunning_config_id = cfg.id)
 
 749        WHERE d.dunning_id = ?
 
 751   $ref = selectfirst_hashref_query($form, $dbh, $query, $dunning_id, $dunning_id, $dunning_id, $dunning_id);
 
 752   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 754   $form->{interest_rate}     = $form->format_amount($myconfig, $ref->{interest_rate} * 100);
 
 755   $form->{fee}               = $form->format_amount($myconfig, $ref->{fee}, 2);
 
 756   $form->{total_interest}    = $form->format_amount($myconfig, $form->round_amount($ref->{total_interest}, 2), 2);
 
 757   $form->{total_open_amount} = $form->format_amount($myconfig, $form->round_amount($ref->{total_open_amount}, 2), 2);
 
 758   $form->{total_amount}      = $form->format_amount($myconfig, $form->round_amount($ref->{fee} + $ref->{total_interest} + $ref->{total_open_amount}, 2), 2);
 
 760   $self->set_template_options($myconfig, $form);
 
 762   my $filename          = "dunning_${dunning_id}_" . Common::unique_id() . ".pdf";
 
 763   $form->{OUT}          = ">${main::spool}/$filename";
 
 764   $form->{keep_tmpfile} = 1;
 
 766   delete $form->{tmpfile};
 
 768   push @{ $form->{DUNNING_PDFS} }, $filename;
 
 769   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${main::spool}/$filename",
 
 770                                            'name'     => "dunning_${dunning_id}.pdf" };
 
 772   $form->parse_template($myconfig, $main::userspath);
 
 774   $dbh->disconnect() unless $provided_dbh;
 
 776   $main::lxdebug->leave_sub();
 
 779 sub print_invoice_for_fees {
 
 780   $main::lxdebug->enter_sub();
 
 782   my ($self, $myconfig, $form, $dunning_id, $provided_dbh) = @_;
 
 784   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect($myconfig);
 
 786   my ($query, @values, $sth);
 
 790          d.fee_interest_ar_id,
 
 793        LEFT JOIN dunning_config dcfg ON (d.dunning_config_id = dcfg.id)
 
 794        WHERE d.dunning_id = ?|;
 
 795   my ($ar_id, $template) = selectrow_query($form, $dbh, $query, $dunning_id);
 
 798     $main::lxdebug->leave_sub();
 
 802   my $saved_form = save_form();
 
 804   $query = qq|SELECT SUM(fee), SUM(interest) FROM dunning WHERE id = ?|;
 
 805   my ($fee_total, $interest_total) = selectrow_query($form, $dbh, $query, $dunning_id);
 
 809          ar.invnumber, ar.transdate AS invdate, ar.amount, ar.netamount,
 
 810          ar.duedate,   ar.notes,     ar.notes AS invoicenotes,
 
 812          c.name,      c.department_1,   c.department_2, c.street, c.zipcode, c.city, c.country,
 
 813          c.contact,   c.customernumber, c.phone,        c.fax,    c.email,
 
 814          c.taxnumber, c.sic_code,       c.greeting
 
 817        LEFT JOIN customer c ON (ar.customer_id = c.id)
 
 819   $ref = selectfirst_hashref_query($form, $dbh, $query, $ar_id);
 
 820   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
 
 822   $query = qq|SELECT * FROM employee WHERE login = ?|;
 
 823   $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{login});
 
 824   map { $form->{"employee_${_}"} = $ref->{$_} } keys %{ $ref };
 
 826   $query = qq|SELECT * FROM acc_trans WHERE trans_id = ? ORDER BY oid ASC|;
 
 827   $sth   = prepare_execute_query($form, $dbh, $query, $ar_id);
 
 829   my ($row, $fee, $interest) = (0, 0, 0);
 
 831   while ($ref = $sth->fetchrow_hashref()) {
 
 832     next if ($ref->{amount} < 0);
 
 837       $fee = $ref->{amount};
 
 839       $interest = $ref->{amount};
 
 843   $form->{fee}        = $form->round_amount($fee,             2);
 
 844   $form->{interest}   = $form->round_amount($interest,        2);
 
 845   $form->{invamount}  = $form->round_amount($fee + $interest, 2);
 
 846   $form->{dunning_id} = $dunning_id;
 
 847   $form->{formname}   = "${template}_invoice";
 
 849   map { $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) } qw(fee interest invamount);
 
 851   $self->set_template_options($myconfig, $form);
 
 853   my $filename = Common::unique_id() . "dunning_invoice_${dunning_id}.pdf";
 
 855   $form->{OUT}          = ">$main::spool/$filename";
 
 856   $form->{keep_tmpfile} = 1;
 
 857   delete $form->{tmpfile};
 
 859   map { delete $form->{$_} } grep /^[a-z_]+_\d+$/, keys %{ $form };
 
 861   $form->parse_template($myconfig, $main::userspath);
 
 863   restore_form($saved_form);
 
 865   push @{ $form->{DUNNING_PDFS} }, $filename;
 
 866   push @{ $form->{DUNNING_PDFS_EMAIL} }, { 'filename' => "${main::spool}/$filename",
 
 867                                            'name'     => "dunning_invoice_${dunning_id}.pdf" };
 
 869   $dbh->disconnect() unless $provided_dbh;
 
 871   $main::lxdebug->leave_sub();