1 package FS::Template_Mixin;
4 use vars qw( $DEBUG $me
9 use vars qw( $invoice_lines @buf ); #yuck
10 use List::Util qw(sum); #can't import first, it conflicts with cust_main.first
13 use Text::Template 1.20;
15 use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
20 use FS::Misc qw( send_email );
21 use FS::Record qw( qsearch qsearchs );
23 use FS::Misc qw( generate_ps generate_pdf );
30 $me = '[FS::Template_Mixin]';
31 FS::UID->install_callback( sub {
32 my $conf = new FS::Conf; #global
33 $money_char = $conf->config('money_char') || '$';
34 $date_format = $conf->config('date_format') || '%x'; #/YY
39 Returns a configuration handle (L<FS::Conf>) set to the customer's locale.
41 If the "mode" pseudo-field is set on the object, the configuration handle
42 will be an L<FS::invoice_conf> for that invoice mode (and the customer's
49 my $mode = $self->get('mode');
50 if ($self->{_conf} and !defined($mode)) {
51 return $self->{_conf};
54 my $cust_main = $self->cust_main;
55 my $locale = $cust_main ? $cust_main->locale : '';
58 if ( ref $mode and $mode->isa('FS::invoice_mode') ) {
59 $mode = $mode->modenum;
60 } elsif ( $mode =~ /\D/ ) {
61 die "invalid invoice mode $mode";
63 $conf = qsearchs('invoice_conf', { modenum => $mode, locale => $locale });
65 $conf = qsearchs('invoice_conf', { modenum => $mode, locale => '' });
66 # it doesn't have a locale, but system conf still might
67 $conf->set('locale' => $locale) if $conf;
70 # if $mode is unspecified, or if there is no invoice_conf matching this mode
71 # and locale, then use the system config only (but with the locale)
72 $conf ||= FS::Conf->new({ 'locale' => $locale });
74 return $self->{_conf} = $conf;
77 =item print_text OPTIONS
79 Returns an text invoice, as a list of lines.
81 Options can be passed as a hash.
83 I<time>, if specified, is used to control the printing of overdue messages. The
84 default is now. It isn't the date of the invoice; that's the `_date' field.
85 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
86 L<Time::Local> and L<Date::Parse> for conversion functions.
88 I<template>, if specified, is the name of a suffix for alternate invoices.
90 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
98 %params = %{ shift() };
103 $params{'format'} = 'template'; # for some reason
105 $self->print_generic( %params );
108 =item print_latex HASHREF
110 Internal method - returns a filename of a filled-in LaTeX template for this
111 invoice (Note: add ".tex" to get the actual filename), and a filename of
112 an associated logo (with the .eps extension included).
114 See print_ps and print_pdf for methods that return PostScript and PDF output.
116 Options can be passed as a hash.
118 I<time>, if specified, is used to control the printing of overdue messages. The
119 default is now. It isn't the date of the invoice; that's the `_date' field.
120 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
121 L<Time::Local> and L<Date::Parse> for conversion functions.
123 I<template>, if specified, is the name of a suffix for alternate invoices.
124 This is strongly deprecated; see L<FS::invoice_conf> for the right way to
125 customize invoice templates for different purposes.
127 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
136 %params = %{ shift() };
141 $params{'format'} = 'latex';
142 my $conf = $self->conf;
144 # this needs to go away
145 my $template = $params{'template'};
146 # and this especially
147 $template ||= $self->_agent_template
148 if $self->can('_agent_template');
150 my $pkey = $self->primary_key;
151 my $tmp_template = $self->table. '.'. $self->$pkey. '.XXXXXXXX';
153 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
154 my $lh = new File::Temp(
155 TEMPLATE => $tmp_template,
159 ) or die "can't open temp file: $!\n";
161 my $agentnum = $self->agentnum;
163 if ( $template && $conf->exists("logo_${template}.eps", $agentnum) ) {
164 print $lh $conf->config_binary("logo_${template}.eps", $agentnum)
165 or die "can't write temp file: $!\n";
167 print $lh $conf->config_binary('logo.eps', $agentnum)
168 or die "can't write temp file: $!\n";
171 $params{'logo_file'} = $lh->filename;
173 if( $conf->exists('invoice-barcode')
174 && $self->can('invoice_barcode')
175 && $self->invnum ) { # don't try to barcode statements
176 my $png_file = $self->invoice_barcode($dir);
177 my $eps_file = $png_file;
178 $eps_file =~ s/\.png$/.eps/g;
179 $png_file =~ /(barcode.*png)/;
181 $eps_file =~ /(barcode.*eps)/;
184 my $curr_dir = cwd();
186 # after painfuly long experimentation, it was determined that sam2p won't
187 # accept : and other chars in the path, no matter how hard I tried to
188 # escape them, hence the chdir (and chdir back, just to be safe)
189 system('sam2p', '-j:quiet', $png_file, 'EPS:', $eps_file ) == 0
190 or die "sam2p failed: $!\n";
194 $params{'barcode_file'} = $eps_file;
197 my @filled_in = $self->print_generic( %params );
199 my $fh = new File::Temp( TEMPLATE => $tmp_template,
203 ) or die "can't open temp file: $!\n";
204 binmode($fh, ':utf8'); # language support
205 print $fh join('', @filled_in );
208 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
209 return ($1, $params{'logo_file'}, $params{'barcode_file'});
215 my $cust_main = $self->cust_main;
216 $cust_main ? $cust_main->agentnum : $self->prospect_main->agentnum;
219 =item print_generic OPTION => VALUE ...
221 Internal method - returns a filled-in template for this invoice as a scalar.
223 See print_ps and print_pdf for methods that return PostScript and PDF output.
231 The B<format> option is required and should be set to html, latex (print and PDF) or template (plaintext).
241 Overrides "Invoice" as the name of the sent document.
245 Used to control the printing of overdue messages. The
246 default is now. It isn't the date of the invoice; that's the `_date' field.
247 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
248 L<Time::Local> and L<Date::Parse> for conversion functions.
252 Logo file (path to temporary EPS file on the local filesystem)
256 CID for inline (emailed) images (logo)
260 Override customer's locale
264 Overrides any per customer cdr squelching when true
268 Supress the (invoice, quotation, statement, etc.) number
276 Supress the payment coupon
280 Barcode file (path to temporary EPS file on the local filesystem)
284 Flag indicating the barcode image should be a link (normal HTML dipaly)
288 Barcode CID for inline (emailed) images
290 =item preref_callback
292 Coderef run for each line item, code should return HTML to be displayed
293 before that line item (quotations only)
297 Dprecated. Used as a suffix for a configuration template. Please
298 don't use this, it deprecated in favor of more flexible alternatives.
304 #what's with all the sprintf('%10.2f')'s in here? will it cause any
305 # (alignment in text invoice?) problems to change them all to '%.2f' ?
306 # yes: fixed width/plain text printing will be borked
308 my( $self, %params ) = @_;
309 my $conf = $self->conf;
311 my $today = $params{today} ? $params{today} : time;
312 warn "$me print_generic called on $self with suffix $params{template}\n"
315 my $format = $params{format};
316 die "Unknown format: $format"
317 unless $format =~ /^(latex|html|template)$/;
319 my $cust_main = $self->cust_main || $self->prospect_main;
321 my $locale = $params{'locale'} || $cust_main->locale;
323 my %delimiters = ( 'latex' => [ '[@--', '--@]' ],
324 'html' => [ '<%=', '%>' ],
325 'template' => [ '{', '}' ],
328 warn "$me print_generic creating template\n"
331 # set the notice name here, and nowhere else.
332 my $notice_name = $params{notice_name}
333 || $conf->config('notice_name')
334 || $self->notice_name;
337 my $template = $params{template} ? $params{template} : $self->_agent_template;
338 my $templatefile = $self->template_conf. $format;
339 $templatefile .= "_$template"
340 if length($template) && $conf->exists($templatefile."_$template");
343 my @invoice_template = map "$_\n", $conf->config($templatefile)
344 or die "cannot load config data $templatefile";
346 if ( $format eq 'latex' && grep { /^%%Detail/ } @invoice_template ) {
347 #change this to a die when the old code is removed
348 # it's been almost ten years, changing it to a die
349 die "old-style invoice template $templatefile; ".
350 "patch with conf/invoice_latex.diff or use new conf/invoice_latex*\n";
351 #$old_latex = 'true';
352 #@invoice_template = _translate_old_latex_format(@invoice_template);
355 warn "$me print_generic creating T:T object\n"
358 my $text_template = new Text::Template(
360 SOURCE => \@invoice_template,
361 DELIMITERS => $delimiters{$format},
364 warn "$me print_generic compiling T:T object\n"
367 $text_template->compile()
368 or die "Can't compile $templatefile: $Text::Template::ERROR\n";
371 # additional substitution could possibly cause breakage in existing templates
374 'notes' => sub { map "$_", @_ },
375 'footer' => sub { map "$_", @_ },
376 'smallfooter' => sub { map "$_", @_ },
377 'returnaddress' => sub { map "$_", @_ },
378 'coupon' => sub { map "$_", @_ },
379 'summary' => sub { map "$_", @_ },
385 s/%%(.*)$/<!-- $1 -->/g;
386 s/\\section\*\{\\textsc\{(.)(.*)\}\}/<p><b><font size="+1">$1<\/font>\U$2<\/b>/g;
387 s/\\begin\{enumerate\}/<ol>/g;
389 s/\\end\{enumerate\}/<\/ol>/g;
390 s/\\textbf\{(.*)\}/<b>$1<\/b>/g;
399 sub { map { s/~/ /g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
401 sub { map { s/~/ /g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
407 s/\\hyphenation\{[\w\s\-]+}//;
412 'coupon' => sub { "" },
413 'summary' => sub { "" },
420 s/\\section\*\{\\textsc\{(.*)\}\}/\U$1/g;
421 s/\\begin\{enumerate\}//g;
423 s/\\end\{enumerate\}//g;
424 s/\\textbf\{(.*)\}/$1/g;
431 sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
433 sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
438 s/\\\\\*?\s*$/\n/; # dubious
439 s/\\hyphenation\{[\w\s\-]+}//;
443 'coupon' => sub { "" },
444 'summary' => sub { "" },
449 # hashes for differing output formats
450 my %nbsps = ( 'latex' => '~',
451 'html' => '', # '&nbps;' would be nice
452 'template' => '', # not used
454 my $nbsp = $nbsps{$format};
456 my %escape_functions = ( 'latex' => \&_latex_escape,
457 'html' => \&_html_escape_nbsp,#\&encode_entities,
458 'template' => sub { shift },
460 my $escape_function = $escape_functions{$format};
461 my $escape_function_nonbsp = ($format eq 'html')
462 ? \&_html_escape : $escape_function;
464 my %newline_tokens = ( 'latex' => '\\\\',
468 my $newline_token = $newline_tokens{$format};
470 warn "$me generating template variables\n"
473 # generate template variables
477 defined( $conf->config_orbase( "invoice_${format}returnaddress",
481 && length( $conf->config_orbase( "invoice_${format}returnaddress",
487 $returnaddress = join("\n",
488 $conf->config_orbase("invoice_${format}returnaddress", $template)
492 $conf->config_orbase('invoice_latexreturnaddress', $template) ) {
494 my $convert_map = $convert_maps{$format}{'returnaddress'};
497 &$convert_map( $conf->config_orbase( "invoice_latexreturnaddress",
502 } elsif ( grep /\S/, $conf->config('company_address', $cust_main->agentnum) ) {
504 my $convert_map = $convert_maps{$format}{'returnaddress'};
505 $returnaddress = join( "\n", &$convert_map(
506 map { s/( {2,})/'~' x length($1)/eg;
510 ( $conf->config('company_name', $cust_main->agentnum),
511 $conf->config('company_address', $cust_main->agentnum),
518 my $warning = "Couldn't find a return address; ".
519 "do you need to set the company_address configuration value?";
521 $returnaddress = $nbsp;
522 #$returnaddress = $warning;
526 warn "$me generating invoice data\n"
529 my $agentnum = $cust_main->agentnum;
534 'company_name' => scalar( $conf->config('company_name', $agentnum) ),
535 'company_address' => join("\n", $conf->config('company_address', $agentnum) ). "\n",
536 'company_phonenum'=> scalar( $conf->config('company_phonenum', $agentnum) ),
537 'returnaddress' => $returnaddress,
538 'agent' => &$escape_function($cust_main->agent->agent),
540 #invoice/quotation info
541 'no_number' => $params{'no_number'},
542 'invnum' => ( $params{'no_number'} ? '' : $self->invnum ),
543 'quotationnum' => $self->quotationnum,
544 'no_date' => $params{'no_date'},
545 '_date' => ( $params{'no_date'} ? '' : $self->_date ),
546 # workaround for inconsistent behavior in the early plain text
547 # templates; see RT#28271
548 'date' => ( $params{'no_date'}
550 : ($format eq 'template'
552 : $self->time2str_local('long', $self->_date, $format)
555 'today' => $self->time2str_local('long', $today, $format),
556 'terms' => $self->terms,
557 'template' => $template, #params{'template'},
558 'notice_name' => $notice_name, # escape?
559 'current_charges' => sprintf("%.2f", $self->charged),
560 'duedate' => $self->due_date2str('rdate'), #date_format?
563 'custnum' => $cust_main->display_custnum,
564 'prospectnum' => $cust_main->prospectnum,
565 'agent_custid' => &$escape_function($cust_main->agent_custid),
566 ( map { $_ => &$escape_function($cust_main->$_()) }
567 qw( company address1 address2 city state zip fax )
569 'payname' => &$escape_function( $cust_main->invoice_attn
570 || $cust_main->contact_firstlast ),
573 'ship_enable' => $cust_main->invoice_ship_address || $conf->exists('invoice-ship_address'),
574 'unitprices' => $conf->exists('invoice-unitprice'),
575 'smallernotes' => $conf->exists('invoice-smallernotes'),
576 'smallerfooter' => $conf->exists('invoice-smallerfooter'),
577 'balance_due_below_line' => $conf->exists('balance_due_below_line'),
579 #layout info -- would be fancy to calc some of this and bury the template
581 'topmargin' => scalar($conf->config('invoice_latextopmargin', $agentnum)),
582 'headsep' => scalar($conf->config('invoice_latexheadsep', $agentnum)),
583 'textheight' => scalar($conf->config('invoice_latextextheight', $agentnum)),
584 'extracouponspace' => scalar($conf->config('invoice_latexextracouponspace', $agentnum)),
585 'couponfootsep' => scalar($conf->config('invoice_latexcouponfootsep', $agentnum)),
586 'verticalreturnaddress' => $conf->exists('invoice_latexverticalreturnaddress', $agentnum),
587 'addresssep' => scalar($conf->config('invoice_latexaddresssep', $agentnum)),
588 'amountenclosedsep' => scalar($conf->config('invoice_latexcouponamountenclosedsep', $agentnum)),
589 'coupontoaddresssep' => scalar($conf->config('invoice_latexcoupontoaddresssep', $agentnum)),
590 'addcompanytoaddress' => $conf->exists('invoice_latexcouponaddcompanytoaddress', $agentnum),
592 # better hang on to conf_dir for a while (for old templates)
593 'conf_dir' => "$FS::UID::conf_dir/conf.$FS::UID::datasrc",
595 #these are only used when doing paged plaintext
602 $invoice_data{'emt'} = sub { &$escape_function($self->mt(@_)) };
603 # prototype here to silence warnings
604 $invoice_data{'time2str'} = sub ($;$$) { $self->time2str_local(@_, $format) };
606 my $min_sdate = 999999999999;
608 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
609 next unless $cust_bill_pkg->pkgnum > 0;
610 $min_sdate = $cust_bill_pkg->sdate
611 if length($cust_bill_pkg->sdate) && $cust_bill_pkg->sdate < $min_sdate;
612 $max_edate = $cust_bill_pkg->edate
613 if length($cust_bill_pkg->edate) && $cust_bill_pkg->edate > $max_edate;
616 $invoice_data{'bill_period'} = '';
617 $invoice_data{'bill_period'} =
618 $self->time2str_local('%e %h', $min_sdate, $format)
620 $self->time2str_local('%e %h', $max_edate, $format)
621 if ($max_edate != 0 && $min_sdate != 999999999999);
623 $invoice_data{finance_section} = '';
624 if ( $conf->config('finance_pkgclass') ) {
626 qsearchs('pkg_class', { classnum => $conf->config('finance_pkgclass') });
627 $invoice_data{finance_section} = $pkg_class->categoryname;
629 $invoice_data{finance_amount} = '0.00';
630 $invoice_data{finance_section} ||= 'Finance Charges'; #avoid config confusion
632 my $countrydefault = $conf->config('countrydefault') || 'US';
633 foreach ( qw( address1 address2 city state zip country fax) ){
634 my $method = 'ship_'.$_;
635 $invoice_data{"ship_$_"} = $escape_function->($cust_main->$method);
637 if ( length($cust_main->ship_company) ) {
638 $invoice_data{'ship_company'} = $escape_function->($cust_main->ship_company);
640 $invoice_data{'ship_company'} = $escape_function->($cust_main->company);
642 $invoice_data{'ship_contact'} = $escape_function->($cust_main->contact);
643 $invoice_data{'ship_country'} = ''
644 if ( $invoice_data{'ship_country'} eq $countrydefault );
646 $invoice_data{'cid'} = $params{'cid'}
649 if ( $cust_main->country eq $countrydefault ) {
650 $invoice_data{'country'} = '';
652 $invoice_data{'country'} = &$escape_function($cust_main->bill_country_full);
656 $invoice_data{'address'} = \@address;
658 $invoice_data{'payname'}.
659 ( $cust_main->po_number
660 ? " (P.O. #". $cust_main->po_number. ")"
664 push @address, $cust_main->company
665 if $cust_main->company;
666 push @address, $cust_main->address1;
667 push @address, $cust_main->address2
668 if $cust_main->address2;
670 $cust_main->city. ", ". $cust_main->state. " ". $cust_main->zip;
671 push @address, $invoice_data{'country'}
672 if $invoice_data{'country'};
674 while (scalar(@address) < 5);
676 $invoice_data{'logo_file'} = $params{'logo_file'}
677 if $params{'logo_file'};
678 $invoice_data{'barcode_file'} = $params{'barcode_file'}
679 if $params{'barcode_file'};
680 $invoice_data{'barcode_img'} = $params{'barcode_img'}
681 if $params{'barcode_img'};
682 $invoice_data{'barcode_cid'} = $params{'barcode_cid'}
683 if $params{'barcode_cid'};
685 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
686 # my( $cr_total, @cr_cust_credit ) = $self->cust_credit; #credits
687 #my $balance_due = $self->owed + $pr_total - $cr_total;
688 my $balance_due = $self->owed;
689 if ( $self->enable_previous ) {
690 $balance_due += $pr_total;
692 # otherwise the previous balance is not shown, so including it in the
693 # balance due is just confusing
695 # the sum of amount owed on all invoices
696 # (this is used in the summary & on the payment coupon)
697 $invoice_data{'balance'} = sprintf("%.2f", $balance_due);
699 # flag telling this invoice to have a first-page summary
700 my $summarypage = '';
702 if ( $self->custnum && $self->invnum ) {
703 # XXX should be an FS::cust_bill method to set the defaults, instead
704 # of checking the type here
706 # info from customer's last invoice before this one, for some
708 $invoice_data{'last_bill'} = {};
710 my $last_bill = $self->previous_bill;
713 # "balance_date_range" unfortunately is unsuitable for this, since it
714 # cares about application dates. We want to know the sum of all
715 # _top-level transactions_ dated before the last invoice.
717 # still do this for the "Previous Balance" line of the summary block
719 map "$_ WHERE _date <= ? AND custnum = ?", (
720 "SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill",
721 "SELECT -1 * COALESCE( SUM(amount), 0 ) FROM cust_credit",
722 "SELECT -1 * COALESCE( SUM(paid), 0 ) FROM cust_pay",
723 "SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund",
726 # the customer's current balance immediately after generating the last
729 my $last_bill_balance = $last_bill->charged;
731 my $delta = FS::Record->scalar_sql(
733 $last_bill->_date - 1,
736 $last_bill_balance += $delta;
739 $last_bill_balance = sprintf("%.2f", $last_bill_balance);
741 warn sprintf("LAST BILL: INVNUM %d, DATE %s, BALANCE %.2f\n\n",
743 $self->time2str_local('%D', $last_bill->_date),
746 # ("true_previous_balance" is a terrible name, but at least it's no
747 # longer stored in the database)
748 $invoice_data{'true_previous_balance'} = $last_bill_balance;
750 # Now, get all applications of credits/payments dated on or after the
751 # previous bill, to invoices before the current bill. (The
752 # credit/payment date restriction prevents these from intersecting
753 # the "Previous Balance" set.)
754 # These are "adjustments". The past due balance will be shown as
755 # Previous Balance - Adjustments.
758 "SELECT COALESCE(SUM(y.amount),0) FROM $_ JOIN cust_bill USING (invnum)
759 WHERE cust_bill._date < ?
761 AND cust_bill.custnum = ?"
762 } "cust_credit AS x JOIN cust_credit_bill y USING (crednum)",
763 "cust_pay AS x JOIN cust_bill_pay y USING (paynum)"
766 my $delta = FS::Record->scalar_sql(
772 $adjustments += $delta;
774 $invoice_data{'balance_adjustments'} = sprintf("%.2f", $adjustments);
776 warn sprintf("BALANCE ADJUSTMENTS: %.2f\n\n",
777 $invoice_data{'balance_adjustments'}
780 # the sum of amount owed on all previous invoices
781 # ($pr_total is used elsewhere but not as $previous_balance)
782 $invoice_data{'previous_balance'} = sprintf("%.2f", $pr_total);
784 $invoice_data{'last_bill'}{'_date'} = $last_bill->_date; #unformatted
785 my (@payments, @credits);
786 # for formats that itemize previous payments
787 foreach my $cust_pay ( qsearch('cust_pay', {
788 'custnum' => $self->custnum,
789 '_date' => { op => '>=',
790 value => $last_bill->_date }
793 next if $cust_pay->_date > $self->_date;
795 '_date' => $cust_pay->_date,
796 'date' => $self->time2str_local('long', $cust_pay->_date, $format),
797 'payinfo' => $cust_pay->payby_payinfo_pretty,
798 'amount' => sprintf('%.2f', $cust_pay->paid),
800 # not concerned about applications
802 foreach my $cust_credit ( qsearch('cust_credit', {
803 'custnum' => $self->custnum,
804 '_date' => { op => '>=',
805 value => $last_bill->_date }
808 next if $cust_credit->_date > $self->_date;
810 '_date' => $cust_credit->_date,
811 'date' => $self->time2str_local('long', $cust_credit->_date, $format),
812 'creditreason'=> $cust_credit->reason,
813 'amount' => sprintf('%.2f', $cust_credit->amount),
816 $invoice_data{'previous_payments'} = \@payments;
817 $invoice_data{'previous_credits'} = \@credits;
819 # there is no $last_bill
820 $invoice_data{'true_previous_balance'} =
821 $invoice_data{'balance_adjustments'} =
822 $invoice_data{'previous_balance'} = '0.00';
823 $invoice_data{'previous_payments'} = [];
824 $invoice_data{'previous_credits'} = [];
827 if ( $conf->exists('invoice_usesummary', $agentnum) ) {
828 $invoice_data{'summarypage'} = $summarypage = 1;
831 } # if this is an invoice
833 warn "$me substituting variables in notes, footer, smallfooter\n"
836 my $tc = $self->template_conf;
837 my @include = ( [ $tc, 'notes' ],
838 [ 'invoice_', 'footer' ],
839 [ 'invoice_', 'smallfooter', ],
840 [ 'invoice_', 'watermark' ],
842 push @include, [ $tc, 'coupon', ]
843 unless $params{'no_coupon'};
845 foreach my $i (@include) {
847 # load the configuration for this sub-template
849 my($base, $include) = @$i;
851 my $inc_file = $conf->key_orbase("$base$format$include", $template);
853 my @inc_src = $conf->config($inc_file, $agentnum);
855 my $converter = $convert_maps{$format}{$include};
857 # then attempt to convert LaTeX to the requested format
858 $inc_file = $conf->key_orbase($base.'latex'.$include, $template);
859 @inc_src = &$converter( $conf->config($inc_file, $agentnum) );
861 # this isn't included in the convert_maps
862 my ($open, $close) = @{ $delimiters{$format} };
867 } # else @inc_src is empty and that's fine
869 # make a Text::Template out of it
871 my $inc_tt = new Text::Template (
873 SOURCE => [ map "$_\n", @inc_src ],
874 DELIMITERS => $delimiters{$format},
875 ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
877 unless ( $inc_tt->compile() ) {
878 my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
879 warn $error. "Template:\n". join('', map "$_\n", @inc_src);
885 $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
887 $invoice_data{$include} =~ s/\n+$//
888 if ($format eq 'latex');
891 # if (well, probably when) we still need PO numbers in the brave new world of
892 # 4.x, then we'll have to add them back as their own customer fields
893 # # let invoices use either of these as needed
894 # $invoice_data{'po_num'} = ($cust_main->payby eq 'BILL')
895 # ? $cust_main->payinfo : '';
896 # $invoice_data{'po_line'} =
897 # ( $cust_main->payby eq 'BILL' && $cust_main->payinfo )
898 # ? &$escape_function($self->mt("Purchase Order #").$cust_main->payinfo)
901 my %money_chars = ( 'latex' => '',
902 'html' => $conf->config('money_char') || '$',
905 my $money_char = $money_chars{$format};
908 my %other_money_chars = ( 'latex' => '\dollar ',#XXX should be a config too
909 'html' => $conf->config('money_char') || '$',
912 my $other_money_char = $other_money_chars{$format};
913 $invoice_data{'dollar'} = $other_money_char;
915 my %minus_signs = ( 'latex' => '$-$',
917 'template' => '- ' );
918 my $minus = $minus_signs{$format};
920 my @detail_items = ();
921 my @total_items = ();
925 $invoice_data{'detail_items'} = \@detail_items;
926 $invoice_data{'total_items'} = \@total_items;
927 $invoice_data{'buf'} = \@buf;
928 $invoice_data{'sections'} = \@sections;
930 warn "$me generating sections\n"
933 my $unsquelched = $params{unsquelch_cdr} || $cust_main->squelch_cdr ne 'Y';
934 my $multisection = $self->has_sections;
935 $conf->exists($tc.'sections', $cust_main->agentnum) ||
936 $conf->exists($tc.'sections_by_location', $cust_main->agentnum);
937 $invoice_data{'multisection'} = $multisection;
939 my $extra_sections = [];
940 my $extra_lines = ();
942 # default section ('Charges')
943 my $default_section = { 'description' => '',
948 # Previous Charges section
949 # subtotal is the first return value from $self->previous
950 my $previous_section;
951 # if the invoice has major sections, or if we're summarizing previous
952 # charges with a single line, or if we've been specifically told to put them
953 # in a section, create a section for previous charges:
954 if ( $multisection or
955 $conf->exists('previous_balance-summary_only') or
956 $conf->exists('previous_balance-section') ) {
958 $previous_section = { 'description' => $self->mt('Previous Charges'),
959 'subtotal' => $other_money_char.
960 sprintf('%.2f', $pr_total),
961 'summarized' => '', #why? $summarypage ? 'Y' : '',
963 $previous_section->{posttotal} = '0 / 30 / 60 / 90 days overdue '.
964 join(' / ', map { $cust_main->balance_date_range(@$_) }
965 $self->_prior_month30s
967 if $conf->exists('invoice_include_aging');
970 # otherwise put them in the main section
971 $previous_section = $default_section;
974 my $adjust_section = {
975 'description' => $self->mt('Credits, Payments, and Adjustments'),
976 'adjust_section' => 1,
977 'subtotal' => 0, # adjusted below
979 my $adjust_weight = _pkg_category($adjust_section->{description})
980 ? _pkg_category($adjust_section->{description})->weight
982 $adjust_section->{'summarized'} = ''; #why? $summarypage && !$adjust_weight ? 'Y' : '';
983 # Note: 'sort_weight' here is actually a flag telling whether there is an
984 # explicit package category for the adjust section. If so, certain behavior
986 $adjust_section->{'sort_weight'} = $adjust_weight;
989 if ( $multisection ) {
990 ($extra_sections, $extra_lines) =
991 $self->_items_extra_usage_sections($escape_function_nonbsp, $format)
992 if $conf->exists('usage_class_as_a_section', $cust_main->agentnum)
993 && $self->can('_items_extra_usage_sections');
995 push @$extra_sections, $adjust_section if $adjust_section->{sort_weight};
997 push @detail_items, @$extra_lines if $extra_lines;
999 # the code is written so that both methods can be used together, but
1000 # we haven't yet changed the template to take advantage of that, so for
1001 # now, treat them as mutually exclusive.
1002 my %section_method = ( by_category => 1 );
1003 if ( $conf->config($tc.'sections_method') eq 'location' ) {
1004 %section_method = ( by_location => 1 );
1006 my ($early, $late) =
1007 $self->_items_sections( 'summary' => $summarypage,
1008 'escape' => $escape_function_nonbsp,
1009 'extra_sections' => $extra_sections,
1010 'format' => $format,
1013 push @sections, @$early;
1014 $late_sections = $late;
1016 if ( $conf->exists('svc_phone_sections')
1017 && $self->can('_items_svc_phone_sections')
1020 my ($phone_sections, $phone_lines) =
1021 $self->_items_svc_phone_sections($escape_function_nonbsp, $format);
1022 push @{$late_sections}, @$phone_sections;
1023 push @detail_items, @$phone_lines;
1025 if ( $conf->exists('voip-cust_accountcode_cdr')
1026 && $cust_main->accountcode_cdr
1027 && $self->can('_items_accountcode_cdr')
1030 my ($accountcode_section, $accountcode_lines) =
1031 $self->_items_accountcode_cdr($escape_function_nonbsp,$format);
1032 if ( scalar(@$accountcode_lines) ) {
1033 push @{$late_sections}, $accountcode_section;
1034 push @detail_items, @$accountcode_lines;
1037 } else {# not multisection
1038 # make a default section
1039 push @sections, $default_section;
1040 # and calculate the finance charge total, since it won't get done otherwise.
1041 # and the default section total
1042 # XXX possibly finance_pkgclass should not be used in this manner?
1043 my @finance_charges;
1045 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1046 if ( $invoice_data{finance_section} and
1047 grep { $_->section eq $invoice_data{finance_section} }
1048 $cust_bill_pkg->cust_bill_pkg_display ) {
1049 # I think these are always setup fees, but just to be sure...
1050 push @finance_charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1052 push @charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1055 $invoice_data{finance_amount} =
1056 sprintf('%.2f', sum( @finance_charges ) || 0);
1057 $default_section->{subtotal} = $other_money_char.
1058 sprintf('%.2f', sum( @charges ) || 0);
1061 # start setting up summary subtotals
1062 my @summary_subtotals;
1063 my $method = $conf->config('summary_subtotals_method');
1064 if ( $method and $method ne $conf->config($tc.'sections_method') ) {
1065 # then re-section them by the correct method
1066 my %section_method = ( by_category => 1 );
1067 if ( $conf->config('summary_subtotals_method') eq 'location' ) {
1068 %section_method = ( by_location => 1 );
1070 my ($early, $late) =
1071 $self->_items_sections( 'summary' => $summarypage,
1072 'escape' => $escape_function_nonbsp,
1073 'extra_sections' => $extra_sections,
1074 'format' => $format,
1077 foreach ( @$early ) {
1078 next if $_->{subtotal} == 0;
1079 $_->{subtotal} = $other_money_char.sprintf('%.2f', $_->{subtotal});
1080 push @summary_subtotals, $_;
1083 # subtotal sectioning is the same as for the actual invoice sections
1084 @summary_subtotals = @sections;
1087 # Hereafter, push sections to both @sections and @summary_subtotals
1088 # if they belong in both places (e.g. tax section). Late sections are
1089 # never in @summary_subtotals.
1091 # previous invoice balances in the Previous Charges section if there
1092 # is one, otherwise in the main detail section
1093 # (except if summary_only is enabled, don't show them at all)
1094 if ( $self->can('_items_previous') &&
1095 $self->enable_previous &&
1096 ! $conf->exists('previous_balance-summary_only') ) {
1098 warn "$me adding previous balances\n"
1101 foreach my $line_item ( $self->_items_previous ) {
1104 ref => $line_item->{'pkgnum'},
1105 pkgpart => $line_item->{'pkgpart'},
1106 #quantity => 1, # not really correct
1107 section => $previous_section, # which might be $default_section
1108 description => &$escape_function($line_item->{'description'}),
1109 ext_description => [ map { &$escape_function($_) }
1110 @{ $line_item->{'ext_description'} || [] }
1112 amount => $money_char . $line_item->{'amount'},
1113 product_code => $line_item->{'pkgpart'} || 'N/A',
1116 push @detail_items, $detail;
1117 push @buf, [ $detail->{'description'},
1118 $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1124 if ( @pr_cust_bill && $self->enable_previous ) {
1125 push @buf, ['','-----------'];
1126 push @buf, [ $self->mt('Total Previous Balance'),
1127 $money_char. sprintf("%10.2f", $pr_total) ];
1131 if ( $conf->exists('svc_phone-did-summary') && $self->can('_did_summary') ) {
1132 warn "$me adding DID summary\n"
1135 my ($didsummary,$minutes) = $self->_did_summary;
1136 my $didsummary_desc = 'DID Activity Summary (since last invoice)';
1138 { 'description' => $didsummary_desc,
1139 'ext_description' => [ $didsummary, $minutes ],
1143 foreach my $section (@sections, @$late_sections) {
1145 # begin some normalization
1146 $section->{'subtotal'} = $section->{'amount'}
1148 && !exists($section->{subtotal})
1149 && exists($section->{amount});
1151 $invoice_data{finance_amount} = sprintf('%.2f', $section->{'subtotal'} )
1152 if ( $invoice_data{finance_section} &&
1153 $section->{'description'} eq $invoice_data{finance_section} );
1155 $section->{'subtotal'} = $other_money_char.
1156 sprintf('%.2f', $section->{'subtotal'})
1159 # continue some normalization
1160 $section->{'amount'} = $section->{'subtotal'}
1164 if ( $section->{'description'} ) {
1165 push @buf, ( [ &$escape_function($section->{'description'}), '' ],
1170 warn "$me setting options\n"
1174 $options{'section'} = $section if $multisection;
1175 $options{'format'} = $format;
1176 $options{'escape_function'} = $escape_function;
1177 $options{'no_usage'} = 1 unless $unsquelched;
1178 $options{'unsquelched'} = $unsquelched;
1179 $options{'summary_page'} = $summarypage;
1180 $options{'skip_usage'} =
1181 scalar(@$extra_sections) && !grep{$section == $_} @$extra_sections;
1182 $options{'preref_callback'} = $params{'preref_callback'};
1184 warn "$me searching for line items\n"
1187 foreach my $line_item ( $self->_items_pkg(%options),
1188 $self->_items_fee(%options) ) {
1190 warn "$me adding line item ".
1191 join(', ', map "$_=>".$line_item->{$_}, keys %$line_item). "\n"
1194 push @buf, ( [ $line_item->{'description'},
1195 $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1197 map { [ " ". $_, '' ] } @{$line_item->{'ext_description'}},
1200 $line_item->{'ref'} = $line_item->{'pkgnum'};
1201 $line_item->{'product_code'} = $line_item->{'pkgpart'} || 'N/A'; # mt()?
1202 $line_item->{'section'} = $section;
1203 $line_item->{'description'} = &$escape_function($line_item->{'description'});
1204 $line_item->{'amount'} = $money_char.$line_item->{'amount'};
1206 if ( length($line_item->{'unit_amount'}) ) {
1207 $line_item->{'unit_amount'} = $money_char.$line_item->{'unit_amount'};
1209 $line_item->{'ext_description'} ||= [];
1211 push @detail_items, $line_item;
1214 if ( $section->{'description'} ) {
1215 push @buf, ( ['','-----------'],
1216 [ $section->{'description'}. ' sub-total',
1217 $section->{'subtotal'} # already formatted this
1226 $invoice_data{current_less_finance} =
1227 sprintf('%.2f', $self->charged - $invoice_data{finance_amount} );
1229 # if there's anything in the Previous Charges section, prepend it to the list
1230 if ( $pr_total and $previous_section ne $default_section ) {
1231 unshift @sections, $previous_section;
1232 # but not @summary_subtotals
1235 warn "$me adding taxes\n"
1238 # create a tax section if we don't yet have one
1239 my $tax_description = 'Taxes, Surcharges, and Fees';
1241 List::Util::first { $_->{description} eq $tax_description } @sections;
1242 if (!$tax_section) {
1243 $tax_section = { 'description' => $tax_description };
1245 $tax_section->{tax_section} = 1; # mark this section as containing taxes
1246 # if this is an existing tax section, we're merging the tax items into it.
1247 # grab the taxtotal that's already there, strip the money symbol if any
1248 my $taxtotal = $tax_section->{'subtotal'} || 0;
1249 $taxtotal =~ s/^\Q$other_money_char\E//;
1252 #my $tax_weight = _pkg_category($tax_section->{description})
1253 # ? _pkg_category($tax_section->{description})->weight
1255 #$tax_section->{'summarized'} = ''; #why? $summarypage && !$tax_weight ? 'Y' : '';
1256 #$tax_section->{'sort_weight'} = $tax_weight;
1258 my @items_tax = $self->_items_tax;
1259 push @sections, $tax_section if $multisection and @items_tax > 0;
1261 foreach my $tax ( @items_tax ) {
1263 $taxtotal += $tax->{'amount'};
1265 my $description = &$escape_function( $tax->{'description'} );
1266 my $amount = sprintf( '%.2f', $tax->{'amount'} );
1268 if ( $multisection ) {
1270 push @detail_items, {
1271 ext_description => [],
1274 description => $description,
1275 amount => $money_char. $amount,
1277 section => $tax_section,
1282 push @total_items, {
1283 'total_item' => $description,
1284 'total_amount' => $other_money_char. $amount,
1289 push @buf,[ $description,
1290 $money_char. $amount,
1297 $total->{'total_item'} = $self->mt('Sub-total');
1298 $total->{'total_amount'} =
1299 $other_money_char. sprintf('%.2f', $self->charged - $taxtotal );
1301 if ( $multisection ) {
1302 if ( $taxtotal > 0 ) {
1303 # there are taxes, so prepare the section to be displayed.
1304 # $taxtotal already includes any line items that were already in the
1305 # section (fees, taxes that are charged as packages for some reason).
1306 # also set 'summarized' to false so that this isn't a summary-only
1308 $tax_section->{'subtotal'} = $other_money_char.
1309 sprintf('%.2f', $taxtotal);
1310 $tax_section->{'pretotal'} = 'New charges sub-total '.
1311 $total->{'total_amount'};
1312 $tax_section->{'description'} = $self->mt($tax_description);
1313 $tax_section->{'summarized'} = '';
1315 # append it if it's not already there
1316 if ( !grep $tax_section, @sections ) {
1317 push @sections, $tax_section;
1318 push @summary_subtotals, $tax_section;
1323 unshift @total_items, $total;
1326 $invoice_data{'taxtotal'} = sprintf('%.2f', $taxtotal);
1332 my %embolden_functions = (
1333 'latex' => sub { return '\textbf{'. shift(). '}' },
1334 'html' => sub { return '<b>'. shift(). '</b>' },
1335 'template' => sub { shift },
1337 my $embolden_function = $embolden_functions{$format};
1339 if ( $multisection ) {
1341 if ( $adjust_section->{'sort_weight'} ) {
1342 $adjust_section->{'posttotal'} = $self->mt('Balance Forward').' '.
1343 $other_money_char. sprintf("%.2f", ($self->billing_balance || 0) );
1345 $adjust_section->{'pretotal'} = $self->mt('New charges total').' '.
1346 $other_money_char. sprintf('%.2f', $self->charged );
1351 if ( $self->can('_items_total') ) { # should always be true now
1353 # even for multisection, need plain text version
1355 my @new_total_items = $self->_items_total;
1357 push @buf,['','-----------'];
1359 foreach ( @new_total_items ) {
1360 my ($item, $amount) = ($_->{'total_item'}, $_->{'total_amount'});
1361 $_->{'total_item'} = &$embolden_function( $item );
1362 $_->{'total_amount'} = &$embolden_function( $other_money_char.$amount );
1363 # but if it's multisection, don't append to @total_items. the adjust
1364 # section has all this stuff
1365 push @total_items, $_ if !$multisection;
1366 push @buf, [ $item, $money_char.sprintf('%10.2f',$amount) ];
1369 push @buf, [ '', '' ];
1371 # if we're showing previous invoices, also show previous
1372 # credits and payments
1373 if ( $self->enable_previous
1374 and $self->can('_items_credits')
1375 and $self->can('_items_payments') )
1379 my $credittotal = 0;
1380 foreach my $credit (
1381 $self->_items_credits( 'template' => $template, 'trim_len' => 40 )
1385 $total->{'total_item'} = &$escape_function($credit->{'description'});
1386 $credittotal += $credit->{'amount'};
1387 $total->{'total_amount'} = $minus.$other_money_char.$credit->{'amount'};
1388 if ( $multisection ) {
1389 push @detail_items, {
1390 ext_description => [],
1393 description => &$escape_function($credit->{'description'}),
1394 amount => $money_char . $credit->{'amount'},
1396 section => $adjust_section,
1399 push @total_items, $total;
1403 $invoice_data{'credittotal'} = sprintf('%.2f', $credittotal);
1406 foreach my $credit (
1407 $self->_items_credits( 'template' => $template, 'trim_len'=>32 )
1409 push @buf, [ $credit->{'description'}, $money_char.$credit->{'amount'} ];
1413 my $paymenttotal = 0;
1414 foreach my $payment (
1415 $self->_items_payments( 'template' => $template )
1418 $total->{'total_item'} = &$escape_function($payment->{'description'});
1419 $paymenttotal += $payment->{'amount'};
1420 $total->{'total_amount'} = $minus.$other_money_char.$payment->{'amount'};
1421 if ( $multisection ) {
1422 push @detail_items, {
1423 ext_description => [],
1426 description => &$escape_function($payment->{'description'}),
1427 amount => $money_char . $payment->{'amount'},
1429 section => $adjust_section,
1432 push @total_items, $total;
1434 push @buf, [ $payment->{'description'},
1435 $money_char. sprintf("%10.2f", $payment->{'amount'}),
1438 $invoice_data{'paymenttotal'} = sprintf('%.2f', $paymenttotal);
1440 if ( $multisection ) {
1441 $adjust_section->{'subtotal'} = $other_money_char.
1442 sprintf('%.2f', $credittotal + $paymenttotal);
1444 #why this? because {sort_weight} forces the adjust_section to appear
1445 #in @extra_sections instead of @sections. obviously.
1446 push @sections, $adjust_section
1447 unless $adjust_section->{sort_weight};
1448 # do not summarize; adjustments there are shown according to
1452 # create Balance Due message
1455 $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1456 $total->{'total_amount'} =
1457 &$embolden_function(
1458 $other_money_char. sprintf('%.2f', #why? $summarypage
1459 # ? $self->charged +
1460 # $self->billing_balance
1462 $self->owed + $pr_total
1465 if ( $multisection && !$adjust_section->{sort_weight} ) {
1466 $adjust_section->{'posttotal'} = $total->{'total_item'}. ' '.
1467 $total->{'total_amount'};
1469 push @total_items, $total;
1471 push @buf,['','-----------'];
1472 push @buf,[$self->balance_due_msg, $money_char.
1473 sprintf("%10.2f", $balance_due ) ];
1476 if ( $conf->exists('previous_balance-show_credit')
1477 and $cust_main->balance < 0 ) {
1478 my $credit_total = {
1479 'total_item' => &$embolden_function($self->credit_balance_msg),
1480 'total_amount' => &$embolden_function(
1481 $other_money_char. sprintf('%.2f', -$cust_main->balance)
1484 if ( $multisection ) {
1485 $adjust_section->{'posttotal'} .= $newline_token .
1486 $credit_total->{'total_item'} . ' ' . $credit_total->{'total_amount'};
1489 push @total_items, $credit_total;
1491 push @buf,['','-----------'];
1492 push @buf,[$self->credit_balance_msg, $money_char.
1493 sprintf("%10.2f", -$cust_main->balance ) ];
1497 } #end of default total adding ! can('_items_total')
1499 if ( $multisection ) {
1500 if ( $conf->exists('svc_phone_sections')
1501 && $self->can('_items_svc_phone_sections')
1505 $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1506 $total->{'total_amount'} =
1507 &$embolden_function(
1508 $other_money_char. sprintf('%.2f', $self->owed + $pr_total)
1510 my $last_section = pop @sections;
1511 $last_section->{'posttotal'} = $total->{'total_item'}. ' '.
1512 $total->{'total_amount'};
1513 push @sections, $last_section;
1515 push @sections, @$late_sections
1519 # make a discounts-available section, even without multisection
1520 if ( $conf->exists('discount-show_available')
1521 and my @discounts_avail = $self->_items_discounts_avail ) {
1522 my $discount_section = {
1523 'description' => $self->mt('Discounts Available'),
1528 push @sections, $discount_section; # do not summarize
1529 push @detail_items, map { +{
1530 'ref' => '', #should this be something else?
1531 'section' => $discount_section,
1532 'description' => &$escape_function( $_->{description} ),
1533 'amount' => $money_char . &$escape_function( $_->{amount} ),
1534 'ext_description' => [ &$escape_function($_->{ext_description}) || () ],
1535 } } @discounts_avail;
1538 # not adding any more sections after this
1539 $invoice_data{summary_subtotals} = \@summary_subtotals;
1542 if ( $conf->exists('usage_class_summary')
1543 and $self->can('_items_usage_class_summary') ) {
1544 my @usage_subtotals = $self->_items_usage_class_summary(escape => $escape_function, 'money_char' => $other_money_char);
1545 if ( @usage_subtotals ) {
1546 unshift @sections, $usage_subtotals[0]->{section}; # do not summarize
1547 unshift @detail_items, @usage_subtotals;
1551 # invoice history "section" (not really a section)
1552 # not to be included in any subtotals, completely independent of
1554 if ( $conf->exists('previous_invoice_history') and $cust_main->isa('FS::cust_main') ) {
1557 foreach my $cust_bill ( $cust_main->cust_bill ) {
1558 # XXX hardcoded format, and currently only 'charged'; add other fields
1559 # if they become necessary
1560 my $date = $self->time2str_local('%b %Y', $cust_bill->_date);
1561 $history{$date} ||= 0;
1562 $history{$date} += $cust_bill->charged;
1563 # just so we have a numeric sort key
1564 $monthorder{$date} ||= $cust_bill->_date;
1566 my @sorted_months = sort { $monthorder{$a} <=> $monthorder{$b} }
1568 my @sorted_amounts = map { sprintf('%.2f', $history{$_}) } @sorted_months;
1569 $invoice_data{monthly_history} = [ \@sorted_months, \@sorted_amounts ];
1572 # service locations: another option for template customization
1574 foreach my $item (@detail_items) {
1575 if ( $item->{locationnum} ) {
1576 $location_info{ $item->{locationnum} } ||= {
1577 FS::cust_location->by_key( $item->{locationnum} )->location_hash
1581 $invoice_data{location_info} = \%location_info;
1583 # debugging hook: call this with 'diag' => 1 to just get a hash of
1584 # the invoice variables
1585 return \%invoice_data if ( $params{'diag'} );
1587 # All sections and items are built; now fill in templates.
1588 my @includelist = ();
1589 push @includelist, 'summary' if $summarypage;
1590 foreach my $include ( @includelist ) {
1592 my $inc_file = $conf->key_orbase("invoice_${format}$include", $template);
1595 if ( length( $conf->config($inc_file, $agentnum) ) ) {
1597 @inc_src = $conf->config($inc_file, $agentnum);
1601 $inc_file = $conf->key_orbase("invoice_latex$include", $template);
1603 my $convert_map = $convert_maps{$format}{$include};
1605 @inc_src = map { s/\[\@--/$delimiters{$format}[0]/g;
1606 s/--\@\]/$delimiters{$format}[1]/g;
1609 &$convert_map( $conf->config($inc_file, $agentnum) );
1613 my $inc_tt = new Text::Template (
1615 SOURCE => [ map "$_\n", @inc_src ],
1616 DELIMITERS => $delimiters{$format},
1617 ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
1619 unless ( $inc_tt->compile() ) {
1620 my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
1621 warn $error. "Template:\n". join('', map "$_\n", @inc_src);
1625 $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
1627 $invoice_data{$include} =~ s/\n+$//
1628 if ($format eq 'latex');
1633 foreach ( grep /invoice_lines\(\d*\)/, @invoice_template ) { #kludgy
1634 /invoice_lines\((\d*)\)/;
1635 $invoice_lines += $1 || scalar(@buf);
1638 die "no invoice_lines() functions in template?"
1639 if ( $format eq 'template' && !$wasfunc );
1641 if ($format eq 'template') {
1643 if ( $invoice_lines ) {
1644 $invoice_data{'total_pages'} = int( scalar(@buf) / $invoice_lines );
1645 $invoice_data{'total_pages'}++
1646 if scalar(@buf) % $invoice_lines;
1649 #setup subroutine for the template
1650 $invoice_data{invoice_lines} = sub {
1651 my $lines = shift || scalar(@buf);
1663 push @collect, split("\n",
1664 $text_template->fill_in( HASH => \%invoice_data )
1666 $invoice_data{'page'}++;
1668 map "$_\n", @collect;
1670 } else { # this is where we actually create the invoice
1672 if ( $params{no_addresses} ) {
1673 delete $invoice_data{$_} foreach qw(
1674 payname company address1 address2 city state zip country
1676 $invoice_data{returnaddress} = '~';
1679 warn "filling in template for invoice ". $self->invnum. "\n"
1681 warn join("\n", map " $_ => ". $invoice_data{$_}, keys %invoice_data). "\n"
1684 $text_template->fill_in(HASH => \%invoice_data);
1688 sub notice_name { '('.shift->table.')'; }
1690 # this is not supposed to happen
1691 sub template_conf { warn "bare FS::Template_Mixin::template_conf";
1695 # helper routine for generating date ranges
1696 sub _prior_month30s {
1699 [ 1, 2592000 ], # 0-30 days ago
1700 [ 2592000, 5184000 ], # 30-60 days ago
1701 [ 5184000, 7776000 ], # 60-90 days ago
1702 [ 7776000, 0 ], # 90+ days ago
1705 map { [ $_->[0] ? $self->_date - $_->[0] - 1 : '',
1706 $_->[1] ? $self->_date - $_->[1] - 1 : '',
1711 =item print_ps HASHREF | [ TIME [ , TEMPLATE ] ]
1713 Returns an postscript invoice, as a scalar.
1715 Options can be passed as a hashref (recommended) or as a list of time, template
1716 and then any key/value pairs for any other options.
1718 I<time> an optional value used to control the printing of overdue messages. The
1719 default is now. It isn't the date of the invoice; that's the `_date' field.
1720 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1721 L<Time::Local> and L<Date::Parse> for conversion functions.
1723 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1730 my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1731 my $ps = generate_ps($file);
1733 unlink($barcodefile) if $barcodefile;
1738 =item print_pdf HASHREF | [ TIME [ , TEMPLATE ] ]
1740 Returns an PDF invoice, as a scalar.
1742 Options can be passed as a hashref (recommended) or as a list of time, template
1743 and then any key/value pairs for any other options.
1745 I<time> an optional value used to control the printing of overdue messages. The
1746 default is now. It isn't the date of the invoice; that's the `_date' field.
1747 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1748 L<Time::Local> and L<Date::Parse> for conversion functions.
1750 I<template>, if specified, is the name of a suffix for alternate invoices.
1752 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1759 my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1760 my $pdf = generate_pdf($file);
1762 unlink($barcodefile) if $barcodefile;
1767 =item print_html HASHREF | [ TIME [ , TEMPLATE [ , CID ] ] ]
1769 Returns an HTML invoice, as a scalar.
1771 I<time> an optional value used to control the printing of overdue messages. The
1772 default is now. It isn't the date of the invoice; that's the `_date' field.
1773 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1774 L<Time::Local> and L<Date::Parse> for conversion functions.
1776 I<template>, if specified, is the name of a suffix for alternate invoices.
1778 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1780 I<cid> is a MIME Content-ID used to create a "cid:" URL for the logo image, used
1781 when emailing the invoice as part of a multipart/related MIME email.
1789 %params = %{ shift() };
1793 $params{'format'} = 'html';
1795 $self->print_generic( %params );
1798 # quick subroutine for print_latex
1800 # There are ten characters that LaTeX treats as special characters, which
1801 # means that they do not simply typeset themselves:
1802 # # $ % & ~ _ ^ \ { }
1804 # TeX ignores blanks following an escaped character; if you want a blank (as
1805 # in "10% of ..."), you have to "escape" the blank as well ("10\%\ of ...").
1809 $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
1810 $value =~ s/([<>])/\$$1\$/g;
1816 encode_entities($value);
1820 sub _html_escape_nbsp {
1821 my $value = _html_escape(shift);
1822 $value =~ s/ +/ /g;
1826 #utility methods for print_*
1828 sub _translate_old_latex_format {
1829 warn "_translate_old_latex_format called\n"
1836 if ( $line =~ /^%%Detail\s*$/ ) {
1838 push @template, q![@--!,
1839 q! foreach my $_tr_line (@detail_items) {!,
1840 q! if ( scalar ($_tr_item->{'ext_description'} ) ) {!,
1841 q! $_tr_line->{'description'} .= !,
1842 q! "\\tabularnewline\n~~".!,
1843 q! join( "\\tabularnewline\n~~",!,
1844 q! @{$_tr_line->{'ext_description'}}!,
1848 while ( ( my $line_item_line = shift )
1849 !~ /^%%EndDetail\s*$/ ) {
1850 $line_item_line =~ s/'/\\'/g; # nice LTS
1851 $line_item_line =~ s/\\/\\\\/g; # escape quotes and backslashes
1852 $line_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1853 push @template, " \$OUT .= '$line_item_line';";
1856 push @template, '}',
1859 } elsif ( $line =~ /^%%TotalDetails\s*$/ ) {
1861 push @template, '[@--',
1862 ' foreach my $_tr_line (@total_items) {';
1864 while ( ( my $total_item_line = shift )
1865 !~ /^%%EndTotalDetails\s*$/ ) {
1866 $total_item_line =~ s/'/\\'/g; # nice LTS
1867 $total_item_line =~ s/\\/\\\\/g; # escape quotes and backslashes
1868 $total_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1869 push @template, " \$OUT .= '$total_item_line';";
1872 push @template, '}',
1876 $line =~ s/\$(\w+)/[\@-- \$$1 --\@]/g;
1877 push @template, $line;
1883 warn "$_\n" foreach @template;
1895 my $conf = $self->conf;
1897 #check for an invoice-specific override
1898 return $self->invoice_terms if $self->invoice_terms;
1900 #check for a customer- specific override
1901 my $cust_main = $self->cust_main;
1902 return $cust_main->invoice_terms if $cust_main && $cust_main->invoice_terms;
1906 $agentnum = $cust_main->agentnum;
1907 } elsif ( my $prospect_main = $self->prospect_main ) {
1908 $agentnum = $prospect_main->agentnum;
1911 #use configured default
1912 $conf->config('invoice_default_terms', $agentnum) || '';
1922 if ( $self->terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
1923 $duedate = $self->_date() + ( $1 * 86400 );
1934 $self->due_date ? $self->time2str_local(shift, $self->due_date) : '';
1937 =item balance_due_msg
1941 sub balance_due_msg {
1943 my $msg = $self->mt('Balance Due');
1944 return $msg unless $self->terms; # huh?
1945 if ( !$self->conf->exists('invoice_show_prior_due_date')
1946 or $self->conf->exists('invoice_sections') ) {
1947 # if enabled, the due date is shown with Total New Charges (see
1948 # _items_total) and not here
1949 # (yes, or if invoice_sections is enabled; this is just for compatibility)
1950 if ( $self->due_date ) {
1951 $msg .= ' - ' . $self->mt('Please pay by'). ' '.
1952 $self->due_date2str('short');
1953 } elsif ( $self->terms ) {
1954 $msg .= ' - '. $self->mt($self->terms);
1960 =item balance_due_date
1964 sub balance_due_date {
1966 my $conf = $self->conf;
1968 my $terms = $self->terms;
1969 if ( $terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
1970 $duedate = $self->time2str_local('rdate', $self->_date + ($1*86400) );
1975 sub credit_balance_msg {
1977 $self->mt('Credit Balance Remaining')
1982 Returns a string with the date, for example: "3/20/2008", localized for the
1983 customer. Use _date_pretty_unlocalized for non-end-customer display use.
1989 $self->time2str_local('short', $self->_date);
1992 =item _date_pretty_unlocalized
1994 Returns a string with the date, for example: "3/20/2008", in the format
1995 configured for the back-office. Use _date_pretty for end-customer display use.
1999 sub _date_pretty_unlocalized {
2001 time2str($date_format, $self->_date);
2006 Emails this template.
2008 Options are passed as a hashref. Available options:
2014 If specified, overrides the default From: address.
2018 If specified, overrides the name of the sent document ("Invoice" or "Quotation")
2022 (Deprecated) If specified, is the name of a suffix for alternate template files.
2026 Options accepted by generate_email can also be used.
2032 my $opt = shift || {};
2033 if ($opt and !ref($opt)) {
2034 die ref($self). '->email called with positional parameters';
2037 return if $self->hide;
2039 my $error = send_email(
2040 $self->generate_email(
2041 'subject' => $self->email_subject($opt->{template}),
2042 %$opt, # template, etc.
2046 die "can't email: $error\n" if $error;
2049 =item generate_email OPTION => VALUE ...
2057 sender address, required
2061 alternate template name, optional
2065 email subject, optional
2069 notice name instead of "Invoice", optional
2073 Returns an argument list to be passed to L<FS::Misc::send_email>.
2079 sub generate_email {
2083 my $conf = $self->conf;
2085 my $me = '[FS::Template_Mixin::generate_email]';
2088 'from' => $args{'from'},
2089 'subject' => ($args{'subject'} || $self->email_subject),
2090 'custnum' => $self->custnum,
2091 'msgtype' => 'invoice',
2094 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
2096 my $cust_main = $self->cust_main;
2098 if (ref($args{'to'}) eq 'ARRAY') {
2099 $return{'to'} = $args{'to'};
2100 } elsif ( $cust_main ) {
2101 $return{'to'} = [ $cust_main->invoicing_list_emailonly ];
2104 my $tc = $self->template_conf;
2106 my @text; # array of lines
2107 my $html; # a big string
2108 my @related_parts; # will contain the text/HTML alternative, and images
2109 my $related; # will contain the multipart/related object
2111 if ( $conf->exists($tc. 'email_pdf') ) {
2112 if ( my $msgnum = $conf->config($tc.'email_pdf_msgnum') ) {
2114 warn "$me using '${tc}email_pdf_msgnum' in multipart message"
2117 my $msg_template = FS::msg_template->by_key($msgnum)
2118 or die "${tc}email_pdf_msgnum $msgnum not found\n";
2119 my %prepared = $msg_template->prepare(
2120 cust_main => $self->cust_main,
2124 @text = split(/(?=\n)/, $prepared{'text_body'});
2125 $html = $prepared{'html_body'};
2127 } elsif ( my @note = $conf->config($tc.'email_pdf_note') ) {
2129 warn "$me using '${tc}email_pdf_note' in multipart message"
2131 @text = $conf->config($tc.'email_pdf_note');
2132 $html = join('<BR>', @text);
2134 } # else use the plain text invoice
2139 if ( $conf->config($tc.'template') ) {
2141 warn "$me generating plain text invoice"
2144 # 'print_text' argument is no longer used
2145 @text = $self->print_text(\%args);
2149 warn "$me no plain text version exists; sending empty message body"
2156 my $text_part = build MIME::Entity (
2157 'Type' => 'text/plain',
2158 'Encoding' => 'quoted-printable',
2159 'Charset' => 'UTF-8',
2160 #'Encoding' => '7bit',
2162 'Disposition' => 'inline',
2167 if ( $conf->exists($tc.'html') ) {
2168 warn "$me generating HTML invoice"
2171 $args{'from'} =~ /\@([\w\.\-]+)/;
2172 my $from = $1 || 'example.com';
2173 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
2176 my $agentnum = $cust_main ? $cust_main->agentnum
2177 : $self->prospect_main->agentnum;
2178 if ( defined($args{'template'}) && length($args{'template'})
2179 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
2182 $logo = 'logo_'. $args{'template'}. '.png';
2186 my $image_data = $conf->config_binary( $logo, $agentnum);
2188 push @related_parts, build MIME::Entity
2189 'Type' => 'image/png',
2190 'Encoding' => 'base64',
2191 'Data' => $image_data,
2192 'Filename' => 'logo.png',
2193 'Content-ID' => "<$content_id>",
2196 if ( ref($self) eq 'FS::cust_bill' && $conf->exists('invoice-barcode') ) {
2197 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
2198 push @related_parts, build MIME::Entity
2199 'Type' => 'image/png',
2200 'Encoding' => 'base64',
2201 'Data' => $self->invoice_barcode(0),
2202 'Filename' => 'barcode.png',
2203 'Content-ID' => "<$barcode_content_id>",
2205 $args{'barcode_cid'} = $barcode_content_id;
2208 $html = $self->print_html({ 'cid'=>$content_id, %args });
2215 warn "$me creating HTML/text multipart message"
2218 $return{'nobody'} = 1;
2220 my $alternative = build MIME::Entity
2221 'Type' => 'multipart/alternative',
2222 #'Encoding' => '7bit',
2223 'Disposition' => 'inline'
2227 $alternative->add_part($text_part);
2230 $alternative->attach(
2231 'Type' => 'text/html',
2232 'Encoding' => 'quoted-printable',
2233 'Data' => [ '<html>',
2236 ' '. encode_entities($return{'subject'}),
2239 ' <body bgcolor="#e8e8e8">',
2244 'Disposition' => 'inline',
2245 #'Filename' => 'invoice.pdf',
2248 unshift @related_parts, $alternative;
2250 $related = build MIME::Entity 'Type' => 'multipart/related',
2251 'Encoding' => '7bit';
2253 #false laziness w/Misc::send_email
2254 $related->head->replace('Content-type',
2255 $related->mime_type.
2256 '; boundary="'. $related->head->multipart_boundary. '"'.
2257 '; type=multipart/alternative'
2260 $related->add_part($_) foreach @related_parts;
2264 my @otherparts = ();
2265 if ( ref($self) eq 'FS::cust_bill' && $cust_main->email_csv_cdr ) {
2267 if ( $conf->config('voip-cdr_email_attach') eq 'zip' ) {
2269 my $data = join('', map "$_\n",
2270 $self->call_details(prepend_billed_number=>1)
2273 my $zip = new Archive::Zip;
2274 my $file = $zip->addString( $data, 'usage-'.$self->invnum.'.csv' );
2275 $file->desiredCompressionMethod( COMPRESSION_DEFLATED );
2278 my $SH = IO::Scalar->new(\$zipdata);
2279 my $status = $zip->writeToFileHandle($SH);
2280 die "Error zipping CDR attachment: $!" unless $status == AZ_OK;
2282 push @otherparts, build MIME::Entity
2283 'Type' => 'application/zip',
2284 'Encoding' => 'base64',
2286 'Disposition' => 'attachment',
2287 'Filename' => 'usage-'. $self->invnum. '.zip',
2290 } else { # } elsif ( $conf->config('voip-cdr_email_attach') eq 'csv' ) {
2292 push @otherparts, build MIME::Entity
2293 'Type' => 'text/csv',
2294 'Encoding' => '7bit',
2295 'Data' => [ map { "$_\n" }
2296 $self->call_details('prepend_billed_number' => 1)
2298 'Disposition' => 'attachment',
2299 'Filename' => 'usage-'. $self->invnum. '.csv',
2306 if ( $conf->exists($tc.'email_pdf') ) {
2311 # multipart/alternative
2317 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
2318 push @otherparts, $pdf;
2322 $return{'content-type'} = 'multipart/mixed'; # of the outer container
2324 $return{'mimeparts'} = [ $related, @otherparts ];
2325 $return{'type'} = 'multipart/related'; # of the first part
2327 $return{'mimeparts'} = [ $text_part, @otherparts ];
2328 $return{'type'} = 'text/plain';
2330 } elsif ( $html ) { # no PDF or CSV, strip the outer container
2331 $return{'mimeparts'} = \@related_parts;
2332 $return{'content-type'} = 'multipart/related';
2333 $return{'type'} = 'multipart/alternative';
2334 } else { # no HTML either
2335 $return{'body'} = \@text;
2336 $return{'content-type'} = 'text/plain';
2345 Returns a list suitable for passing to MIME::Entity->build(), representing
2346 this invoice as PDF attachment.
2353 'Type' => 'application/pdf',
2354 'Encoding' => 'base64',
2355 'Data' => [ $self->print_pdf(@_) ],
2356 'Disposition' => 'attachment',
2357 'Filename' => 'invoice-'. $self->invnum. '.pdf',
2361 =item postal_mail_fsinc
2363 Sends this invoice to the Freeside Internet Services, Inc. print and mail
2370 use HTTP::Request::Common qw( POST );
2371 use Cpanel::JSON::XS;
2373 sub postal_mail_fsinc {
2374 my ( $self, %opt ) = @_;
2376 my $url = 'https://ws.freeside.biz/print';
2378 my $cust_main = $self->cust_main;
2379 my $agentnum = $cust_main->agentnum;
2380 my $bill_location = $cust_main->bill_location;
2382 die "Extra charges for international mailing; contact support\@freeside.biz to enable\n"
2383 if $bill_location->country ne 'US';
2385 my $conf = new FS::Conf;
2387 my @company_address = $conf->config('company_address', $agentnum);
2388 my ( $company_address1, $company_address2, $company_city, $company_state, $company_zip );
2389 if ( $company_address[2] =~ /^\s*(\S.*\S)\s*[\s,](\w\w),?\s*(\d{5}(-\d{4})?)\s*$/ ) {
2390 $company_address1 = $company_address[0];
2391 $company_address2 = $company_address[1];
2393 $company_state = $2;
2395 } elsif ( $company_address[1] =~ /^\s*(\S.*\S)\s*[\s,](\w\w),?\s*(\d{5}(-\d{4})?)\s*$/ ) {
2396 $company_address1 = $company_address[0];
2397 $company_address2 = '';
2399 $company_state = $2;
2402 die "Unparsable company_address; contact support\@freeside.biz\n";
2404 $company_city =~ s/,$//;
2406 my $file = $self->print_pdf(%opt, 'no_addresses' => 1);
2407 my $pages = CAM::PDF->new($file)->numPages;
2409 my $ua = LWP::UserAgent->new( 'ssl_opts' => { 'verify_hostname'=>0 });
2410 my $response = $ua->request( POST $url, [
2411 'support-key' => scalar($conf->config('support-key')),
2412 'file' => encode_base64($file),
2416 'company_name' => scalar( $conf->config('company_name', $agentnum) ),
2417 'company_address1' => $company_address1,
2418 'company_address2' => $company_address2,
2419 'company_city' => $company_city,
2420 'company_state' => $company_state,
2421 'company_zip' => $company_zip,
2422 'company_country' => 'US',
2423 'company_phonenum' => scalar($conf->config('company_phonenum', $agentnum)),
2424 'company_email' => scalar($conf->config('invoice_from', $agentnum)),
2427 'name' => $cust_main->invoice_attn
2428 || $cust_main->contact_firstlast,
2429 'company' => $cust_main->company,
2430 'address1' => $bill_location->address1,
2431 'address2' => $bill_location->address2,
2432 'city' => $bill_location->city,
2433 'state' => $bill_location->state,
2434 'zip' => $bill_location->zip,
2435 'country' => $bill_location->country,
2438 die "Print connection error: ". $response->message. "\n"
2439 unless $response->is_success;
2442 my $content = eval { decode_json($response->content) };
2443 die "Print JSON error : $@\n" if $@;
2445 die $content->{error}."\n"
2446 if $content->{error};
2448 #TODO: store this so we can query for a status later
2449 warn "Invoice printed, ID ". $content->{id}. "\n";
2455 =item _items_sections OPTIONS
2457 Generate section information for all items appearing on this invoice.
2458 This will only be called for multi-section invoices.
2460 For each line item (L<FS::cust_bill_pkg> record), this will fetch all
2461 related display records (L<FS::cust_bill_pkg_display>) and organize
2462 them into two groups ("early" and "late" according to whether they come
2463 before or after the total), then into sections. A subtotal is calculated
2466 Section descriptions are returned in sort weight order. Each consists
2467 of a hash containing:
2469 description: the package category name, escaped
2470 subtotal: the total charges in that section
2471 tax_section: a flag indicating that the section contains only tax charges
2472 summarized: same as tax_section, for some reason
2473 sort_weight: the package category's sort weight
2475 If 'condense' is set on the display record, it also contains everything
2476 returned from C<_condense_section()>, i.e. C<_condensed_foo_generator>
2477 coderefs to generate parts of the invoice. This is not advised.
2479 The method returns two arrayrefs, one of "early" sections and one of "late"
2482 OPTIONS may include:
2484 by_location: a flag to divide the invoice into sections by location.
2485 Each section hash will have a 'location' element containing a hashref of
2486 the location fields (see L<FS::cust_location>). The section description
2487 will be the location label, but the template can use any of the location
2488 fields to create a suitable label.
2490 by_category: a flag to divide the invoice into sections using display
2491 records (see L<FS::cust_bill_pkg_display>). This is the "traditional"
2492 behavior. Each section hash will have a 'category' element containing
2493 the section name from the display record (which probably equals the
2494 category name of the package, but may not in some cases).
2496 summary: a flag indicating that this is a summary-format invoice.
2497 Turning this on has the following effects:
2498 - Ignores display items with the 'summary' flag.
2499 - Places all sections in the "early" group even if they have post_total.
2500 - Creates sections for all non-disabled package categories, even if they
2501 have no charges on this invoice, as well as a section with no name.
2503 escape: an escape function to use for section titles.
2505 extra_sections: an arrayref of additional sections to return after the
2506 sorted list. If there are any of these, section subtotals exclude
2509 format: 'latex', 'html', or 'template' (i.e. text). Not used, but
2510 passed through to C<_condense_section()>.
2514 use vars qw(%pkg_category_cache);
2515 sub _items_sections {
2519 my $escape = $opt{escape};
2520 my @extra_sections = @{ $opt{extra_sections} || [] };
2522 # $subtotal{$locationnum}{$categoryname} = amount.
2523 # if we're not using by_location, $locationnum is undef.
2524 # if we're not using by_category, you guessed it, $categoryname is undef.
2525 # if we're not using either one, we shouldn't be here in the first place...
2527 my %late_subtotal = ();
2530 # About tax items + multisection invoices:
2531 # If either invoice_*summary option is enabled, AND there is a
2532 # package category with the name of the tax, then there will be
2533 # a display record assigning the tax item to that category.
2535 # However, the taxes are always placed in the "Taxes, Surcharges,
2536 # and Fees" section regardless of that. The only effect of the
2537 # display record is to create a subtotal for the summary page.
2540 my $pkg_hash = $self->cust_pkg_hash;
2542 foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2545 my $usage = $cust_bill_pkg->usage;
2548 if ( $opt{by_location} ) {
2549 if ( $cust_bill_pkg->pkgnum ) {
2550 $locationnum = $pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum;
2555 $locationnum = undef;
2558 # as in _items_cust_pkg, if a line item has no display records,
2559 # cust_bill_pkg_display() returns a default record for it
2561 foreach my $display ($cust_bill_pkg->cust_bill_pkg_display) {
2562 next if ( $display->summary && $opt{summary} );
2564 my $section = $display->section;
2565 my $type = $display->type;
2566 # Set $section = undef if we're sectioning by location and this
2567 # line item _has_ a location (i.e. isn't a fee).
2568 $section = undef if $locationnum;
2570 # set this flag if the section is not tax-only
2571 $not_tax{$locationnum}{$section} = 1
2572 if $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart;
2574 # there's actually a very important piece of logic buried in here:
2575 # incrementing $late_subtotal{$section} CREATES
2576 # $late_subtotal{$section}. keys(%late_subtotal) is later used
2577 # to define the list of late sections, and likewise keys(%subtotal).
2578 # When _items_cust_bill_pkg is called to generate line items for
2579 # real, it will be called with 'section' => $section for each
2581 if ( $display->post_total && !$opt{summary} ) {
2582 if (! $type || $type eq 'S') {
2583 $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2584 if $cust_bill_pkg->setup != 0
2585 || $cust_bill_pkg->setup_show_zero;
2589 $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur
2590 if $cust_bill_pkg->recur != 0
2591 || $cust_bill_pkg->recur_show_zero;
2594 if ($type && $type eq 'R') {
2595 $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2596 if $cust_bill_pkg->recur != 0
2597 || $cust_bill_pkg->recur_show_zero;
2600 if ($type && $type eq 'U') {
2601 $late_subtotal{$locationnum}{$section} += $usage
2602 unless scalar(@extra_sections);
2605 } else { # it's a pre-total (normal) section
2607 # skip tax items unless they're explicitly included in a section
2608 next if $cust_bill_pkg->pkgnum == 0 and
2609 ! $cust_bill_pkg->feepart and
2612 if ( $type eq 'S' ) {
2613 $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2614 if $cust_bill_pkg->setup != 0
2615 || $cust_bill_pkg->setup_show_zero;
2616 } elsif ( $type eq 'R' ) {
2617 $subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2618 if $cust_bill_pkg->recur != 0
2619 || $cust_bill_pkg->recur_show_zero;
2620 } elsif ( $type eq 'U' ) {
2621 $subtotal{$locationnum}{$section} += $usage
2622 unless scalar(@extra_sections);
2623 } elsif ( !$type ) {
2624 $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2625 + $cust_bill_pkg->recur;
2634 %pkg_category_cache = ();
2636 # summary invoices need subtotals for all non-disabled package categories,
2637 # even if they're zero
2638 # but currently assume that there are no location sections, or at least
2639 # that the summary page doesn't care about them
2640 if ( $opt{summary} ) {
2641 foreach my $category (qsearch('pkg_category', {disabled => ''})) {
2642 $subtotal{''}{$category->categoryname} ||= 0;
2644 $subtotal{''}{''} ||= 0;
2648 foreach my $post_total (0,1) {
2650 my $s = $post_total ? \%late_subtotal : \%subtotal;
2651 foreach my $locationnum (keys %$s) {
2652 foreach my $sectionname (keys %{ $s->{$locationnum} }) {
2654 'subtotal' => $s->{$locationnum}{$sectionname},
2657 if ( $locationnum ) {
2658 $section->{'locationnum'} = $locationnum;
2659 my $location = FS::cust_location->by_key($locationnum);
2660 $section->{'description'} = &{ $escape }($location->location_label);
2661 # Better ideas? This will roughly group them by proximity,
2662 # which alpha sorting on any of the address fields won't.
2663 # Sorting by locationnum is meaningless.
2664 # We have to sort on _something_ or the order may change
2665 # randomly from one invoice to the next, which will confuse
2667 $section->{'sort_weight'} = sprintf('%012s',$location->zip) .
2669 $section->{'location'} = {
2670 label_prefix => &{ $escape }($location->label_prefix),
2671 map { $_ => &{ $escape }($location->get($_)) }
2675 $section->{'category'} = $sectionname;
2676 $section->{'description'} = &{ $escape }($sectionname);
2677 if ( _pkg_category($sectionname) ) {
2678 $section->{'sort_weight'} = _pkg_category($sectionname)->weight;
2679 if ( _pkg_category($sectionname)->condense ) {
2680 $section = { %$section, $self->_condense_section($opt{format}) };
2684 if ( !$post_total and !$not_tax{$locationnum}{$sectionname} ) {
2685 # then it's a tax-only section
2686 $section->{'summarized'} = 'Y';
2687 $section->{'tax_section'} = 'Y';
2689 push @these, $section;
2690 } # foreach $sectionname
2691 } #foreach $locationnum
2692 push @these, @extra_sections if $post_total == 0;
2693 # need an alpha sort for location sections, because postal codes can
2695 $sections[ $post_total ] = [ sort {
2696 $opt{'by_location'} ?
2697 ($a->{sort_weight} cmp $b->{sort_weight}) :
2698 ($a->{sort_weight} <=> $b->{sort_weight})
2700 } #foreach $post_total
2702 return @sections; # early, late
2705 #helper subs for above
2709 $self->{cust_pkg} ||= { map { $_->pkgnum => $_ } $self->cust_pkg };
2713 my $categoryname = shift;
2714 $pkg_category_cache{$categoryname} ||=
2715 qsearchs( 'pkg_category', { 'categoryname' => $categoryname } );
2718 my %condensed_format = (
2719 'label' => [ qw( Description Qty Amount ) ],
2721 sub { shift->{description} },
2722 sub { shift->{quantity} },
2723 sub { my($href, %opt) = @_;
2724 ($opt{dollar} || ''). $href->{amount};
2727 'align' => [ qw( l r r ) ],
2728 'span' => [ qw( 5 1 1 ) ], # unitprices?
2729 'width' => [ qw( 10.7cm 1.4cm 1.6cm ) ], # don't like this
2732 sub _condense_section {
2733 my ( $self, $format ) = ( shift, shift );
2735 map { my $method = "_condensed_$_"; $_ => $self->$method($format) }
2736 qw( description_generator
2739 total_line_generator
2744 sub _condensed_generator_defaults {
2745 my ( $self, $format ) = ( shift, shift );
2746 return ( \%condensed_format, ' ', ' ', ' ', sub { shift } );
2755 sub _condensed_header_generator {
2756 my ( $self, $format ) = ( shift, shift );
2758 my ( $f, $prefix, $suffix, $separator, $column ) =
2759 _condensed_generator_defaults($format);
2761 if ($format eq 'latex') {
2762 $prefix = "\\hline\n\\rule{0pt}{2.5ex}\n\\makebox[1.4cm]{}&\n";
2763 $suffix = "\\\\\n\\hline";
2766 sub { my ($d,$a,$s,$w) = @_;
2767 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2769 } elsif ( $format eq 'html' ) {
2770 $prefix = '<th></th>';
2774 sub { my ($d,$a,$s,$w) = @_;
2775 return qq!<th align="$html_align{$a}">$d</th>!;
2783 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
2785 &{$column}( map { $f->{$_}->[$i] } qw(label align span width) );
2788 $prefix. join($separator, @result). $suffix;
2793 sub _condensed_description_generator {
2794 my ( $self, $format ) = ( shift, shift );
2796 my ( $f, $prefix, $suffix, $separator, $column ) =
2797 _condensed_generator_defaults($format);
2799 my $money_char = '$';
2800 if ($format eq 'latex') {
2801 $prefix = "\\hline\n\\multicolumn{1}{c}{\\rule{0pt}{2.5ex}~} &\n";
2803 $separator = " & \n";
2805 sub { my ($d,$a,$s,$w) = @_;
2806 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2808 $money_char = '\\dollar';
2809 }elsif ( $format eq 'html' ) {
2810 $prefix = '"><td align="center"></td>';
2814 sub { my ($d,$a,$s,$w) = @_;
2815 return qq!<td align="$html_align{$a}">$d</td>!;
2817 #$money_char = $conf->config('money_char') || '$';
2818 $money_char = ''; # this is madness
2826 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
2828 $dollar = $money_char if $i == scalar(@{$f->{label}})-1;
2830 &{$column}( &{$f->{fields}->[$i]}($href, 'dollar' => $dollar),
2831 map { $f->{$_}->[$i] } qw(align span width)
2835 $prefix. join( $separator, @result ). $suffix;
2840 sub _condensed_total_generator {
2841 my ( $self, $format ) = ( shift, shift );
2843 my ( $f, $prefix, $suffix, $separator, $column ) =
2844 _condensed_generator_defaults($format);
2847 if ($format eq 'latex') {
2850 $separator = " & \n";
2852 sub { my ($d,$a,$s,$w) = @_;
2853 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
2855 }elsif ( $format eq 'html' ) {
2859 $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
2861 sub { my ($d,$a,$s,$w) = @_;
2862 return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
2871 # my $r = &{$f->{fields}->[$i]}(@args);
2872 # $r .= ' Total' unless $i;
2874 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
2876 &{$column}( &{$f->{fields}->[$i]}(@args). ($i ? '' : ' Total'),
2877 map { $f->{$_}->[$i] } qw(align span width)
2881 $prefix. join( $separator, @result ). $suffix;
2886 =item total_line_generator FORMAT
2888 Returns a coderef used for generation of invoice total line items for this
2889 usage_class. FORMAT is either html or latex
2893 # should not be used: will have issues with hash element names (description vs
2894 # total_item and amount vs total_amount -- another array of functions?
2896 sub _condensed_total_line_generator {
2897 my ( $self, $format ) = ( shift, shift );
2899 my ( $f, $prefix, $suffix, $separator, $column ) =
2900 _condensed_generator_defaults($format);
2903 if ($format eq 'latex') {
2906 $separator = " & \n";
2908 sub { my ($d,$a,$s,$w) = @_;
2909 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
2911 }elsif ( $format eq 'html' ) {
2915 $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
2917 sub { my ($d,$a,$s,$w) = @_;
2918 return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
2927 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
2929 &{$column}( &{$f->{fields}->[$i]}(@args),
2930 map { $f->{$_}->[$i] } qw(align span width)
2934 $prefix. join( $separator, @result ). $suffix;
2939 =item _items_pkg [ OPTIONS ]
2941 Return line item hashes for each package item on this invoice. Nearly
2944 $self->_items_cust_bill_pkg([ $self->cust_bill_pkg ])
2946 OPTIONS are passed through to _items_cust_bill_pkg, and should include
2947 'format' and 'escape_function' at minimum.
2949 To produce items for a specific invoice section, OPTIONS should include
2950 'section', a hashref containing 'category' and/or 'locationnum' keys.
2952 'section' may also contain a key named 'condensed'. If this is present
2953 and has a true value, _items_pkg will try to merge identical items into items
2954 with 'quantity' equal to the number of items (not the sum of their separate
2955 quantities, for some reason).
2961 # The order of these is important. Bundled line items will be merged into
2962 # the most recent non-hidden item, so it needs to be the one with:
2964 # - the same start date
2965 # - no pkgpart_override
2967 # So: sort by pkgnum,
2969 # then sort the base line item before any overrides
2970 # then sort hidden before non-hidden add-ons
2971 # then sort by override pkgpart (for consistency)
2972 sort { $a->pkgnum <=> $b->pkgnum or
2973 $a->sdate <=> $b->sdate or
2974 ($a->pkgpart_override ? 0 : -1) or
2975 ($b->pkgpart_override ? 0 : 1) or
2976 $b->hidden cmp $a->hidden or
2977 $a->pkgpart_override <=> $b->pkgpart_override
2979 # and of course exclude taxes and fees
2980 grep { $_->pkgnum > 0 } $self->cust_bill_pkg;
2986 my @cust_bill_pkg = grep { $_->feepart } $self->cust_bill_pkg;
2987 my $escape_function = $options{escape_function};
2990 foreach my $cust_bill_pkg (@cust_bill_pkg) {
2991 # cache this, so we don't look it up again in every section
2992 my $part_fee = $cust_bill_pkg->get('part_fee')
2993 || $cust_bill_pkg->part_fee;
2994 $cust_bill_pkg->set('part_fee', $part_fee);
2996 #die "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n"; # might make more sense
2997 warn "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n";
3000 if ( exists($options{section}) and exists($options{section}{category}) )
3002 my $categoryname = $options{section}{category};
3003 # then filter for items that have that section
3004 if ( $part_fee->categoryname ne $categoryname ) {
3005 warn "skipping fee '".$part_fee->itemdesc."'--not in section $categoryname\n" if $DEBUG;
3008 } # otherwise include them all in the main section
3009 # XXX what to do when sectioning by location?
3012 my %base_invnums; # invnum => invoice date
3013 foreach ($cust_bill_pkg->cust_bill_pkg_fee) {
3014 if ($_->base_invnum) {
3015 my $base_bill = FS::cust_bill->by_key($_->base_invnum);
3016 my $base_date = $self->time2str_local('short', $base_bill->_date)
3018 $base_invnums{$_->base_invnum} = $base_date || '';
3021 foreach (sort keys(%base_invnums)) {
3022 next if $_ == $self->invnum;
3023 # per convention, we must escape ext_description lines
3025 &{$escape_function}(
3026 $self->mt('from invoice #[_1] on [_2]', $_, $base_invnums{$_})
3029 my $desc = $part_fee->itemdesc_locale($self->cust_main->locale);
3030 # but not escape the base description line
3033 { feepart => $cust_bill_pkg->feepart,
3034 amount => sprintf('%.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
3035 description => $desc,
3036 ext_description => \@ext_desc
3047 warn "$me _items_pkg searching for all package line items\n"
3050 my @cust_bill_pkg = $self->_items_nontax;
3052 warn "$me _items_pkg filtering line items\n"
3054 my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3056 if ($options{section} && $options{section}->{condensed}) {
3058 warn "$me _items_pkg condensing section\n"
3062 local $Storable::canonical = 1;
3063 foreach ( @items ) {
3065 delete $item->{ref};
3066 delete $item->{ext_description};
3067 my $key = freeze($item);
3068 $itemshash{$key} ||= 0;
3069 $itemshash{$key} ++; # += $item->{quantity};
3071 @items = sort { $a->{description} cmp $b->{description} }
3072 map { my $i = thaw($_);
3073 $i->{quantity} = $itemshash{$_};
3075 sprintf( "%.2f", $i->{quantity} * $i->{amount} );#unit_amount
3081 warn "$me _items_pkg returning ". scalar(@items). " items\n"
3088 return 0 unless $a->itemdesc cmp $b->itemdesc;
3089 return -1 if $b->itemdesc eq 'Tax';
3090 return 1 if $a->itemdesc eq 'Tax';
3091 return -1 if $b->itemdesc eq 'Other surcharges';
3092 return 1 if $a->itemdesc eq 'Other surcharges';
3093 $a->itemdesc cmp $b->itemdesc;
3098 my @cust_bill_pkg = sort _taxsort grep { ! $_->pkgnum and ! $_->feepart }
3099 $self->cust_bill_pkg;
3100 my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3102 if ( $self->conf->exists('always_show_tax') ) {
3103 my $itemdesc = $self->conf->config('always_show_tax') || 'Tax';
3104 if (0 == grep { $_->{description} eq $itemdesc } @items) {
3106 { 'description' => $itemdesc,
3113 =item _items_cust_bill_pkg CUST_BILL_PKGS OPTIONS
3115 Takes an arrayref of L<FS::cust_bill_pkg> objects, and returns a
3116 list of hashrefs describing the line items they generate on the invoice.
3118 OPTIONS may include:
3120 format: the invoice format.
3122 escape_function: the function used to escape strings.
3124 DEPRECATED? (expensive, mostly unused?)
3125 format_function: the function used to format CDRs.
3127 section: a hashref containing 'category' and/or 'locationnum'; if this
3128 is present, only returns line items that belong to that category and/or
3129 location (whichever is defined).
3131 multisection: a flag indicating that this is a multisection invoice,
3132 which does something complicated.
3134 Returns a list of hashrefs, each of which may contain:
3136 pkgnum, description, amount, unit_amount, quantity, pkgpart, _is_setup, and
3137 ext_description, which is an arrayref of detail lines to show below
3142 sub _items_cust_bill_pkg {
3144 my $conf = $self->conf;
3145 my $cust_bill_pkgs = shift;
3148 my $format = $opt{format} || '';
3149 my $escape_function = $opt{escape_function} || sub { shift };
3150 my $format_function = $opt{format_function} || '';
3151 my $no_usage = $opt{no_usage} || '';
3152 my $unsquelched = $opt{unsquelched} || ''; #unused
3153 my ($section, $locationnum, $category);
3154 if ( $opt{section} ) {
3155 $category = $opt{section}->{category};
3156 $locationnum = $opt{section}->{locationnum};
3158 my $summary_page = $opt{summary_page} || ''; #unused
3159 my $multisection = defined($category) || defined($locationnum);
3160 # this variable is the value of the config setting, not whether it applies
3161 # to this particular line item.
3162 my $discount_show_always = $conf->exists('discount-show-always');
3164 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
3166 my $cust_main = $self->cust_main;#for per-agent cust_bill-line_item-ate_style
3168 # for location labels: use default location on the invoice date
3169 my $default_locationnum;
3170 if ( $self->custnum ) {
3172 my @h_search = FS::h_cust_main->sql_h_search($self->_date);
3173 $h_cust_main = qsearchs({
3174 'table' => 'h_cust_main',
3175 'hashref' => { custnum => $self->custnum },
3176 'extra_sql' => $h_search[1],
3177 'addl_from' => $h_search[3],
3179 $default_locationnum = $h_cust_main->ship_locationnum;
3180 } elsif ( $self->prospectnum ) {
3181 my $cust_location = qsearchs('cust_location',
3182 { prospectnum => $self->prospectnum,
3184 $default_locationnum = $cust_location->locationnum if $cust_location;
3187 my @b = (); # accumulator for the line item hashes that we'll return
3188 my ($s, $r, $u, $d) = ( undef, undef, undef, undef );
3189 # the 'current' line item hashes for setup, recur, usage, discount
3190 foreach my $cust_bill_pkg ( @$cust_bill_pkgs )
3192 # if the current line item is waiting to go out, and the one we're about
3193 # to start is not bundled, then push out the current one and start a new
3196 $d->{amount} = $d->{setup_amount} + $d->{recur_amount};
3198 foreach ( $s, $r, ($opt{skip_usage} ? () : $u ), $d ) {
3199 if ( $_ && !$cust_bill_pkg->hidden ) {
3200 $_->{amount} = sprintf( "%.2f", $_->{amount} );
3201 $_->{amount} =~ s/^\-0\.00$/0.00/;
3202 if (exists($_->{unit_amount})) {
3203 $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} );
3206 # we already decided to create this display line; don't reconsider it
3208 # if $_->{amount} != 0
3209 # || $discount_show_always
3210 # || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
3211 # || ( $_->{_is_setup} && $_->{setup_show_zero} )
3217 if ( $locationnum ) {
3218 # this is a location section; skip packages that aren't at this
3220 next if $cust_bill_pkg->pkgnum == 0; # skips fees...
3221 next if $self->cust_pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum
3225 # Consider display records for this item to determine if it belongs
3226 # in this section. Note that if there are no display records, there
3227 # will be a default pseudo-record that includes all charge types
3228 # and has no section name.
3229 my @cust_bill_pkg_display = $cust_bill_pkg->can('cust_bill_pkg_display')
3230 ? $cust_bill_pkg->cust_bill_pkg_display
3231 : ( $cust_bill_pkg );
3233 warn "$me _items_cust_bill_pkg considering cust_bill_pkg ".
3234 $cust_bill_pkg->billpkgnum. ", pkgnum ". $cust_bill_pkg->pkgnum. "\n"
3237 if ( defined($category) ) {
3238 # then this is a package category section; process all display records
3239 # that belong to this section.
3240 @cust_bill_pkg_display = grep { $_->section eq $category }
3241 @cust_bill_pkg_display;
3243 # otherwise, process all display records that aren't usage summaries
3244 # (I don't think there should be usage summaries if you aren't using
3245 # category sections, but this is the historical behavior)
3246 @cust_bill_pkg_display = grep { !$_->summary }
3247 @cust_bill_pkg_display;
3250 my $classname = ''; # package class name, will fill in later
3252 foreach my $display (@cust_bill_pkg_display) {
3254 warn "$me _items_cust_bill_pkg considering cust_bill_pkg_display ".
3255 $display->billpkgdisplaynum. "\n"
3258 my $type = $display->type;
3260 my $desc = $cust_bill_pkg->desc( $cust_main ? $cust_main->locale : '' );
3261 $desc = substr($desc, 0, $maxlength). '...'
3262 if $format eq 'latex' && length($desc) > $maxlength;
3264 my %details_opt = ( 'format' => $format,
3265 'escape_function' => $escape_function,
3266 'format_function' => $format_function,
3267 'no_usage' => $opt{'no_usage'},
3270 if ( $cust_bill_pkg->pkgnum > 0 ) {
3271 # a "normal" package line item (not a quotation, not a fee, not a tax)
3273 warn "$me _items_cust_bill_pkg cust_bill_pkg is non-tax\n"
3276 my $cust_pkg = $cust_bill_pkg->cust_pkg;
3277 my $part_pkg = $cust_pkg->part_pkg;
3279 # which pkgpart to show for display purposes?
3280 my $pkgpart = $cust_bill_pkg->pkgpart_override || $cust_pkg->pkgpart;
3282 # start/end dates for invoice formats that do nonstandard
3284 my %item_dates = ();
3285 %item_dates = map { $_ => $cust_bill_pkg->$_ } ('sdate', 'edate')
3286 unless $part_pkg->option('disable_line_item_date_ranges',1);
3288 # not normally used, but pass this to the template anyway
3289 $classname = $part_pkg->classname;
3291 if ( (!$type || $type eq 'S')
3292 && ( $cust_bill_pkg->setup != 0
3293 || $cust_bill_pkg->setup_show_zero
3294 || ($discount_show_always and $cust_bill_pkg->unitsetup > 0)
3299 warn "$me _items_cust_bill_pkg adding setup\n"
3302 # append the word 'Setup' to the setup line if there's going to be
3303 # a recur line for the same package (i.e. not a one-time charge)
3304 my $description = $desc;
3305 $description .= ' Setup'
3306 if $cust_bill_pkg->recur != 0
3307 || ($discount_show_always and $cust_bill_pkg->unitrecur > 0)
3308 || $cust_bill_pkg->recur_show_zero;
3310 $description .= $cust_bill_pkg->time_period_pretty( $part_pkg,
3312 if $part_pkg->is_prepaid #for prepaid, "display the validity period
3313 # triggered by the recurring charge freq
3315 && $cust_bill_pkg->recur == 0
3316 && ! $cust_bill_pkg->recur_show_zero;
3321 # always pass the svc_label through to the template, even if
3322 # not displaying it as an ext_description
3323 my @svc_labels = map &{$escape_function}($_),
3324 $cust_pkg->h_labels_short($self->_date, undef, 'I');
3326 $svc_label = $svc_labels[0];
3328 unless ( $cust_pkg->part_pkg->hide_svc_detail
3329 || $cust_bill_pkg->hidden )
3332 push @d, @svc_labels
3333 unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
3334 # show the location label if it's not the customer's default
3335 # location, and we're not grouping items by location already
3336 if ( $cust_pkg->locationnum != $default_locationnum
3337 and !defined($locationnum) ) {
3338 my $loc = $cust_pkg->location_label;
3339 $loc = substr($loc, 0, $maxlength). '...'
3340 if $format eq 'latex' && length($loc) > $maxlength;
3341 push @d, &{$escape_function}($loc);
3344 } #unless hiding service details
3346 push @d, $cust_bill_pkg->details(%details_opt)
3347 if $cust_bill_pkg->recur == 0;
3349 if ( $cust_bill_pkg->hidden ) {
3350 $s->{amount} += $cust_bill_pkg->setup;
3351 $s->{unit_amount} += $cust_bill_pkg->unitsetup;
3352 push @{ $s->{ext_description} }, @d;
3356 description => $description,
3357 pkgpart => $pkgpart,
3358 pkgnum => $cust_bill_pkg->pkgnum,
3359 amount => $cust_bill_pkg->setup,
3360 setup_show_zero => $cust_bill_pkg->setup_show_zero,
3361 unit_amount => $cust_bill_pkg->unitsetup,
3362 quantity => $cust_bill_pkg->quantity,
3363 ext_description => \@d,
3364 svc_label => ($svc_label || ''),
3365 locationnum => $cust_pkg->locationnum, # sure, why not?
3371 # should we show a recur line?
3372 # if type eq 'S', then NO, because we've been told not to.
3373 # otherwise, show the recur line if:
3374 # - there's a recurring charge
3375 # - or recur_show_zero is on
3376 # - or there's a positive unitrecur (so it's been discounted to zero)
3377 # and discount-show-always is on
3378 if ( ( !$type || $type eq 'R' || $type eq 'U' )
3380 $cust_bill_pkg->recur != 0
3382 || ($discount_show_always and $cust_bill_pkg->unitrecur > 0)
3383 || $cust_bill_pkg->recur_show_zero
3388 warn "$me _items_cust_bill_pkg adding recur/usage\n"
3391 my $is_summary = $display->summary;
3392 my $description = $desc;
3393 if ( $type eq 'U' and defined($r) ) {
3394 # don't just show the same description as the recur line
3395 $description = $self->mt('Usage charges');
3398 my $part_pkg = $cust_pkg->part_pkg;
3400 $description .= $cust_bill_pkg->time_period_pretty( $part_pkg,
3404 my @seconds = (); # for display of usage info
3407 #at least until cust_bill_pkg has "past" ranges in addition to
3408 #the "future" sdate/edate ones... see #3032
3409 my @dates = ( $self->_date );
3410 my $prev = $cust_bill_pkg->previous_cust_bill_pkg;
3411 push @dates, $prev->sdate if $prev;
3412 push @dates, undef if !$prev;
3414 my @svc_labels = map &{$escape_function}($_),
3415 $cust_pkg->h_labels_short(@dates, 'I');
3416 $svc_label = $svc_labels[0];
3418 # show service labels, unless...
3419 # the package is set not to display them
3420 unless ( $part_pkg->hide_svc_detail
3421 # or this is a tax-like line item
3422 || $cust_bill_pkg->itemdesc
3423 # or this is a hidden (bundled) line item
3424 || $cust_bill_pkg->hidden
3425 # or this is a usage summary line
3426 || $is_summary && $type && $type eq 'U'
3427 # or this is a usage line and there's a recurring line
3428 # for the package in the same section (which will
3429 # have service labels already)
3430 || ($type eq 'U' and defined($r))
3434 warn "$me _items_cust_bill_pkg adding service details\n"
3437 push @d, @svc_labels
3438 unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
3439 warn "$me _items_cust_bill_pkg done adding service details\n"
3442 # show the location label if it's not the customer's default
3443 # location, and we're not grouping items by location already
3444 if ( $cust_pkg->locationnum != $default_locationnum
3445 and !defined($locationnum) ) {
3446 my $loc = $cust_pkg->location_label;
3447 $loc = substr($loc, 0, $maxlength). '...'
3448 if $format eq 'latex' && length($loc) > $maxlength;
3449 push @d, &{$escape_function}($loc);
3452 # Display of seconds_since_sqlradacct:
3453 # On the invoice, when processing @detail_items, look for a field
3454 # named 'seconds'. This will contain total seconds for each
3455 # service, in the same order as @ext_description. For services
3456 # that don't support this it will show undef.
3457 if ( $conf->exists('svc_acct-usage_seconds')
3458 and ! $cust_bill_pkg->pkgpart_override ) {
3459 foreach my $cust_svc (
3460 $cust_pkg->h_cust_svc(@dates, 'I')
3463 # eval because not having any part_export_usage exports
3464 # is a fatal error, last_bill/_date because that's how
3465 # sqlradius_hour billing does it
3467 $cust_svc->seconds_since_sqlradacct($dates[1] || 0, $dates[0]);
3469 push @seconds, $sec;
3471 } #if svc_acct-usage_seconds
3473 } # if we are showing service labels
3475 unless ( $is_summary ) {
3476 warn "$me _items_cust_bill_pkg adding details\n"
3479 #instead of omitting details entirely in this case (unwanted side
3480 # effects), just omit CDRs
3481 $details_opt{'no_usage'} = 1
3482 if $type && $type eq 'R';
3484 push @d, $cust_bill_pkg->details(%details_opt);
3487 warn "$me _items_cust_bill_pkg calculating amount\n"
3492 $amount = $cust_bill_pkg->recur;
3493 } elsif ($type eq 'R') {
3494 $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
3495 } elsif ($type eq 'U') {
3496 $amount = $cust_bill_pkg->usage;
3499 if ( !$type || $type eq 'R' ) {
3501 warn "$me _items_cust_bill_pkg adding recur\n"
3505 ( $cust_bill_pkg->unitrecur > 0 ) ? $cust_bill_pkg->unitrecur
3508 if ( $cust_bill_pkg->hidden ) {
3509 $r->{amount} += $amount;
3510 $r->{unit_amount} += $unit_amount;
3511 push @{ $r->{ext_description} }, @d;
3514 description => $description,
3515 pkgpart => $pkgpart,
3516 pkgnum => $cust_bill_pkg->pkgnum,
3518 recur_show_zero => $cust_bill_pkg->recur_show_zero,
3519 unit_amount => $unit_amount,
3520 quantity => $cust_bill_pkg->quantity,
3522 ext_description => \@d,
3523 svc_label => ($svc_label || ''),
3524 locationnum => $cust_pkg->locationnum,
3526 $r->{'seconds'} = \@seconds if grep {defined $_} @seconds;
3529 } else { # $type eq 'U'
3531 warn "$me _items_cust_bill_pkg adding usage\n"
3534 if ( $cust_bill_pkg->hidden and defined($u) ) {
3535 # if this is a hidden package and there's already a usage
3536 # line for the bundle, add this package's total amount and
3537 # usage details to it
3538 $u->{amount} += $amount;
3539 push @{ $u->{ext_description} }, @d;
3540 } elsif ( $amount ) {
3541 # create a new usage line
3543 description => $description,
3544 pkgpart => $pkgpart,
3545 pkgnum => $cust_bill_pkg->pkgnum,
3548 recur_show_zero => $cust_bill_pkg->recur_show_zero,
3550 ext_description => \@d,
3551 locationnum => $cust_pkg->locationnum,
3553 } # else this has no usage, so don't create a usage section
3556 } # recurring or usage with recurring charge
3558 } else { # taxes and fees
3560 warn "$me _items_cust_bill_pkg cust_bill_pkg is tax\n"
3563 # items of this kind should normally not have sdate/edate.
3565 'description' => $desc,
3566 'amount' => sprintf('%.2f', $cust_bill_pkg->setup
3567 + $cust_bill_pkg->recur)
3570 } # if package line item / other line item
3572 # decide whether to show active discounts here
3574 # case 1: we are showing a single line for the package
3576 # case 2: we are showing a setup line for a package that has
3577 # no base recurring fee
3578 or ( $type eq 'S' and $cust_bill_pkg->unitrecur == 0 )
3579 # case 3: we are showing a recur line for a package that has
3580 # a base recurring fee
3581 or ( $type eq 'R' and $cust_bill_pkg->unitrecur > 0 )
3584 my $item_discount = $cust_bill_pkg->_item_discount;
3585 if ( $item_discount ) {
3586 # $item_discount->{amount} is negative
3588 if ( $d and $cust_bill_pkg->hidden ) {
3589 $d->{setup_amount} += $item_discount->{setup_amount};
3590 $d->{recur_amount} += $item_discount->{recur_amount};
3592 $d = $item_discount;
3593 $_ = &{$escape_function}($_) foreach @{ $d->{ext_description} };
3596 # update the active line (before the discount) to show the
3597 # original price (whether this is a hidden line or not)
3599 $s->{amount} -= $item_discount->{setup_amount} if $s;
3600 $r->{amount} -= $item_discount->{recur_amount} if $r;
3602 } # if there are any discounts
3603 } # if this is an appropriate place to show discounts
3605 } # foreach $display
3609 # discount amount is internally split up
3611 $d->{amount} = $d->{setup_amount} + $d->{recur_amount};
3614 foreach ( $s, $r, ($opt{skip_usage} ? () : $u ), $d ) {
3616 $_->{amount} = sprintf( "%.2f", $_->{amount} ),
3617 if exists($_->{amount});
3618 $_->{amount} =~ s/^\-0\.00$/0.00/;
3619 if (exists($_->{unit_amount})) {
3620 $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} );
3624 #if $_->{amount} != 0
3625 # || $discount_show_always
3626 # || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
3627 # || ( $_->{_is_setup} && $_->{setup_show_zero} )
3631 warn "$me _items_cust_bill_pkg done considering cust_bill_pkgs\n"
3638 =item _items_discounts_avail
3640 Returns an array of line item hashrefs representing available term discounts
3641 for this invoice. This makes the same assumptions that apply to term
3642 discounts in general: that the package is billed monthly, at a flat rate,
3643 with no usage charges. A prorated first month will be handled, as will
3644 a setup fee if the discount is allowed to apply to setup fees.
3648 sub _items_discounts_avail {
3651 #maybe move this method from cust_bill when quotations support discount_plans
3652 return () unless $self->can('discount_plans');
3653 my %plans = $self->discount_plans;
3655 my $list_pkgnums = 0; # if any packages are not eligible for all discounts
3656 $list_pkgnums = grep { $_->list_pkgnums } values %plans;
3660 my $plan = $plans{$months};
3662 my $term_total = sprintf('%.2f', $plan->discounted_total);
3663 my $percent = sprintf('%.0f',
3664 100 * (1 - $term_total / $plan->base_total) );
3665 my $permonth = sprintf('%.2f', $term_total / $months);
3666 my $detail = $self->mt('discount on item'). ' '.
3667 join(', ', map { "#$_" } $plan->pkgnums)
3670 # discounts for non-integer months don't work anyway
3671 $months = sprintf("%d", $months);
3674 description => $self->mt('Save [_1]% by paying for [_2] months',
3676 amount => $self->mt('[_1] ([_2] per month)',
3677 $term_total, $money_char.$permonth),
3678 ext_description => ($detail || ''),
3681 sort { $b <=> $a } keys %plans;