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 Time::Local qw( timelocal );
14 use Text::Template 1.20;
16 use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
21 use FS::Misc qw( send_email );
22 use FS::Record qw( qsearch qsearchs dbh );
24 use FS::Misc qw( generate_ps generate_pdf );
32 $me = '[FS::Template_Mixin]';
33 FS::UID->install_callback( sub {
34 my $conf = new FS::Conf; #global
35 $money_char = $conf->config('money_char') || '$';
36 $date_format = $conf->config('date_format') || '%x'; #/YY
41 Returns a configuration handle (L<FS::Conf>) set to the customer's locale.
43 If the "mode" pseudo-field is set on the object, the configuration handle
44 will be an L<FS::invoice_conf> for that invoice mode (and the customer's
51 my $mode = $self->get('mode');
52 if ($self->{_conf} and !defined($mode)) {
53 return $self->{_conf};
56 my $cust_main = $self->cust_main;
57 my $locale = $cust_main ? $cust_main->locale : '';
60 if ( ref $mode and $mode->isa('FS::invoice_mode') ) {
61 $mode = $mode->modenum;
62 } elsif ( $mode =~ /\D/ ) {
63 die "invalid invoice mode $mode";
65 $conf = qsearchs('invoice_conf', { modenum => $mode, locale => $locale });
67 $conf = qsearchs('invoice_conf', { modenum => $mode, locale => '' });
68 # it doesn't have a locale, but system conf still might
69 $conf->set('locale' => $locale) if $conf;
72 # if $mode is unspecified, or if there is no invoice_conf matching this mode
73 # and locale, then use the system config only (but with the locale)
74 $conf ||= FS::Conf->new({ 'locale' => $locale });
76 return $self->{_conf} = $conf;
79 =item print_text OPTIONS
81 Returns an text invoice, as a list of lines.
83 Options can be passed as a hash.
85 I<time>, if specified, is used to control the printing of overdue messages. The
86 default is now. It isn't the date of the invoice; that's the `_date' field.
87 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
88 L<Time::Local> and L<Date::Parse> for conversion functions.
90 I<template>, if specified, is the name of a suffix for alternate invoices.
92 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
100 %params = %{ shift() };
105 $params{'format'} = 'template'; # for some reason
107 $self->print_generic( %params );
110 =item print_latex HASHREF
112 Internal method - returns a filename of a filled-in LaTeX template for this
113 invoice (Note: add ".tex" to get the actual filename), and a filename of
114 an associated logo (with the .eps extension included).
116 See print_ps and print_pdf for methods that return PostScript and PDF output.
118 Options can be passed as a hash.
120 I<time>, if specified, is used to control the printing of overdue messages. The
121 default is now. It isn't the date of the invoice; that's the `_date' field.
122 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
123 L<Time::Local> and L<Date::Parse> for conversion functions.
125 I<template>, if specified, is the name of a suffix for alternate invoices.
126 This is strongly deprecated; see L<FS::invoice_conf> for the right way to
127 customize invoice templates for different purposes.
129 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
138 %params = %{ shift() };
143 $params{'format'} = 'latex';
144 my $conf = $self->conf;
146 # this needs to go away
147 my $template = $params{'template'};
148 # and this especially
149 $template ||= $self->_agent_template
150 if $self->can('_agent_template');
153 $self->set('mode', $params{mode})
156 my $pkey = $self->primary_key;
157 my $tmp_template = $self->table. '.'. $self->$pkey. '.XXXXXXXX';
159 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
160 my $lh = new File::Temp(
161 TEMPLATE => $tmp_template,
165 ) or die "can't open temp file: $!\n";
167 my $agentnum = $self->agentnum;
169 if ( $template && $conf->exists("logo_${template}.eps", $agentnum) ) {
170 print $lh $conf->config_binary("logo_${template}.eps", $agentnum)
171 or die "can't write temp file: $!\n";
173 print $lh $conf->config_binary('logo.eps', $agentnum)
174 or die "can't write temp file: $!\n";
177 $params{'logo_file'} = $lh->filename;
179 if( $conf->exists('invoice-barcode')
180 && $self->can('invoice_barcode')
181 && $self->invnum ) { # don't try to barcode statements
182 my $png_file = $self->invoice_barcode($dir);
183 my $eps_file = $png_file;
184 $eps_file =~ s/\.png$/.eps/g;
185 $png_file =~ /(barcode.*png)/;
187 $eps_file =~ /(barcode.*eps)/;
190 my $curr_dir = cwd();
192 # after painfuly long experimentation, it was determined that sam2p won't
193 # accept : and other chars in the path, no matter how hard I tried to
194 # escape them, hence the chdir (and chdir back, just to be safe)
195 system('sam2p', '-j:quiet', $png_file, 'EPS:', $eps_file ) == 0
196 or die "sam2p failed: $!\n";
200 $params{'barcode_file'} = $eps_file;
203 my @filled_in = $self->print_generic( %params );
205 my $fh = new File::Temp( TEMPLATE => $tmp_template,
209 ) or die "can't open temp file: $!\n";
210 binmode($fh, ':utf8'); # language support
211 print $fh join('', @filled_in );
214 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
215 return ($1, $params{'logo_file'}, $params{'barcode_file'});
221 my $cust_main = $self->cust_main;
222 $cust_main ? $cust_main->agentnum : $self->prospect_main->agentnum;
225 =item print_generic OPTION => VALUE ...
227 Internal method - returns a filled-in template for this invoice as a scalar.
229 See print_ps and print_pdf for methods that return PostScript and PDF output.
237 The B<format> option is required and should be set to html, latex (print and PDF) or template (plaintext).
247 Overrides "Invoice" as the name of the sent document.
251 Used to control the printing of overdue messages. The
252 default is now. It isn't the date of the invoice; that's the `_date' field.
253 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
254 L<Time::Local> and L<Date::Parse> for conversion functions.
258 Logo file (path to temporary EPS file on the local filesystem)
262 CID for inline (emailed) images (logo)
266 Override customer's locale
270 Overrides any per customer cdr squelching when true
274 Supress the (invoice, quotation, statement, etc.) number
282 Supress the payment coupon
286 Barcode file (path to temporary EPS file on the local filesystem)
290 Flag indicating the barcode image should be a link (normal HTML dipaly)
294 Barcode CID for inline (emailed) images
296 =item preref_callback
298 Coderef run for each line item, code should return HTML to be displayed
299 before that line item (quotations only)
303 Deprecated. Used as a suffix for a configuration template. Please
304 don't use this, it deprecated in favor of more flexible alternatives.
310 #what's with all the sprintf('%10.2f')'s in here? will it cause any
311 # (alignment in text invoice?) problems to change them all to '%.2f' ?
312 # yes: fixed width/plain text printing will be borked
314 my( $self, %params ) = @_;
315 my $conf = $self->conf;
317 my $today = $params{today} ? $params{today} : time;
318 warn "$me print_generic called on $self with suffix $params{template}\n"
321 my $format = $params{format};
322 die "Unknown format: $format"
323 unless $format =~ /^(latex|html|template)$/;
325 my $cust_main = $self->cust_main || $self->prospect_main;
327 my $locale = $params{'locale'} || $cust_main->locale;
329 my %delimiters = ( 'latex' => [ '[@--', '--@]' ],
330 'html' => [ '<%=', '%>' ],
331 'template' => [ '{', '}' ],
334 warn "$me print_generic creating template\n"
337 # set the notice name here, and nowhere else.
338 my $notice_name = $params{notice_name}
339 || $conf->config('notice_name')
340 || $self->notice_name;
343 my $template = $params{template} ? $params{template} : $self->_agent_template;
344 my $templatefile = $self->template_conf. $format;
345 $templatefile .= "_$template"
346 if length($template) && $conf->exists($templatefile."_$template");
348 $self->set('_template',$template);
351 my @invoice_template = map "$_\n", $conf->config($templatefile)
352 or die "cannot load config data $templatefile";
354 if ( $format eq 'latex' && grep { /^%%Detail/ } @invoice_template ) {
355 #change this to a die when the old code is removed
356 # it's been almost ten years, changing it to a die
357 die "old-style invoice template $templatefile; ".
358 "patch with conf/invoice_latex.diff or use new conf/invoice_latex*\n";
359 #$old_latex = 'true';
360 #@invoice_template = _translate_old_latex_format(@invoice_template);
363 warn "$me print_generic creating T:T object\n"
366 my $text_template = new Text::Template(
368 SOURCE => \@invoice_template,
369 DELIMITERS => $delimiters{$format},
372 warn "$me print_generic compiling T:T object\n"
375 $text_template->compile()
376 or die "Can't compile $templatefile: $Text::Template::ERROR\n";
379 # additional substitution could possibly cause breakage in existing templates
382 'notes' => sub { map "$_", @_ },
383 'footer' => sub { map "$_", @_ },
384 'smallfooter' => sub { map "$_", @_ },
385 'returnaddress' => sub { map "$_", @_ },
386 'coupon' => sub { map "$_", @_ },
387 'summary' => sub { map "$_", @_ },
393 s/%%(.*)$/<!-- $1 -->/g;
394 s/\\section\*\{\\textsc\{(.)(.*)\}\}/<p><b><font size="+1">$1<\/font>\U$2<\/b>/g;
395 s/\\begin\{enumerate\}/<ol>/g;
397 s/\\end\{enumerate\}/<\/ol>/g;
398 s/\\textbf\{(.*)\}/<b>$1<\/b>/g;
407 sub { map { s/~/ /g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
409 sub { map { s/~/ /g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
415 s/\\hyphenation\{[\w\s\-]+}//;
420 'coupon' => sub { "" },
421 'summary' => sub { "" },
428 s/\\section\*\{\\textsc\{(.*)\}\}/\U$1/g;
429 s/\\begin\{enumerate\}//g;
431 s/\\end\{enumerate\}//g;
432 s/\\textbf\{(.*)\}/$1/g;
439 sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
441 sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
446 s/\\\\\*?\s*$/\n/; # dubious
447 s/\\hyphenation\{[\w\s\-]+}//;
451 'coupon' => sub { "" },
452 'summary' => sub { "" },
457 # hashes for differing output formats
458 my %nbsps = ( 'latex' => '~',
459 'html' => '', # '&nbps;' would be nice
460 'template' => '', # not used
462 my $nbsp = $nbsps{$format};
464 my %escape_functions = ( 'latex' => \&_latex_escape,
465 'html' => \&_html_escape_nbsp,#\&encode_entities,
466 'template' => sub { shift },
468 my $escape_function = $escape_functions{$format};
469 my $escape_function_nonbsp = ($format eq 'html')
470 ? \&_html_escape : $escape_function;
472 my %newline_tokens = ( 'latex' => '\\\\',
476 my $newline_token = $newline_tokens{$format};
478 warn "$me generating template variables\n"
481 # generate template variables
485 defined( $conf->config_orbase( "invoice_${format}returnaddress",
489 && length( $conf->config_orbase( "invoice_${format}returnaddress",
495 $returnaddress = join("\n",
496 $conf->config_orbase("invoice_${format}returnaddress", $template)
500 $conf->config_orbase('invoice_latexreturnaddress', $template) ) {
502 my $convert_map = $convert_maps{$format}{'returnaddress'};
505 &$convert_map( $conf->config_orbase( "invoice_latexreturnaddress",
510 } elsif ( grep /\S/, $conf->config('company_address', $cust_main->agentnum) ) {
512 my $convert_map = $convert_maps{$format}{'returnaddress'};
513 $returnaddress = join( "\n", &$convert_map(
514 map { s/( {2,})/'~' x length($1)/eg;
518 ( $conf->config('company_name', $cust_main->agentnum),
519 $conf->config('company_address', $cust_main->agentnum),
526 my $warning = "Couldn't find a return address; ".
527 "do you need to set the company_address configuration value?";
529 $returnaddress = $nbsp;
530 #$returnaddress = $warning;
534 warn "$me generating invoice data\n"
537 my $agentnum = $cust_main->agentnum;
542 'company_name' => scalar( $conf->config('company_name', $agentnum) ),
543 'company_address' => join("\n", $conf->config('company_address', $agentnum) ). "\n",
544 'company_phonenum'=> scalar( $conf->config('company_phonenum', $agentnum) ),
545 'returnaddress' => $returnaddress,
546 'agent' => &$escape_function($cust_main->agent->agent),
548 #invoice/quotation info
549 'no_number' => $params{'no_number'},
550 'invnum' => ( $params{'no_number'} ? '' : $self->invnum ),
551 'quotationnum' => $self->quotationnum,
552 'no_date' => $params{'no_date'},
553 '_date' => ( $params{'no_date'} ? '' : $self->_date ),
554 # workaround for inconsistent behavior in the early plain text
555 # templates; see RT#28271
556 'date' => ( $params{'no_date'}
558 : ($format eq 'template'
560 : $self->time2str_local('long', $self->_date, $format)
563 'today' => $self->time2str_local('long', $today, $format),
564 'terms' => $self->terms,
565 'template' => $template, #params{'template'},
566 'notice_name' => $notice_name, # escape?
567 'current_charges' => sprintf("%.2f", $self->charged),
568 'duedate' => $self->due_date2str('rdate'), #date_format?
569 'duedate_long' => $self->due_date2str('long'),
572 'custnum' => $cust_main->display_custnum,
573 'prospectnum' => $cust_main->prospectnum,
574 'agent_custid' => &$escape_function($cust_main->agent_custid),
575 ( map { $_ => &$escape_function($cust_main->$_()) }
576 qw( company address1 address2 city state zip fax )
578 'payname' => &$escape_function( $cust_main->invoice_attn
579 || $cust_main->contact_firstlast ),
582 'ship_enable' => $cust_main->invoice_ship_address || $conf->exists('invoice-ship_address'),
583 'unitprices' => $conf->exists('invoice-unitprice'),
584 'smallernotes' => $conf->exists('invoice-smallernotes'),
585 'smallerfooter' => $conf->exists('invoice-smallerfooter'),
586 'balance_due_below_line' => $conf->exists('balance_due_below_line'),
588 #layout info -- would be fancy to calc some of this and bury the template
590 'topmargin' => scalar($conf->config('invoice_latextopmargin', $agentnum)),
591 'headsep' => scalar($conf->config('invoice_latexheadsep', $agentnum)),
592 'textheight' => scalar($conf->config('invoice_latextextheight', $agentnum)),
593 'extracouponspace' => scalar($conf->config('invoice_latexextracouponspace', $agentnum)),
594 'couponfootsep' => scalar($conf->config('invoice_latexcouponfootsep', $agentnum)),
595 'verticalreturnaddress' => $conf->exists('invoice_latexverticalreturnaddress', $agentnum),
596 'addresssep' => scalar($conf->config('invoice_latexaddresssep', $agentnum)),
597 'amountenclosedsep' => scalar($conf->config('invoice_latexcouponamountenclosedsep', $agentnum)),
598 'coupontoaddresssep' => scalar($conf->config('invoice_latexcoupontoaddresssep', $agentnum)),
599 'addcompanytoaddress' => $conf->exists('invoice_latexcouponaddcompanytoaddress', $agentnum),
600 'couponlocation' => (scalar($conf->config('invoice_latexcouponlocation', $agentnum)) eq "top") ? 'top' : 'bottom',
602 # better hang on to conf_dir for a while (for old templates)
603 'conf_dir' => "$FS::UID::conf_dir/conf.$FS::UID::datasrc",
605 #these are only used when doing paged plaintext
611 #quotations have $name
612 $invoice_data{'name'} = $invoice_data{'payname'};
615 $invoice_data{'emt'} = sub { &$escape_function($self->mt(@_)) };
616 # prototype here to silence warnings
617 $invoice_data{'time2str'} = sub ($;$$) { $self->time2str_local(@_, $format) };
619 my $min_sdate = 999999999999;
621 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
622 next unless $cust_bill_pkg->pkgnum > 0;
623 $min_sdate = $cust_bill_pkg->sdate
624 if length($cust_bill_pkg->sdate) && $cust_bill_pkg->sdate < $min_sdate;
625 $max_edate = $cust_bill_pkg->edate
626 if length($cust_bill_pkg->edate) && $cust_bill_pkg->edate > $max_edate;
629 $invoice_data{'bill_period'} = '';
630 $invoice_data{'bill_period'} =
631 $self->time2str_local('%e %h', $min_sdate, $format)
633 $self->time2str_local('%e %h', $max_edate, $format)
634 if ($max_edate != 0 && $min_sdate != 999999999999);
636 $invoice_data{finance_section} = '';
637 if ( $conf->config('finance_pkgclass') ) {
639 qsearchs('pkg_class', { classnum => $conf->config('finance_pkgclass') });
640 $invoice_data{finance_section} = $pkg_class->categoryname;
642 $invoice_data{finance_amount} = '0.00';
643 $invoice_data{finance_section} ||= 'Finance Charges'; #avoid config confusion
645 my $countrydefault = $conf->config('countrydefault') || 'US';
646 foreach ( qw( address1 address2 city state zip country fax) ){
647 my $method = 'ship_'.$_;
648 $invoice_data{"ship_$_"} = $escape_function->($cust_main->$method);
650 if ( length($cust_main->ship_company) ) {
651 $invoice_data{'ship_company'} = $escape_function->($cust_main->ship_company);
653 $invoice_data{'ship_company'} = $escape_function->($cust_main->company);
655 $invoice_data{'ship_contact'} = $escape_function->($cust_main->contact);
656 $invoice_data{'ship_country'} = ''
657 if ( $invoice_data{'ship_country'} eq $countrydefault );
659 $invoice_data{'cid'} = $params{'cid'}
662 if ( $cust_main->bill_locationnum
663 && $cust_main->bill_location->country ne $countrydefault ) {
664 $invoice_data{'country'} = &$escape_function($cust_main->bill_country_full);
666 $invoice_data{'country'} = '';
670 $invoice_data{'address'} = \@address;
672 $invoice_data{'payname'}.
673 ( $cust_main->po_number
674 ? " (P.O. #". $cust_main->po_number. ")"
678 push @address, $cust_main->company
679 if $cust_main->company;
680 push @address, $cust_main->address1;
681 push @address, $cust_main->address2
682 if $cust_main->address2;
684 $cust_main->city. ", ". $cust_main->state. " ". $cust_main->zip;
685 push @address, $invoice_data{'country'}
686 if $invoice_data{'country'};
688 while (scalar(@address) < 5);
690 $invoice_data{'logo_file'} = $params{'logo_file'}
691 if $params{'logo_file'};
692 $invoice_data{'barcode_file'} = $params{'barcode_file'}
693 if $params{'barcode_file'};
694 $invoice_data{'barcode_img'} = $params{'barcode_img'}
695 if $params{'barcode_img'};
696 $invoice_data{'barcode_cid'} = $params{'barcode_cid'}
697 if $params{'barcode_cid'};
701 # using owed_on_invoice() instead of owed() here for $balance_due
702 # using _items_previous_total() instead of ->previous() for $pr_total
704 # owed_on_invoice() is aware of configuration flags that affect how an
705 # invoice is rendered. May not return actual current balance. Will
706 # return balance appropriate for the invoice being rendered, based
707 # on which past due items, current charges, and future payments are
710 # Going forward, usage of owed(), or bypassing cust_bill helper methods
711 # when generating invoice lines may lead to incorrect or misleading
714 # Helper methods that are aware of invoicing conf flags:
715 # - owed_on_invoice # use instead of owed()
716 # - _items_previous() # use instead of previous()
717 # - _items_credits() # use instead of cust_credit()
718 # - _items_payments()
720 # - _items_previous_total() # use instead of previous()
721 # - _items_payments_total()
722 # - _items_credits_total() # use instead of cust_credit()
724 my $pr_total = $self->_items_previous_total();
726 my $balance_due = $self->owed_on_invoice();
727 $invoice_data{'balance'} = sprintf("%.2f", $balance_due);
729 # flag telling this invoice to have a first-page summary
730 my $summarypage = '';
732 if ( $self->custnum && $self->invnum ) {
733 # XXX should be an FS::cust_bill method to set the defaults, instead
734 # of checking the type here
736 # info from customer's last invoice before this one, for some
738 $invoice_data{'last_bill'} = {};
740 # my $last_bill = $self->previous_bill;
741 # if ( $last_bill ) {
743 # Populate template stash for previous balance and payments
745 # Used on summary page as "Previous Balance"
746 $invoice_data{'true_previous_balance'} = sprintf("%.2f", $pr_total);
748 # Used on summary page as "Payments"
749 $invoice_data{'balance_adjustments'} = sprintf("%.2f",
750 $self->_items_payments_total() + $self->_items_credits_total()
753 # Used in invoice template as "Previous Balance"
754 $invoice_data{'previous_balance'} = sprintf("%.2f", $pr_total);
756 # $invoice_data{last_bill}{_date}:
757 # Not used in default templates, but may be in use by someone
759 # ! May be a problem field if they are using it... this field
760 # stores the date of the previous invoice... it is possible to
761 # carry a balance, but have the immediately previous invoice paid off.
762 # In this case, this field might be presenting bad data? Not
763 # altering the problematic behavior, because someone might be
764 # expecting this bad behavior in their templates for some other
765 # purpose, such as a "your last bill was dated %_date%"
766 my $last_bill = $self->previous_bill;
767 $invoice_data{'last_bill'}{'_date'}
769 ? $last_bill->_date()
772 # $invoice_data{previous_payments}
773 # Not used in default templates, but may be in use by someone
775 # Returns an array of hrefs representing payments, each with keys:
776 # - _date: epoch timestamp
777 # - date: text formatted date
778 # - amount: money formatted amount string
779 # - payinfo: string from payby_payinfo_pretty()
780 # - paynum: id for cust_pay
781 # - description: Text description for bill line item
783 my @payments = $self->_items_payments();
784 $invoice_data{previous_payments} = \@payments;
786 # $invoice_data{previous_credits}
787 # Not used in default templates, but may be in use by someone
789 # Returns an array of hrefs representing credits, each with keys:
790 # - _date: epoch timestamp
791 # - date: text formatted date
792 # - amount: money formatted amount string
793 # - crednum: id for cust_credit
794 # - description: Text description for bill line item
795 # - creditreason: reason() from cust_credit
797 my @credits = $self->_items_credits();
798 $invoice_data{previous_credits} = \@credits;
800 # Populate formatted date field
801 for my $pmt_href (@payments, @credits) {
802 $pmt_href->{date} = $self->time2str_local(
810 # There are no outstanding invoices = YAPH
811 $invoice_data{'true_previous_balance'} =
812 $invoice_data{'balance_adjustments'} =
813 $invoice_data{'previous_balance'} = '0.00';
814 $invoice_data{'previous_payments'} =
815 $invoice_data{'previous_credits'} = [];
818 # Condencing a lot of debug staements here
820 warn "\$invoice_data{$_}: $invoice_data{$_}"
822 true_previous_balance
830 if ( $conf->config_bool('invoice_usesummary', $agentnum) ) {
831 $invoice_data{'summarypage'} = $summarypage = 1;
834 } # if this is an invoice
836 warn "$me substituting variables in notes, footer, smallfooter\n"
839 my $tc = $self->template_conf;
840 my @include = ( [ $tc, 'notes' ],
841 [ 'invoice_', 'footer' ],
842 [ 'invoice_', 'smallfooter', ],
843 [ 'invoice_', 'watermark' ],
845 push @include, [ $tc, 'coupon', ]
846 unless $params{'no_coupon'};
848 foreach my $i (@include) {
850 # load the configuration for this sub-template
852 my($base, $include) = @$i;
854 my $inc_file = $conf->key_orbase("$base$format$include", $template);
856 my @inc_src = $conf->config($inc_file, $agentnum);
858 my $converter = $convert_maps{$format}{$include};
860 # then attempt to convert LaTeX to the requested format
861 $inc_file = $conf->key_orbase($base.'latex'.$include, $template);
862 @inc_src = &$converter( $conf->config($inc_file, $agentnum) );
864 # this isn't included in the convert_maps
865 my ($open, $close) = @{ $delimiters{$format} };
870 } # else @inc_src is empty and that's fine
872 # make a Text::Template out of it
874 my $inc_tt = new Text::Template (
876 SOURCE => [ map "$_\n", @inc_src ],
877 DELIMITERS => $delimiters{$format},
878 ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
880 unless ( $inc_tt->compile() ) {
881 my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
882 warn $error. "Template:\n". join('', map "$_\n", @inc_src);
888 $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
890 $invoice_data{$include} =~ s/\n+$//
891 if ($format eq 'latex');
894 # if (well, probably when) we still need PO numbers in the brave new world of
895 # 4.x, then we'll have to add them back as their own customer fields
896 # # let invoices use either of these as needed
897 # $invoice_data{'po_num'} = ($cust_main->payby eq 'BILL')
898 # ? $cust_main->payinfo : '';
899 # $invoice_data{'po_line'} =
900 # ( $cust_main->payby eq 'BILL' && $cust_main->payinfo )
901 # ? &$escape_function($self->mt("Purchase Order #").$cust_main->payinfo)
904 my %money_chars = ( 'latex' => '',
905 'html' => $conf->config('money_char') || '$',
908 my $money_char = $money_chars{$format};
911 my %other_money_chars = ( 'latex' => '\dollar ',#XXX should be a config too
912 'html' => $conf->config('money_char') || '$',
915 my $other_money_char = $other_money_chars{$format};
916 $invoice_data{'dollar'} = $other_money_char;
918 my %minus_signs = ( 'latex' => '$-$',
920 'template' => '- ' );
921 my $minus = $minus_signs{$format};
923 my @detail_items = ();
924 my @total_items = ();
928 $invoice_data{'detail_items'} = \@detail_items;
929 $invoice_data{'total_items'} = \@total_items;
930 $invoice_data{'buf'} = \@buf;
931 $invoice_data{'sections'} = \@sections;
933 warn "$me generating sections\n"
936 my $unsquelched = $params{unsquelch_cdr} || $cust_main->squelch_cdr ne 'Y';
937 my $multisection = $self->has_sections;
938 if ( $multisection ) {
939 $invoice_data{multisection} = $conf->config($tc.'sections_method') || 1;
942 my $extra_sections = [];
943 my $extra_lines = ();
945 # default section ('Charges')
946 my $default_section = { 'description' => '',
951 # Previous Charges section
952 # subtotal is the first return value from $self->previous
953 my $previous_section;
954 # if the invoice has major sections, or if we're summarizing previous
955 # charges with a single line, or if we've been specifically told to put them
956 # in a section, create a section for previous charges:
957 if ( $multisection or
958 $conf->exists('previous_balance-summary_only') or
959 $conf->exists('previous_balance-section') ) {
961 $previous_section = { 'description' => $self->mt('Previous Charges'),
962 'subtotal' => $other_money_char.
963 sprintf('%.2f', $pr_total),
964 'summarized' => '', #why? $summarypage ? 'Y' : '',
967 # Include balance aging line and template variables
968 my @aged_balances = $self->_items_aging_balances();
969 ( $invoice_data{aged_balance_current},
970 $invoice_data{aged_balance_30d},
971 $invoice_data{aged_balance_60d},
972 $invoice_data{aged_balance_90d}
975 if ($conf->exists('invoice_include_aging')) {
976 $previous_section->{posttotal} = sprintf(
977 '0 / 30 / 60 / 90 days overdue %.2f / %.2f / %.2f / %.2f',
983 # otherwise put them in the main section
984 $previous_section = $default_section;
987 my $adjust_section = {
988 'description' => $self->mt('Credits, Payments, and Adjustments'),
989 'adjust_section' => 1,
990 'subtotal' => 0, # adjusted below
992 my $adjust_weight = _pkg_category($adjust_section->{description})
993 ? _pkg_category($adjust_section->{description})->weight
995 $adjust_section->{'summarized'} = ''; #why? $summarypage && !$adjust_weight ? 'Y' : '';
996 # Note: 'sort_weight' here is actually a flag telling whether there is an
997 # explicit package category for the adjust section. If so, certain behavior
999 $adjust_section->{'sort_weight'} = $adjust_weight;
1002 if ( $multisection ) {
1003 ($extra_sections, $extra_lines) =
1004 $self->_items_extra_usage_sections($escape_function_nonbsp, $format)
1005 if $conf->exists('usage_class_as_a_section', $cust_main->agentnum)
1006 && $self->can('_items_extra_usage_sections');
1008 push @$extra_sections, $adjust_section if $adjust_section->{sort_weight};
1010 push @detail_items, @$extra_lines if $extra_lines;
1012 # the code is written so that both methods can be used together, but
1013 # we haven't yet changed the template to take advantage of that, so for
1014 # now, treat them as mutually exclusive.
1015 my %section_method = ( by_category => 1 );
1016 if ( $conf->config($tc.'sections_method') eq 'location' ) {
1017 %section_method = ( by_location => 1 );
1019 my ($early, $late) =
1020 $self->_items_sections( 'summary' => $summarypage,
1021 'escape' => $escape_function_nonbsp,
1022 'extra_sections' => $extra_sections,
1023 'format' => $format,
1026 push @sections, @$early;
1027 $late_sections = $late;
1029 if ( $conf->exists('svc_phone_sections')
1030 && $self->can('_items_svc_phone_sections')
1033 my ($phone_sections, $phone_lines) =
1034 $self->_items_svc_phone_sections($escape_function_nonbsp, $format);
1035 push @{$late_sections}, @$phone_sections;
1036 push @detail_items, @$phone_lines;
1038 if ( $conf->exists('voip-cust_accountcode_cdr')
1039 && $cust_main->accountcode_cdr
1040 && $self->can('_items_accountcode_cdr')
1043 my ($accountcode_section, $accountcode_lines) =
1044 $self->_items_accountcode_cdr($escape_function_nonbsp,$format);
1045 if ( scalar(@$accountcode_lines) ) {
1046 push @{$late_sections}, $accountcode_section;
1047 push @detail_items, @$accountcode_lines;
1050 } else {# not multisection
1051 # make a default section
1052 push @sections, $default_section;
1053 # and calculate the finance charge total, since it won't get done otherwise.
1054 # and the default section total
1055 # XXX possibly finance_pkgclass should not be used in this manner?
1056 my @finance_charges;
1058 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1059 if ( $invoice_data{finance_section} and
1060 grep { $_->section eq $invoice_data{finance_section} }
1061 $cust_bill_pkg->cust_bill_pkg_display ) {
1062 # I think these are always setup fees, but just to be sure...
1063 push @finance_charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1065 push @charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1068 $invoice_data{finance_amount} =
1069 sprintf('%.2f', sum( @finance_charges ) || 0);
1070 $default_section->{subtotal} = $other_money_char.
1071 sprintf('%.2f', sum( @charges ) || 0);
1074 # start setting up summary subtotals
1075 my @summary_subtotals;
1076 my $method = $conf->config('summary_subtotals_method');
1077 if ( $method and $method ne $conf->config($tc.'sections_method') ) {
1078 # then re-section them by the correct method
1079 my %section_method = ( by_category => 1 );
1080 if ( $conf->config('summary_subtotals_method') eq 'location' ) {
1081 %section_method = ( by_location => 1 );
1083 my ($early, $late) =
1084 $self->_items_sections( 'summary' => $summarypage,
1085 'escape' => $escape_function_nonbsp,
1086 'extra_sections' => $extra_sections,
1087 'format' => $format,
1090 foreach ( @$early ) {
1091 next if $_->{subtotal} == 0;
1092 $_->{subtotal} = $other_money_char.sprintf('%.2f', $_->{subtotal});
1093 push @summary_subtotals, $_;
1096 # subtotal sectioning is the same as for the actual invoice sections
1097 @summary_subtotals = @sections;
1100 # Hereafter, push sections to both @sections and @summary_subtotals
1101 # if they belong in both places (e.g. tax section). Late sections are
1102 # never in @summary_subtotals.
1104 # previous invoice balances in the Previous Charges section if there
1105 # is one, otherwise in the main detail section
1106 # (except if summary_only is enabled, don't show them at all)
1107 if ( $self->can('_items_previous') &&
1108 $self->enable_previous &&
1109 ! $conf->exists('previous_balance-summary_only') ) {
1111 warn "$me adding previous balances\n"
1114 foreach my $line_item ( $self->_items_previous ) {
1117 ref => $line_item->{'pkgnum'},
1118 pkgpart => $line_item->{'pkgpart'},
1119 #quantity => 1, # not really correct
1120 section => $previous_section, # which might be $default_section
1121 description => &$escape_function($line_item->{'description'}),
1122 ext_description => [ map { &$escape_function($_) }
1123 @{ $line_item->{'ext_description'} || [] }
1125 amount => $money_char . $line_item->{'amount'},
1126 product_code => $line_item->{'pkgpart'} || 'N/A',
1129 push @detail_items, $detail;
1130 push @buf, [ $detail->{'description'},
1131 $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1137 if ( $pr_total && $self->enable_previous ) {
1138 push @buf, ['','-----------'];
1139 push @buf, [ $self->mt('Total Previous Balance'),
1140 $money_char. sprintf("%10.2f", $pr_total) ];
1144 if ( $conf->exists('svc_phone-did-summary') && $self->can('_did_summary') ) {
1145 warn "$me adding DID summary\n"
1148 my ($didsummary,$minutes) = $self->_did_summary;
1149 my $didsummary_desc = 'DID Activity Summary (since last invoice)';
1151 { 'description' => $didsummary_desc,
1152 'ext_description' => [ $didsummary, $minutes ],
1156 foreach my $section (@sections, @$late_sections) {
1158 # begin some normalization
1159 $section->{'subtotal'} = $section->{'amount'}
1161 && !exists($section->{subtotal})
1162 && exists($section->{amount});
1164 $invoice_data{finance_amount} = sprintf('%.2f', $section->{'subtotal'} )
1165 if ( $invoice_data{finance_section} &&
1166 $section->{'description'} eq $invoice_data{finance_section} );
1168 if ( $multisection ) {
1170 if ( ref($section->{'subtotal'}) ) {
1172 $section->{'subtotal'} =
1173 sprintf("$other_money_char%.2f to $other_money_char%.2f",
1174 $section->{'subtotal'}[0],
1175 $section->{'subtotal'}[1]
1180 $section->{'subtotal'} = $other_money_char.
1181 sprintf('%.2f', $section->{'subtotal'})
1185 # continue some normalization
1186 $section->{'amount'} = $section->{'subtotal'}
1190 if ( $section->{'description'} ) {
1191 push @buf, ( [ &$escape_function($section->{'description'}), '' ],
1196 warn "$me setting options\n"
1200 $options{'section'} = $section if $multisection;
1201 $options{'section_with_taxes'} = 1
1203 && $conf->config_bool('invoice_sections_with_taxes', $cust_main->agentnum);
1204 $options{'format'} = $format;
1205 $options{'escape_function'} = $escape_function;
1206 $options{'no_usage'} = 1 unless $unsquelched;
1207 $options{'unsquelched'} = $unsquelched;
1208 $options{'summary_page'} = $summarypage;
1209 $options{'skip_usage'} =
1210 scalar(@$extra_sections) && !grep{$section == $_} @$extra_sections;
1211 $options{'preref_callback'} = $params{'preref_callback'};
1212 $options{'disable_line_item_date_ranges'} =
1213 $conf->exists('disable_line_item_date_ranges');
1215 warn "$me searching for line items\n"
1218 my %section_tax_lines;
1220 foreach my $line_item ( $self->_items_pkg(%options),
1221 $self->_items_fee(%options) ) {
1223 # When bill is sectioned by location, fees may be displayed within the
1224 # appropriate location section. Suppress this fee from the taxes/fees
1225 # end section, so it doesn't appear to be charged twice and make the
1226 # subtotals seem incorrect
1228 if $line_item->{locationnum}
1229 && ref $options{section}
1230 && !exists $options{section}->{locationnum}
1231 && $self->has_sections
1232 && $conf->config($tc.'sections_method') eq 'location';
1234 warn "$me adding line item ".
1235 join(', ', map "$_=>".$line_item->{$_}, keys %$line_item). "\n"
1238 push @buf, ( [ $line_item->{'description'},
1239 $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1241 map { [ " ". $_, '' ] } @{$line_item->{'ext_description'}},
1244 $line_item->{'ref'} = $line_item->{'pkgnum'};
1245 $line_item->{'product_code'} = $line_item->{'pkgpart'} || 'N/A'; # mt()?
1246 $line_item->{'section'} = $section;
1247 $line_item->{'description'} = &$escape_function($line_item->{'description'});
1248 $line_item->{'amount'} = $money_char.$line_item->{'amount'};
1250 if ( length($line_item->{'unit_amount'}) ) {
1251 $line_item->{'unit_amount'} = $money_char.$line_item->{'unit_amount'};
1253 $line_item->{'ext_description'} ||= [];
1255 if ( $options{section_with_taxes} && ref $line_item->{pkg_tax} ) {
1256 for my $line_tax ( @{$ line_item->{pkg_tax} } ) {
1258 # It is rarely possible for the same tax record to be presented here
1259 # multiple times. See cust_bill_pkg::_pkg_tax_list for more info
1260 next if $seen_tax_lines{ $line_tax->{billpkgtaxlocationnum} };
1261 $seen_tax_lines{ $line_tax->{billpkgtaxlocationnum} } = 1;
1263 $section_tax_lines{ $line_tax->{taxname} } += $line_tax->{amount};
1267 push @detail_items, $line_item;
1270 # If conf flag invoice_sections_with_taxes:
1271 # - Add @detail_items for taxes into each section
1272 # - Update section subtotal to include taxes
1273 if ( $options{section_with_taxes} && %section_tax_lines ) {
1274 for my $taxname ( keys %section_tax_lines ) {
1276 push @detail_items, {
1277 section => $section,
1278 amount => sprintf($money_char."%.2f",$section_tax_lines{$taxname}),
1279 description => &$escape_function($taxname),
1282 # Append taxes to total. If line format resembles "$5.00 to $12.00"
1283 # append to the second value.
1285 # $section->{subtotal} = '$5.00 to 12.00'; # for testing:
1286 if ($section->{subtotal} =~ /to/) {
1287 my @subtotal = split /\s/, $section->{subtotal};
1288 $subtotal[2] =~ s/[^\d\.]//g;
1289 $subtotal[2] = sprintf(
1291 ( $subtotal[2] + $section_tax_lines{$taxname} )
1293 $section->{subtotal} = join ' ', @subtotal;
1295 $section->{subtotal} =~ s/[^\d\.]//g;
1296 $section->{subtotal} = sprintf(
1297 $money_char . "%.2f",
1298 ( $section->{subtotal} + $section_tax_lines{$taxname} )
1305 if ( $section->{'description'} ) {
1306 push @buf, ( ['','-----------'],
1307 [ $section->{'description'}. ' sub-total',
1308 $section->{'subtotal'} # already formatted this
1317 $invoice_data{current_less_finance} =
1318 sprintf('%.2f', $self->charged - $invoice_data{finance_amount} );
1320 # if there's anything in the Previous Charges section, prepend it to the list
1321 if ( $pr_total and $previous_section ne $default_section ) {
1322 unshift @sections, $previous_section;
1323 # but not @summary_subtotals
1326 warn "$me adding taxes\n"
1329 # create a tax section if we don't yet have one
1330 my @items_tax = $self->_items_tax;
1331 my $tax_description = 'Taxes, Surcharges, and Fees';
1333 List::Util::first { $_->{description} eq $tax_description } @sections;
1334 if (!$tax_section) {
1335 $tax_section = { 'description' => $tax_description };
1336 push @sections, $tax_section if $multisection and @items_tax > 0;
1338 $tax_section->{tax_section} = 1; # mark this section as containing taxes
1339 # if this is an existing tax section, we're merging the tax items into it.
1340 # grab the taxtotal that's already there, strip the money symbol if any
1341 my $taxtotal = $tax_section->{'subtotal'} || 0;
1342 $taxtotal =~ s/^\Q$other_money_char\E//;
1345 #my $tax_weight = _pkg_category($tax_section->{description})
1346 # ? _pkg_category($tax_section->{description})->weight
1348 #$tax_section->{'summarized'} = ''; #why? $summarypage && !$tax_weight ? 'Y' : '';
1349 #$tax_section->{'sort_weight'} = $tax_weight;
1351 my $invoice_sections_with_taxes = $conf->config_bool(
1352 'invoice_sections_with_taxes', $cust_main->agentnum
1355 foreach my $tax ( @items_tax ) {
1358 my $description = &$escape_function( $tax->{'description'} );
1359 my $amount = sprintf( '%.2f', $tax->{'amount'} );
1361 if ( $multisection ) {
1362 if ( !$invoice_sections_with_taxes ) {
1364 $taxtotal += $tax->{'amount'};
1366 push @detail_items, {
1367 ext_description => [],
1370 description => $description,
1371 amount => $money_char. $amount,
1373 section => $tax_section,
1379 $taxtotal += $tax->{'amount'};
1381 push @total_items, {
1382 'total_item' => $description,
1383 'total_amount' => $other_money_char. $amount,
1388 push @buf,[ $description,
1389 $money_char. $amount,
1396 $total->{'total_item'} = $self->mt('Sub-total');
1397 $total->{'total_amount'} =
1398 $other_money_char. sprintf('%.2f', $self->charged - $taxtotal );
1400 if ( $multisection ) {
1402 if ( $conf->config_bool('invoice_sections_with_taxes', $cust_main->agentnum) ) {
1403 # If all tax items are displayed in location/category sections,
1404 # remove the empty tax section
1405 @sections = grep{ $_ ne $tax_section } @sections
1406 unless grep{ $_->{section} eq $tax_section } @detail_items;
1409 if ( $taxtotal > 0 ) {
1410 # there are taxes, so prepare the section to be displayed.
1411 # $taxtotal already includes any line items that were already in the
1412 # section (fees, taxes that are charged as packages for some reason).
1413 # also set 'summarized' to false so that this isn't a summary-only
1415 $tax_section->{'subtotal'} = $other_money_char.
1416 sprintf('%.2f', $taxtotal);
1417 $tax_section->{'pretotal'} = 'New charges sub-total '.
1418 $total->{'total_amount'};
1419 $tax_section->{'description'} = $self->mt($tax_description);
1420 $tax_section->{'summarized'} = '';
1422 # append tax section unless it's already there
1423 push @sections, $tax_section
1424 unless grep {$_ eq $tax_section} @sections;
1426 push @summary_subtotals, $tax_section
1427 unless grep {$_ eq $tax_section} @summary_subtotals;
1431 unshift @total_items, $total;
1434 $invoice_data{'taxtotal'} = sprintf('%.2f', $taxtotal);
1440 my %embolden_functions = (
1441 'latex' => sub { return '\textbf{'. shift(). '}' },
1442 'html' => sub { return '<b>'. shift(). '</b>' },
1443 'template' => sub { shift },
1445 my $embolden_function = $embolden_functions{$format};
1447 if ( $multisection ) {
1449 if ( $adjust_section->{'sort_weight'} ) {
1450 $adjust_section->{'posttotal'} = $self->mt('Balance Forward').' '.
1451 $other_money_char. sprintf("%.2f", ($self->billing_balance || 0) );
1453 $adjust_section->{'pretotal'} = $self->mt('New charges total').' '.
1454 $other_money_char. sprintf('%.2f', $self->charged );
1459 if ( $self->can('_items_total') ) { # should always be true now
1461 # even for multisection, need plain text version
1463 my @new_total_items = $self->_items_total;
1465 push @buf,['','-----------'];
1467 foreach ( @new_total_items ) {
1468 my ($item, $amount) = ($_->{'total_item'}, $_->{'total_amount'});
1469 $_->{'total_item'} = &$embolden_function( $item );
1471 if ( ref($amount) ) {
1472 $_->{'total_amount'} = &$embolden_function(
1473 $other_money_char.$amount->[0]. ' to '.
1474 $other_money_char.$amount->[1]
1477 $_->{'total_amount'} = &$embolden_function( $other_money_char.$amount );
1480 # but if it's multisection, don't append to @total_items. the adjust
1481 # section has all this stuff
1482 push @total_items, $_ if !$multisection;
1483 push @buf, [ $item, $money_char.sprintf('%10.2f',$amount) ];
1486 push @buf, [ '', '' ];
1488 # if we're showing previous invoices, also show previous
1489 # credits and payments
1490 if ( $self->enable_previous
1491 and $self->can('_items_credits')
1492 and $self->can('_items_payments') )
1496 my $credittotal = 0;
1497 foreach my $credit (
1498 $self->_items_credits( 'template' => $template, 'trim_len' => 40 )
1502 $total->{'total_item'} = &$escape_function($credit->{'description'});
1503 $credittotal += $credit->{'amount'};
1504 $total->{'total_amount'} = $minus.$other_money_char.$credit->{'amount'};
1505 if ( $multisection ) {
1506 push @detail_items, {
1507 ext_description => [],
1510 description => &$escape_function($credit->{'description'}),
1511 amount => $money_char . $credit->{'amount'},
1513 section => $adjust_section,
1516 push @total_items, $total;
1520 $invoice_data{'credittotal'} = sprintf('%.2f', $credittotal);
1523 foreach my $credit (
1524 $self->_items_credits( 'template' => $template, 'trim_len'=>32 )
1526 push @buf, [ $credit->{'description'}, $money_char.$credit->{'amount'} ];
1530 my $paymenttotal = 0;
1531 foreach my $payment (
1532 $self->_items_payments( 'template' => $template )
1535 $total->{'total_item'} = &$escape_function($payment->{'description'});
1536 $paymenttotal += $payment->{'amount'};
1537 $total->{'total_amount'} = $minus.$other_money_char.$payment->{'amount'};
1538 if ( $multisection ) {
1539 push @detail_items, {
1540 ext_description => [],
1543 description => &$escape_function($payment->{'description'}),
1544 amount => $money_char . $payment->{'amount'},
1546 section => $adjust_section,
1549 push @total_items, $total;
1551 push @buf, [ $payment->{'description'},
1552 $money_char. sprintf("%10.2f", $payment->{'amount'}),
1555 $invoice_data{'paymenttotal'} = sprintf('%.2f', $paymenttotal);
1557 if ( $multisection ) {
1558 $adjust_section->{'subtotal'} = $other_money_char.
1559 sprintf('%.2f', $credittotal + $paymenttotal);
1561 #why this? because {sort_weight} forces the adjust_section to appear
1562 #in @extra_sections instead of @sections. obviously.
1563 push @sections, $adjust_section
1564 unless $adjust_section->{sort_weight};
1565 # do not summarize; adjustments there are shown according to
1569 # create Balance Due message
1572 $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1573 $total->{'total_amount'} =
1574 &$embolden_function(
1575 $other_money_char. sprintf('%.2f', #why? $summarypage
1576 # ? $self->charged +
1577 # $self->billing_balance
1582 if ( $multisection && !$adjust_section->{sort_weight} ) {
1583 $adjust_section->{'posttotal'} = $total->{'total_item'}. ' '.
1584 $total->{'total_amount'};
1586 push @total_items, $total;
1588 push @buf,['','-----------'];
1589 push @buf,[$self->balance_due_msg, $money_char.
1590 sprintf("%10.2f", $balance_due ) ];
1593 if ( $conf->exists('previous_balance-show_credit')
1594 and $cust_main->balance < 0 ) {
1595 my $credit_total = {
1596 'total_item' => &$embolden_function($self->credit_balance_msg),
1597 'total_amount' => &$embolden_function(
1598 $other_money_char. sprintf('%.2f', -$cust_main->balance)
1601 if ( $multisection ) {
1602 $adjust_section->{'posttotal'} .= $newline_token .
1603 $credit_total->{'total_item'} . ' ' . $credit_total->{'total_amount'};
1606 push @total_items, $credit_total;
1608 push @buf,['','-----------'];
1609 push @buf,[$self->credit_balance_msg, $money_char.
1610 sprintf("%10.2f", -$cust_main->balance ) ];
1614 } #end of default total adding ! can('_items_total')
1616 if ( $multisection ) {
1617 if ( $conf->exists('svc_phone_sections')
1618 && $self->can('_items_svc_phone_sections')
1622 $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1623 $total->{'total_amount'} =
1624 &$embolden_function(
1625 $other_money_char. sprintf('%.2f', $balance_due)
1627 my $last_section = pop @sections;
1628 $last_section->{'posttotal'} = $total->{'total_item'}. ' '.
1629 $total->{'total_amount'};
1630 push @sections, $last_section;
1632 push @sections, @$late_sections
1636 # make a discounts-available section, even without multisection
1637 if ( $conf->exists('discount-show_available')
1638 and my @discounts_avail = $self->_items_discounts_avail ) {
1639 my $discount_section = {
1640 'description' => $self->mt('Discounts Available'),
1645 push @sections, $discount_section; # do not summarize
1646 push @detail_items, map { +{
1647 'ref' => '', #should this be something else?
1648 'section' => $discount_section,
1649 'description' => &$escape_function( $_->{description} ),
1650 'amount' => $money_char . &$escape_function( $_->{amount} ),
1651 'ext_description' => [ &$escape_function($_->{ext_description}) || () ],
1652 } } @discounts_avail;
1655 # not adding any more sections after this
1656 $invoice_data{summary_subtotals} = \@summary_subtotals;
1659 if ( $conf->exists('usage_class_summary')
1660 and $self->can('_items_usage_class_summary') ) {
1661 my @usage_subtotals = $self->_items_usage_class_summary(escape => $escape_function, 'money_char' => $other_money_char);
1662 if ( @usage_subtotals ) {
1663 unshift @sections, $usage_subtotals[0]->{section}; # do not summarize
1664 unshift @detail_items, @usage_subtotals;
1668 # invoice history "section" (not really a section)
1669 # not to be included in any subtotals, completely independent of
1671 if ( $conf->exists('previous_invoice_history') and $cust_main->isa('FS::cust_main') ) {
1674 foreach my $cust_bill ( $cust_main->cust_bill ) {
1675 # XXX hardcoded format, and currently only 'charged'; add other fields
1676 # if they become necessary
1677 my $date = $self->time2str_local('%b %Y', $cust_bill->_date);
1678 $history{$date} ||= 0;
1679 $history{$date} += $cust_bill->charged;
1680 # just so we have a numeric sort key
1681 $monthorder{$date} ||= $cust_bill->_date;
1683 my @sorted_months = sort { $monthorder{$a} <=> $monthorder{$b} }
1685 my @sorted_amounts = map { sprintf('%.2f', $history{$_}) } @sorted_months;
1686 $invoice_data{monthly_history} = [ \@sorted_months, \@sorted_amounts ];
1689 # service locations: another option for template customization
1691 foreach my $item (@detail_items) {
1692 if ( $item->{locationnum} ) {
1693 $location_info{ $item->{locationnum} } ||= {
1694 FS::cust_location->by_key( $item->{locationnum} )->location_hash
1698 $invoice_data{location_info} = \%location_info;
1700 # debugging hook: call this with 'diag' => 1 to just get a hash of
1701 # the invoice variables
1702 return \%invoice_data if ( $params{'diag'} );
1704 # All sections and items are built; now fill in templates.
1705 my @includelist = ();
1706 push @includelist, 'summary' if $summarypage;
1707 foreach my $include ( @includelist ) {
1709 my $inc_file = $conf->key_orbase("invoice_${format}$include", $template);
1712 if ( length( $conf->config($inc_file, $agentnum) ) ) {
1714 @inc_src = $conf->config($inc_file, $agentnum);
1718 $inc_file = $conf->key_orbase("invoice_latex$include", $template);
1720 my $convert_map = $convert_maps{$format}{$include};
1722 @inc_src = map { s/\[\@--/$delimiters{$format}[0]/g;
1723 s/--\@\]/$delimiters{$format}[1]/g;
1726 &$convert_map( $conf->config($inc_file, $agentnum) );
1730 my $inc_tt = new Text::Template (
1732 SOURCE => [ map "$_\n", @inc_src ],
1733 DELIMITERS => $delimiters{$format},
1734 ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
1736 unless ( $inc_tt->compile() ) {
1737 my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
1738 warn $error. "Template:\n". join('', map "$_\n", @inc_src);
1742 $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
1744 $invoice_data{$include} =~ s/\n+$//
1745 if ($format eq 'latex');
1750 foreach ( grep /invoice_lines\(\d*\)/, @invoice_template ) { #kludgy
1751 /invoice_lines\((\d*)\)/;
1752 $invoice_lines += $1 || scalar(@buf);
1755 die "no invoice_lines() functions in template?"
1756 if ( $format eq 'template' && !$wasfunc );
1758 if ( $invoice_lines ) {
1759 $invoice_data{'total_pages'} = int( scalar(@buf) / $invoice_lines );
1760 $invoice_data{'total_pages'}++
1761 if scalar(@buf) % $invoice_lines;
1764 #setup subroutine for the template
1765 $invoice_data{invoice_lines} = sub {
1766 my $lines = shift || scalar(@buf);
1775 if ($format eq 'template') {
1780 push @collect, split("\n",
1781 $text_template->fill_in( HASH => \%invoice_data )
1783 $invoice_data{'page'}++;
1785 map "$_\n", @collect;
1787 } else { # this is where we actually create the invoice
1789 if ( $params{no_addresses} ) {
1790 delete $invoice_data{$_} foreach qw(
1791 payname company address1 address2 city state zip country
1793 $invoice_data{returnaddress} = '~';
1796 warn "filling in template for invoice ". $self->invnum. "\n"
1798 warn join("\n", map " $_ => ". $invoice_data{$_}, keys %invoice_data). "\n"
1801 $text_template->fill_in(HASH => \%invoice_data);
1805 sub notice_name { '('.shift->table.')'; }
1807 # this is not supposed to happen
1808 sub template_conf { warn "bare FS::Template_Mixin::template_conf";
1812 =item print_ps HASHREF | [ TIME [ , TEMPLATE ] ]
1814 Returns an postscript invoice, as a scalar.
1816 Options can be passed as a hashref (recommended) or as a list of time, template
1817 and then any key/value pairs for any other options.
1819 I<time> an optional value used to control the printing of overdue messages. The
1820 default is now. It isn't the date of the invoice; that's the `_date' field.
1821 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1822 L<Time::Local> and L<Date::Parse> for conversion functions.
1824 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1831 my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1832 my $ps = generate_ps($file);
1834 unlink($barcodefile) if $barcodefile;
1839 =item print_pdf HASHREF | [ TIME [ , TEMPLATE ] ]
1841 Returns an PDF invoice, as a scalar.
1843 Options can be passed as a hashref (recommended) or as a list of time, template
1844 and then any key/value pairs for any other options.
1846 I<time> an optional value used to control the printing of overdue messages. The
1847 default is now. It isn't the date of the invoice; that's the `_date' field.
1848 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1849 L<Time::Local> and L<Date::Parse> for conversion functions.
1851 I<template>, if specified, is the name of a suffix for alternate invoices.
1853 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1860 my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1861 my $pdf = generate_pdf($file);
1863 unlink($barcodefile) if $barcodefile;
1868 =item print_html HASHREF | [ TIME [ , TEMPLATE [ , CID ] ] ]
1870 Returns an HTML invoice, as a scalar.
1872 I<time> an optional value used to control the printing of overdue messages. The
1873 default is now. It isn't the date of the invoice; that's the `_date' field.
1874 It is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1875 L<Time::Local> and L<Date::Parse> for conversion functions.
1877 I<template>, if specified, is the name of a suffix for alternate invoices.
1879 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1881 I<cid> is a MIME Content-ID used to create a "cid:" URL for the logo image, used
1882 when emailing the invoice as part of a multipart/related MIME email.
1890 %params = %{ shift() };
1894 $params{'format'} = 'html';
1896 $self->print_generic( %params );
1899 # quick subroutine for print_latex
1901 # There are ten characters that LaTeX treats as special characters, which
1902 # means that they do not simply typeset themselves:
1903 # # $ % & ~ _ ^ \ { }
1905 # TeX ignores blanks following an escaped character; if you want a blank (as
1906 # in "10% of ..."), you have to "escape" the blank as well ("10\%\ of ...").
1910 $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
1911 $value =~ s/([<>])/\$$1\$/g;
1917 encode_entities($value);
1921 sub _html_escape_nbsp {
1922 my $value = _html_escape(shift);
1923 $value =~ s/ +/ /g;
1927 #utility methods for print_*
1929 sub _translate_old_latex_format {
1930 warn "_translate_old_latex_format called\n"
1937 if ( $line =~ /^%%Detail\s*$/ ) {
1939 push @template, q![@--!,
1940 q! foreach my $_tr_line (@detail_items) {!,
1941 q! if ( scalar ($_tr_item->{'ext_description'} ) ) {!,
1942 q! $_tr_line->{'description'} .= !,
1943 q! "\\tabularnewline\n~~".!,
1944 q! join( "\\tabularnewline\n~~",!,
1945 q! @{$_tr_line->{'ext_description'}}!,
1949 while ( ( my $line_item_line = shift )
1950 !~ /^%%EndDetail\s*$/ ) {
1951 $line_item_line =~ s/'/\\'/g; # nice LTS
1952 $line_item_line =~ s/\\/\\\\/g; # escape quotes and backslashes
1953 $line_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1954 push @template, " \$OUT .= '$line_item_line';";
1957 push @template, '}',
1960 } elsif ( $line =~ /^%%TotalDetails\s*$/ ) {
1962 push @template, '[@--',
1963 ' foreach my $_tr_line (@total_items) {';
1965 while ( ( my $total_item_line = shift )
1966 !~ /^%%EndTotalDetails\s*$/ ) {
1967 $total_item_line =~ s/'/\\'/g; # nice LTS
1968 $total_item_line =~ s/\\/\\\\/g; # escape quotes and backslashes
1969 $total_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1970 push @template, " \$OUT .= '$total_item_line';";
1973 push @template, '}',
1977 $line =~ s/\$(\w+)/[\@-- \$$1 --\@]/g;
1978 push @template, $line;
1984 warn "$_\n" foreach @template;
1996 my $conf = $self->conf;
1998 #check for an invoice-specific override
1999 return $self->invoice_terms if $self->invoice_terms;
2001 #check for a customer- specific override
2002 my $cust_main = $self->cust_main;
2003 return $cust_main->invoice_terms if $cust_main && $cust_main->invoice_terms;
2007 $agentnum = $cust_main->agentnum;
2008 } elsif ( my $prospect_main = $self->prospect_main ) {
2009 $agentnum = $prospect_main->agentnum;
2012 #use configured default
2013 $conf->config('invoice_default_terms', $agentnum) || '';
2023 if ( $self->terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
2024 $duedate = $self->_date() + ( $1 * 86400 );
2025 } elsif ( $self->terms =~ /^End of Month$/ ) {
2026 my ($mon,$year) = (localtime($self->_date) )[4,5];
2028 until ( $mon < 12 ) { $mon -= 12; $year++; }
2029 my $nextmonth_first = timelocal(0,0,0,1,$mon,$year);
2030 $duedate = $nextmonth_first - 86400;
2041 $self->due_date ? $self->time2str_local(shift, $self->due_date) : '';
2044 =item invoice_pay_by_msg
2046 displays the invoice_pay_by_msg or default Please pay by [_1] if empty.
2050 sub invoice_pay_by_msg {
2054 $self->conf->config('invoice_pay_by_msg', $self->agentnum)
2055 || 'Please pay by [_1]';
2056 $msg .= ' - ' . $self->mt($please_pay_by, $self->due_date2str('short')) . ' ';
2061 =item balance_due_msg
2065 sub balance_due_msg {
2067 my $msg = $self->mt('Balance Due');
2068 return $msg unless $self->terms; # huh?
2069 if ( !$self->conf->exists('invoice_show_prior_due_date')
2070 || $self->has_sections ) {
2071 # if enabled, the due date is shown with Total New Charges (see
2072 # _items_total) and not here
2073 # (yes, or if invoice_sections is enabled; this is just for compatibility)
2074 if ( $self->due_date ) {
2075 $msg .= $self->invoice_pay_by_msg
2076 unless $self->conf->config_bool('invoice_omit_due_date',$self->agentnum);
2077 } elsif ( $self->terms ) {
2078 $msg .= ' - '. $self->mt($self->terms);
2084 =item balance_due_date
2088 sub balance_due_date {
2090 my $conf = $self->conf;
2092 my $terms = $self->terms;
2093 if ( $terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
2094 $duedate = $self->time2str_local('rdate', $self->_date + ($1*86400) );
2099 sub credit_balance_msg {
2101 $self->mt('Credit Balance Remaining')
2106 Returns a string with the date, for example: "3/20/2008", localized for the
2107 customer. Use _date_pretty_unlocalized for non-end-customer display use.
2113 $self->time2str_local('short', $self->_date);
2116 =item _date_pretty_unlocalized
2118 Returns a string with the date, for example: "3/20/2008", in the format
2119 configured for the back-office. Use _date_pretty for end-customer display use.
2123 sub _date_pretty_unlocalized {
2125 time2str($date_format, $self->_date);
2130 Emails this template.
2132 Options are passed as a hashref. Available options:
2138 If specified, overrides the default From: address.
2142 If specified, overrides the name of the sent document ("Invoice" or "Quotation")
2146 (Deprecated) If specified, is the name of a suffix for alternate template files.
2150 Options accepted by generate_email can also be used.
2156 my $opt = shift || {};
2157 if ($opt and !ref($opt)) {
2158 die ref($self). '->email called with positional parameters';
2161 return if $self->hide;
2163 my $error = send_email(
2164 $self->generate_email(
2165 'subject' => $self->email_subject($opt->{template}),
2166 %$opt, # template, etc.
2170 die "can't email: $error\n" if $error;
2173 =item generate_email OPTION => VALUE ...
2181 sender address, required
2185 alternate template name, optional
2189 email subject, optional
2193 notice name instead of "Invoice", optional
2197 Returns an argument list to be passed to L<FS::Misc/send_email>.
2204 sub generate_email {
2208 my $conf = $self->conf;
2210 my $me = '[FS::Template_Mixin::generate_email]';
2213 'from' => $args{'from'},
2214 'subject' => ($args{'subject'} || $self->email_subject),
2215 'custnum' => $self->custnum,
2216 'msgtype' => 'invoice',
2219 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
2221 my $cust_main = $self->cust_main;
2223 if (ref($args{'to'}) eq 'ARRAY') {
2224 $return{'to'} = $args{'to'};
2225 } elsif ( $cust_main ) {
2226 $return{'to'} = [ $cust_main->invoicing_list_emailonly ];
2229 my $tc = $self->template_conf;
2231 my @text; # array of lines
2232 my $html; # a big string
2233 my @related_parts; # will contain the text/HTML alternative, and images
2234 my $related; # will contain the multipart/related object
2236 if ( $conf->exists($tc. 'email_pdf') ) {
2237 if ( my $msgnum = $conf->config($tc.'email_pdf_msgnum') ) {
2239 warn "$me using '${tc}email_pdf_msgnum' in multipart message"
2242 my $msg_template = FS::msg_template->by_key($msgnum)
2243 or die "${tc}email_pdf_msgnum $msgnum not found\n";
2244 my $cust_msg = $msg_template->prepare(
2245 cust_main => $self->cust_main,
2247 msgtype => 'invoice',
2250 # XXX hack to make this work in the new cust_msg era; consider replacing
2251 # with cust_bill_send_with_notice events.
2252 my @parts = $cust_msg->parts;
2253 foreach my $part (@parts) { # will only have two parts, normally
2254 if ( $part->mime_type eq 'text/plain' ) {
2255 @text = @{ $part->body };
2256 } elsif ( $part->mime_type eq 'text/html' ) {
2257 $html = $part->bodyhandle->as_string;
2261 } elsif ( my @note = $conf->config($tc.'email_pdf_note') ) {
2263 warn "$me using '${tc}email_pdf_note' in multipart message"
2265 @text = $conf->config($tc.'email_pdf_note');
2266 $html = join('<BR>', @text);
2268 } # else use the plain text invoice
2273 if ( $conf->exists($tc.'template') ) {
2275 warn "$me generating plain text invoice"
2278 @text = $self->print_text(\%args);
2282 warn "$me no plain text version exists; sending empty message body"
2289 my $text_part = build MIME::Entity (
2290 'Type' => 'text/plain',
2291 'Encoding' => 'quoted-printable',
2292 'Charset' => 'UTF-8',
2293 #'Encoding' => '7bit',
2296 { Encode::encode('UTF-8', $_, Encode::FB_WARN | Encode::LEAVE_SRC ) }
2299 'Disposition' => 'inline',
2304 if ( $conf->exists($tc.'html') ) {
2305 warn "$me generating HTML invoice"
2308 $args{'from'} =~ /\@([\w\.\-]+)/;
2309 my $from = $1 || 'example.com';
2310 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
2313 my $agentnum = $cust_main ? $cust_main->agentnum
2314 : $self->prospect_main->agentnum;
2315 if ( defined($args{'template'}) && length($args{'template'})
2316 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
2319 $logo = 'logo_'. $args{'template'}. '.png';
2323 my $image_data = $conf->config_binary( $logo, $agentnum);
2325 push @related_parts, build MIME::Entity
2326 'Type' => 'image/png',
2327 'Encoding' => 'base64',
2328 'Data' => $image_data,
2329 'Filename' => 'logo.png',
2330 'Content-ID' => "<$content_id>",
2333 if ( ref($self) eq 'FS::cust_bill' && $conf->exists('invoice-barcode') ) {
2334 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
2335 push @related_parts, build MIME::Entity
2336 'Type' => 'image/png',
2337 'Encoding' => 'base64',
2338 'Data' => $self->invoice_barcode(0),
2339 'Filename' => 'barcode.png',
2340 'Content-ID' => "<$barcode_content_id>",
2342 $args{'barcode_cid'} = $barcode_content_id;
2345 $html = $self->print_html({ 'cid'=>$content_id, %args });
2352 warn "$me creating HTML/text multipart message"
2355 $return{'nobody'} = 1;
2357 my $alternative = build MIME::Entity
2358 'Type' => 'multipart/alternative',
2359 #'Encoding' => '7bit',
2360 'Disposition' => 'inline'
2364 $alternative->add_part($text_part);
2367 $alternative->attach(
2368 'Type' => 'text/html',
2369 'Encoding' => 'quoted-printable',
2370 'Data' => [ '<html>',
2373 ' '. encode_entities($return{'subject'}),
2376 ' <body bgcolor="#e8e8e8">',
2380 Encode::FB_WARN | Encode::LEAVE_SRC
2385 'Disposition' => 'inline',
2386 #'Filename' => 'invoice.pdf',
2389 unshift @related_parts, $alternative;
2391 $related = build MIME::Entity 'Type' => 'multipart/related',
2392 'Encoding' => '7bit';
2394 #false laziness w/Misc::send_email
2395 $related->head->replace('Content-type',
2396 $related->mime_type.
2397 '; boundary="'. $related->head->multipart_boundary. '"'.
2398 '; type=multipart/alternative'
2401 $related->add_part($_) foreach @related_parts;
2405 my @otherparts = ();
2406 if ( ref($self) eq 'FS::cust_bill' && $cust_main->email_csv_cdr ) {
2408 if ( $conf->config('voip-cdr_email_attach') eq 'zip' ) {
2410 my $data = join('', map "$_\n",
2411 $self->call_details(prepend_billed_number=>1)
2414 my $zip = new Archive::Zip;
2415 my $file = $zip->addString( $data, 'usage-'.$self->invnum.'.csv' );
2416 $file->desiredCompressionMethod( COMPRESSION_DEFLATED );
2419 my $SH = IO::Scalar->new(\$zipdata);
2420 my $status = $zip->writeToFileHandle($SH);
2421 die "Error zipping CDR attachment: $!" unless $status == AZ_OK;
2423 push @otherparts, build MIME::Entity
2424 'Type' => 'application/zip',
2425 'Encoding' => 'base64',
2427 'Disposition' => 'attachment',
2428 'Filename' => 'usage-'. $self->invnum. '.zip',
2431 } else { # } elsif ( $conf->config('voip-cdr_email_attach') eq 'csv' ) {
2433 push @otherparts, build MIME::Entity
2434 'Type' => 'text/csv',
2435 'Encoding' => '7bit',
2436 'Data' => [ map { "$_\n" }
2437 $self->call_details('prepend_billed_number' => 1)
2439 'Disposition' => 'attachment',
2440 'Filename' => 'usage-'. $self->invnum. '.csv',
2447 if ( $conf->exists($tc.'email_pdf') ) {
2452 # multipart/alternative
2458 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
2459 push @otherparts, $pdf;
2463 $return{'content-type'} = 'multipart/mixed'; # of the outer container
2465 $return{'mimeparts'} = [ $related, @otherparts ];
2466 $return{'type'} = 'multipart/related'; # of the first part
2468 $return{'mimeparts'} = [ $text_part, @otherparts ];
2469 $return{'type'} = 'text/plain';
2471 } elsif ( $html ) { # no PDF or CSV, strip the outer container
2472 $return{'mimeparts'} = \@related_parts;
2473 $return{'content-type'} = 'multipart/related';
2474 $return{'type'} = 'multipart/alternative';
2475 } else { # no HTML either
2476 $return{'body'} = \@text;
2477 $return{'content-type'} = 'text/plain';
2486 Returns a list suitable for passing to MIME::Entity->build(), representing
2487 this quotation or invoice as PDF attachment.
2494 'Type' => 'application/pdf',
2495 'Encoding' => 'base64',
2496 'Data' => [ $self->print_pdf(@_) ],
2497 'Disposition' => 'attachment',
2498 'Filename' => $self->pdf_filename,
2502 =item postal_mail_fsinc
2504 Sends this invoice to the Freeside Internet Services, Inc. print and mail
2510 use IO::Socket::SSL;
2512 use HTTP::Request::Common qw( POST );
2513 use Cpanel::JSON::XS;
2515 sub postal_mail_fsinc {
2516 my ( $self, %opt ) = @_;
2518 if ( $FS::Misc::DISABLE_PRINT ) {
2519 warn 'postal_mail_fsinc() disabled by $FS::Misc::DISABLE_PRINT' if $DEBUG;
2523 my $url = 'https://ws.freeside.biz/print';
2525 my $cust_main = $self->cust_main;
2526 my $agentnum = $cust_main->agentnum;
2527 my $bill_location = $cust_main->bill_location;
2529 die "Extra charges for international mailing; contact support\@freeside.biz to enable\n"
2530 if $bill_location->country ne 'US';
2532 my $conf = new FS::Conf;
2534 my @company_address = $conf->config('company_address', $agentnum);
2535 my ( $company_address1, $company_address2, $company_city, $company_state, $company_zip );
2536 if ( $company_address[2] =~ /^\s*(\S.*\S)\s*[\s,](\w\w),?\s*(\d{5}(-\d{4})?)\s*$/ ) {
2537 $company_address1 = $company_address[0];
2538 $company_address2 = $company_address[1];
2540 $company_state = $2;
2542 } elsif ( $company_address[1] =~ /^\s*(\S.*\S)\s*[\s,](\w\w),?\s*(\d{5}(-\d{4})?)\s*$/ ) {
2543 $company_address1 = $company_address[0];
2544 $company_address2 = '';
2546 $company_state = $2;
2549 die "Unparsable company_address; contact support\@freeside.biz\n";
2551 $company_city =~ s/,$//;
2553 my $file = $self->print_pdf(%opt, 'no_addresses' => 1);
2554 my $pages = CAM::PDF->new($file)->numPages;
2556 my $ua = LWP::UserAgent->new(
2558 verify_hostname => 0,
2559 SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
2560 SSL_version => 'SSLv3',
2563 my $response = $ua->request( POST $url, [
2564 'support-key' => scalar($conf->config('support-key')),
2565 'file' => encode_base64($file),
2569 'company_name' => scalar( $conf->config('company_name', $agentnum) ),
2570 'company_address1' => $company_address1,
2571 'company_address2' => $company_address2,
2572 'company_city' => $company_city,
2573 'company_state' => $company_state,
2574 'company_zip' => $company_zip,
2575 'company_country' => 'US',
2576 'company_phonenum' => scalar($conf->config('company_phonenum', $agentnum)),
2577 'company_email' => scalar($conf->config('invoice_from', $agentnum)),
2580 'name' => $cust_main->invoice_attn
2581 || $cust_main->contact_firstlast,
2582 'company' => $cust_main->company,
2583 'address1' => $bill_location->address1,
2584 'address2' => $bill_location->address2,
2585 'city' => $bill_location->city,
2586 'state' => $bill_location->state,
2587 'zip' => $bill_location->zip,
2588 'country' => $bill_location->country,
2591 die "Print connection error: ". $response->message.
2592 ' ('. $response->as_string. ")\n"
2593 unless $response->is_success;
2596 my $content = eval { decode_json($response->content) };
2597 die "Print JSON error : $@\n" if $@;
2599 die $content->{error}."\n"
2600 if $content->{error};
2602 #TODO: store this so we can query for a status later
2603 warn "Invoice printed, ID ". $content->{id}. "\n";
2609 =item _items_sections OPTIONS
2611 Generate section information for all items appearing on this invoice.
2612 This will only be called for multi-section invoices.
2614 For each line item (L<FS::cust_bill_pkg> record), this will fetch all
2615 related display records (L<FS::cust_bill_pkg_display>) and organize
2616 them into two groups ("early" and "late" according to whether they come
2617 before or after the total), then into sections. A subtotal is calculated
2620 Section descriptions are returned in sort weight order. Each consists
2621 of a hash containing:
2623 description: the package category name, escaped
2624 subtotal: the total charges in that section
2625 tax_section: a flag indicating that the section contains only tax charges
2626 summarized: same as tax_section, for some reason
2627 sort_weight: the package category's sort weight
2629 If 'condense' is set on the display record, it also contains everything
2630 returned from C<_condense_section()>, i.e. C<_condensed_foo_generator>
2631 coderefs to generate parts of the invoice. This is not advised.
2633 The method returns two arrayrefs, one of "early" sections and one of "late"
2636 OPTIONS may include:
2638 by_location: a flag to divide the invoice into sections by location.
2639 Each section hash will have a 'location' element containing a hashref of
2640 the location fields (see L<FS::cust_location>). The section description
2641 will be the location label, but the template can use any of the location
2642 fields to create a suitable label.
2644 by_category: a flag to divide the invoice into sections using display
2645 records (see L<FS::cust_bill_pkg_display>). This is the "traditional"
2646 behavior. Each section hash will have a 'category' element containing
2647 the section name from the display record (which probably equals the
2648 category name of the package, but may not in some cases).
2650 summary: a flag indicating that this is a summary-format invoice.
2651 Turning this on has the following effects:
2652 - Ignores display items with the 'summary' flag.
2653 - Places all sections in the "early" group even if they have post_total.
2654 - Creates sections for all non-disabled package categories, even if they
2655 have no charges on this invoice, as well as a section with no name.
2657 escape: an escape function to use for section titles.
2659 extra_sections: an arrayref of additional sections to return after the
2660 sorted list. If there are any of these, section subtotals exclude
2663 format: 'latex', 'html', or 'template' (i.e. text). Not used, but
2664 passed through to C<_condense_section()>.
2668 use vars qw(%pkg_category_cache);
2669 sub _items_sections {
2673 my $escape = $opt{escape};
2674 my @extra_sections = @{ $opt{extra_sections} || [] };
2676 # $subtotal{$locationnum}{$categoryname} = amount.
2677 # if we're not using by_location, $locationnum is undef.
2678 # if we're not using by_category, you guessed it, $categoryname is undef.
2679 # if we're not using either one, we shouldn't be here in the first place...
2681 my %late_subtotal = ();
2684 # About tax items + multisection invoices:
2685 # If either invoice_*summary option is enabled, AND there is a
2686 # package category with the name of the tax, then there will be
2687 # a display record assigning the tax item to that category.
2689 # However, the taxes are always placed in the "Taxes, Surcharges,
2690 # and Fees" section regardless of that. The only effect of the
2691 # display record is to create a subtotal for the summary page.
2694 my $pkg_hash = $self->cust_pkg_hash;
2696 foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2699 my $usage = $cust_bill_pkg->usage;
2702 if ( $opt{by_location} ) {
2703 if ( $cust_bill_pkg->pkgnum ) {
2704 $locationnum = $pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum;
2709 $locationnum = undef;
2712 # as in _items_cust_pkg, if a line item has no display records,
2713 # cust_bill_pkg_display() returns a default record for it
2715 foreach my $display ($cust_bill_pkg->cust_bill_pkg_display) {
2716 next if ( $display->summary && $opt{summary} );
2718 #my $section = $display->section;
2719 #false laziness with the method, but for efficiency inside this loop
2720 my $section = $display->get('section');
2721 if ( !$section && !$cust_bill_pkg->hidden ) {
2722 $section = $cust_bill_pkg->get('categoryname'); #cust_bill->cust_bill_pkg added it (XXX quotations / quotation_section)
2725 my $type = $display->type;
2726 # Set $section = undef if we're sectioning by location and this
2727 # line item _has_ a location (i.e. isn't a fee).
2728 $section = undef if $locationnum;
2730 # set this flag if the section is not tax-only
2731 $not_tax{$locationnum}{$section} = 1
2732 if $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart;
2734 # there's actually a very important piece of logic buried in here:
2735 # incrementing $late_subtotal{$section} CREATES
2736 # $late_subtotal{$section}. keys(%late_subtotal) is later used
2737 # to define the list of late sections, and likewise keys(%subtotal).
2738 # When _items_cust_bill_pkg is called to generate line items for
2739 # real, it will be called with 'section' => $section for each
2741 if ( $display->post_total && !$opt{summary} ) {
2742 if (! $type || $type eq 'S') {
2743 $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2744 if $cust_bill_pkg->setup != 0
2745 || $cust_bill_pkg->setup_show_zero;
2749 $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur
2750 if $cust_bill_pkg->recur != 0
2751 || $cust_bill_pkg->recur_show_zero;
2754 if ($type && $type eq 'R') {
2755 $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2756 if $cust_bill_pkg->recur != 0
2757 || $cust_bill_pkg->recur_show_zero;
2760 if ($type && $type eq 'U') {
2761 $late_subtotal{$locationnum}{$section} += $usage
2762 unless scalar(@extra_sections);
2765 } else { # it's a pre-total (normal) section
2767 # skip tax items unless they're explicitly included in a section
2768 next if $cust_bill_pkg->pkgnum == 0 and
2769 ! $cust_bill_pkg->feepart and
2772 if ( $type eq 'S' ) {
2773 $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2774 if $cust_bill_pkg->setup != 0
2775 || $cust_bill_pkg->setup_show_zero;
2776 } elsif ( $type eq 'R' ) {
2777 $subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2778 if $cust_bill_pkg->recur != 0
2779 || $cust_bill_pkg->recur_show_zero;
2780 } elsif ( $type eq 'U' ) {
2781 $subtotal{$locationnum}{$section} += $usage
2782 unless scalar(@extra_sections);
2783 } elsif ( !$type ) {
2784 $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2785 + $cust_bill_pkg->recur;
2794 %pkg_category_cache = ();
2796 # summary invoices need subtotals for all non-disabled package categories,
2797 # even if they're zero
2798 # but currently assume that there are no location sections, or at least
2799 # that the summary page doesn't care about them
2800 if ( $opt{summary} ) {
2801 foreach my $category (qsearch('pkg_category', {disabled => ''})) {
2802 $subtotal{''}{$category->categoryname} ||= 0;
2804 $subtotal{''}{''} ||= 0;
2808 foreach my $post_total (0,1) {
2810 my $s = $post_total ? \%late_subtotal : \%subtotal;
2811 foreach my $locationnum (keys %$s) {
2812 foreach my $sectionname (keys %{ $s->{$locationnum} }) {
2814 'subtotal' => $s->{$locationnum}{$sectionname},
2817 if ( $locationnum ) {
2818 $section->{'locationnum'} = $locationnum;
2819 my $location = FS::cust_location->by_key($locationnum);
2820 $section->{'description'} = &{ $escape }($location->location_label);
2821 # Better ideas? This will roughly group them by proximity,
2822 # which alpha sorting on any of the address fields won't.
2823 # Sorting by locationnum is meaningless.
2824 # We have to sort on _something_ or the order may change
2825 # randomly from one invoice to the next, which will confuse
2827 $section->{'sort_weight'} = sprintf('%012s',$location->zip) .
2829 $section->{'location'} = {
2830 label_prefix => &{ $escape }($location->label_prefix),
2831 map { $_ => &{ $escape }($location->get($_)) }
2835 $section->{'category'} = $sectionname;
2836 $section->{'description'} = &{ $escape }($sectionname);
2837 if ( _pkg_category($sectionname) ) {
2838 $section->{'sort_weight'} = _pkg_category($sectionname)->weight;
2839 if ( _pkg_category($sectionname)->condense ) {
2840 $section = { %$section, $self->_condense_section($opt{format}) };
2844 if ( !$post_total and !$not_tax{$locationnum}{$sectionname} ) {
2845 # then it's a tax-only section
2846 $section->{'summarized'} = 'Y';
2847 $section->{'tax_section'} = 'Y';
2849 push @these, $section;
2850 } # foreach $sectionname
2851 } #foreach $locationnum
2852 push @these, @extra_sections if $post_total == 0;
2853 # need an alpha sort for location sections, because postal codes can
2855 $sections[ $post_total ] = [ sort {
2856 $opt{'by_location'} ?
2857 ($a->{sort_weight} cmp $b->{sort_weight}) :
2858 ($a->{sort_weight} <=> $b->{sort_weight})
2860 } #foreach $post_total
2862 return @sections; # early, late
2865 #helper subs for above
2869 $self->{cust_pkg} ||= { map { $_->pkgnum => $_ } $self->cust_pkg };
2873 my $categoryname = shift;
2874 $pkg_category_cache{$categoryname} ||=
2875 qsearchs( 'pkg_category', { 'categoryname' => $categoryname } );
2878 my %condensed_format = (
2879 'label' => [ qw( Description Qty Amount ) ],
2881 sub { shift->{description} },
2882 sub { shift->{quantity} },
2883 sub { my($href, %opt) = @_;
2884 ($opt{dollar} || ''). $href->{amount};
2887 'align' => [ qw( l r r ) ],
2888 'span' => [ qw( 5 1 1 ) ], # unitprices?
2889 'width' => [ qw( 10.7cm 1.4cm 1.6cm ) ], # don't like this
2892 sub _condense_section {
2893 my ( $self, $format ) = ( shift, shift );
2895 map { my $method = "_condensed_$_"; $_ => $self->$method($format) }
2896 qw( description_generator
2899 total_line_generator
2904 sub _condensed_generator_defaults {
2905 my ( $self, $format ) = ( shift, shift );
2906 return ( \%condensed_format, ' ', ' ', ' ', sub { shift } );
2915 sub _condensed_header_generator {
2916 my ( $self, $format ) = ( shift, shift );
2918 my ( $f, $prefix, $suffix, $separator, $column ) =
2919 _condensed_generator_defaults($format);
2921 if ($format eq 'latex') {
2922 $prefix = "\\hline\n\\rule{0pt}{2.5ex}\n\\makebox[1.4cm]{}&\n";
2923 $suffix = "\\\\\n\\hline";
2926 sub { my ($d,$a,$s,$w) = @_;
2927 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2929 } elsif ( $format eq 'html' ) {
2930 $prefix = '<th></th>';
2934 sub { my ($d,$a,$s,$w) = @_;
2935 return qq!<th align="$html_align{$a}">$d</th>!;
2943 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
2945 &{$column}( map { $f->{$_}->[$i] } qw(label align span width) );
2948 $prefix. join($separator, @result). $suffix;
2953 sub _condensed_description_generator {
2954 my ( $self, $format ) = ( shift, shift );
2956 my ( $f, $prefix, $suffix, $separator, $column ) =
2957 _condensed_generator_defaults($format);
2959 my $money_char = '$';
2960 if ($format eq 'latex') {
2961 $prefix = "\\hline\n\\multicolumn{1}{c}{\\rule{0pt}{2.5ex}~} &\n";
2963 $separator = " & \n";
2965 sub { my ($d,$a,$s,$w) = @_;
2966 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2968 $money_char = '\\dollar';
2969 }elsif ( $format eq 'html' ) {
2970 $prefix = '"><td align="center"></td>';
2974 sub { my ($d,$a,$s,$w) = @_;
2975 return qq!<td align="$html_align{$a}">$d</td>!;
2977 #$money_char = $conf->config('money_char') || '$';
2978 $money_char = ''; # this is madness
2986 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
2988 $dollar = $money_char if $i == scalar(@{$f->{label}})-1;
2990 &{$column}( &{$f->{fields}->[$i]}($href, 'dollar' => $dollar),
2991 map { $f->{$_}->[$i] } qw(align span width)
2995 $prefix. join( $separator, @result ). $suffix;
3000 sub _condensed_total_generator {
3001 my ( $self, $format ) = ( shift, shift );
3003 my ( $f, $prefix, $suffix, $separator, $column ) =
3004 _condensed_generator_defaults($format);
3007 if ($format eq 'latex') {
3010 $separator = " & \n";
3012 sub { my ($d,$a,$s,$w) = @_;
3013 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
3015 }elsif ( $format eq 'html' ) {
3019 $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
3021 sub { my ($d,$a,$s,$w) = @_;
3022 return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
3031 # my $r = &{$f->{fields}->[$i]}(@args);
3032 # $r .= ' Total' unless $i;
3034 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
3036 &{$column}( &{$f->{fields}->[$i]}(@args). ($i ? '' : ' Total'),
3037 map { $f->{$_}->[$i] } qw(align span width)
3041 $prefix. join( $separator, @result ). $suffix;
3046 =item total_line_generator FORMAT
3048 Returns a coderef used for generation of invoice total line items for this
3049 usage_class. FORMAT is either html or latex
3053 # should not be used: will have issues with hash element names (description vs
3054 # total_item and amount vs total_amount -- another array of functions?
3056 sub _condensed_total_line_generator {
3057 my ( $self, $format ) = ( shift, shift );
3059 my ( $f, $prefix, $suffix, $separator, $column ) =
3060 _condensed_generator_defaults($format);
3063 if ($format eq 'latex') {
3066 $separator = " & \n";
3068 sub { my ($d,$a,$s,$w) = @_;
3069 return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
3071 }elsif ( $format eq 'html' ) {
3075 $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
3077 sub { my ($d,$a,$s,$w) = @_;
3078 return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
3087 foreach (my $i = 0; $f->{label}->[$i]; $i++) {
3089 &{$column}( &{$f->{fields}->[$i]}(@args),
3090 map { $f->{$_}->[$i] } qw(align span width)
3094 $prefix. join( $separator, @result ). $suffix;
3099 =item _items_pkg [ OPTIONS ]
3101 Return line item hashes for each package item on this invoice. Nearly
3104 $self->_items_cust_bill_pkg([ $self->cust_bill_pkg ])
3106 OPTIONS are passed through to _items_cust_bill_pkg, and should include
3107 'format' and 'escape_function' at minimum.
3109 To produce items for a specific invoice section, OPTIONS should include
3110 'section', a hashref containing 'category' and/or 'locationnum' keys.
3112 'section' may also contain a key named 'condensed'. If this is present
3113 and has a true value, _items_pkg will try to merge identical items into items
3114 with 'quantity' equal to the number of items (not the sum of their separate
3115 quantities, for some reason).
3121 # The order of these is important. Bundled line items will be merged into
3122 # the most recent non-hidden item, so it needs to be the one with:
3124 # - the same start date
3125 # - no pkgpart_override
3127 # So: sort by pkgnum,
3129 # then sort the base line item before any overrides
3130 # then sort hidden before non-hidden add-ons
3131 # then sort by override pkgpart (for consistency)
3132 sort { $a->pkgnum <=> $b->pkgnum or
3133 $a->sdate <=> $b->sdate or
3134 ($a->pkgpart_override ? 0 : -1) or
3135 ($b->pkgpart_override ? 0 : 1) or
3136 $b->hidden cmp $a->hidden or
3137 $a->pkgpart_override <=> $b->pkgpart_override
3139 # and of course exclude taxes and fees
3140 grep { $_->pkgnum > 0 } $self->cust_bill_pkg;
3146 my @cust_bill_pkg = grep { $_->feepart } $self->cust_bill_pkg;
3147 my $escape_function = $options{escape_function};
3149 my $locale = $self->cust_main
3150 ? $self->cust_main->locale
3151 : $self->prospect_main->locale;
3154 foreach my $cust_bill_pkg (@cust_bill_pkg) {
3155 # cache this, so we don't look it up again in every section
3156 my $part_fee = $cust_bill_pkg->get('part_fee')
3157 || $cust_bill_pkg->part_fee;
3158 $cust_bill_pkg->set('part_fee', $part_fee);
3160 #die "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n"; # might make more sense
3161 warn "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n";
3165 # If _items_fee is called while building a sectioned invoice,
3166 # - invoice_sections_method: category
3167 # Skip fee records that do not match the section category.
3168 # - invoice_sections_method: location
3169 # Skip fee records always for location sections.
3170 # The fee records will be presented in the tax/fee section instead.
3172 exists( $options{section} )
3176 exists( $options{section}{category} )
3178 $part_fee->categoryname ne $options{section}{category}
3181 exists( $options{section}{location})
3184 warn "skipping fee '".$part_fee->itemdesc.
3185 "'--not in section $options{section}{category}\n" if $DEBUG;
3190 my %base_invnums; # invnum => invoice date
3191 foreach ($cust_bill_pkg->cust_bill_pkg_fee) {
3192 if ($_->base_invnum) {
3193 my $base_bill = FS::cust_bill->by_key($_->base_invnum);
3194 my $base_date = $self->time2str_local('short', $base_bill->_date)
3196 $base_invnums{$_->base_invnum} = $base_date || '';
3199 foreach (sort keys(%base_invnums)) {
3200 next if $_ == $self->invnum;
3201 # per convention, we must escape ext_description lines
3203 &{$escape_function}(
3204 $self->mt('from invoice #[_1] on [_2]', $_, $base_invnums{$_})
3207 my $desc = $part_fee->itemdesc_locale($locale);
3208 # but not escape the base description line
3210 my @pkg_tax = $cust_bill_pkg->_pkg_tax_list
3211 if $options{section_with_taxes};
3214 { feepart => $cust_bill_pkg->feepart,
3215 billpkgnum => $cust_bill_pkg->billpkgnum,
3216 amount => sprintf('%.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
3217 description => $desc,
3218 pkg_tax => \@pkg_tax,
3219 ext_description => \@ext_desc,
3230 warn "$me _items_pkg searching for all package line items\n"
3233 my @cust_bill_pkg = $self->_items_nontax;
3235 warn "$me _items_pkg filtering line items\n"
3237 my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3239 if ($options{section} && $options{section}->{condensed}) {
3241 warn "$me _items_pkg condensing section\n"
3245 local $Storable::canonical = 1;
3246 foreach ( @items ) {
3248 delete $item->{ref};
3249 delete $item->{ext_description};
3250 my $key = freeze($item);
3251 $itemshash{$key} ||= 0;
3252 $itemshash{$key} ++; # += $item->{quantity};
3254 @items = sort { $a->{description} cmp $b->{description} }
3255 map { my $i = thaw($_);
3256 $i->{quantity} = $itemshash{$_};
3258 sprintf( "%.2f", $i->{quantity} * $i->{amount} );#unit_amount
3264 warn "$me _items_pkg returning ". scalar(@items). " items\n"
3271 return 0 unless $a->itemdesc cmp $b->itemdesc;
3272 return -1 if $b->itemdesc eq 'Tax';
3273 return 1 if $a->itemdesc eq 'Tax';
3274 return -1 if $b->itemdesc eq 'Other surcharges';
3275 return 1 if $a->itemdesc eq 'Other surcharges';
3276 $a->itemdesc cmp $b->itemdesc;
3281 my @cust_bill_pkg = sort _taxsort grep { ! $_->pkgnum and ! $_->feepart }
3282 $self->cust_bill_pkg;
3283 my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3285 if ( $self->conf->exists('always_show_tax') ) {
3286 my $itemdesc = $self->conf->config('always_show_tax') || 'Tax';
3287 if (0 == grep { $_->{description} eq $itemdesc } @items) {
3289 { 'description' => $itemdesc,
3296 =item _items_cust_bill_pkg CUST_BILL_PKGS OPTIONS
3298 Takes an arrayref of L<FS::cust_bill_pkg> objects, and returns a
3299 list of hashrefs describing the line items they generate on the invoice.
3301 OPTIONS may include:
3303 format: the invoice format.
3305 escape_function: the function used to escape strings.
3307 DEPRECATED? (expensive, mostly unused?)
3308 format_function: the function used to format CDRs.
3310 section: a hashref containing 'category' and/or 'locationnum'; if this
3311 is present, only returns line items that belong to that category and/or
3312 location (whichever is defined).
3314 multisection: a flag indicating that this is a multisection invoice,
3315 which does something complicated.
3317 section_with_taxes: Look up and include applied taxes for each record
3319 Returns a list of hashrefs, each of which may contain:
3321 pkgnum, description, amount, unit_amount, quantity, pkgpart, _is_setup, and
3322 ext_description, which is an arrayref of detail lines to show below
3327 sub _items_cust_bill_pkg {
3329 my $conf = $self->conf;
3330 my $cust_bill_pkgs = shift;
3333 my $format = $opt{format} || '';
3334 my $escape_function = $opt{escape_function} || sub { shift };
3335 my $format_function = $opt{format_function} || '';
3336 my $no_usage = $opt{no_usage} || '';
3337 my $unsquelched = $opt{unsquelched} || ''; #unused
3338 my ($section, $locationnum, $category);
3339 if ( $opt{section} ) {
3340 $category = $opt{section}->{category};
3341 $locationnum = $opt{section}->{locationnum};
3343 my $summary_page = $opt{summary_page} || ''; #unused
3344 my $multisection = defined($category) || defined($locationnum);
3345 # this variable is the value of the config setting, not whether it applies
3346 # to this particular line item.
3347 my $discount_show_always = $conf->exists('discount-show-always');
3349 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
3351 my $cust_main = $self->cust_main;#for per-agent cust_bill-line_item-ate_style
3353 my $agentnum = $self->agentnum;
3355 # for location labels: use default location on the invoice date
3356 my $default_locationnum;
3357 if ( $conf->exists('invoice-all_pkg_addresses') ) {
3358 $default_locationnum = 0; # treat them all as non-default
3359 } elsif ( $self->custnum ) {
3361 my @h_search = FS::h_cust_main->sql_h_search($self->_date);
3362 $h_cust_main = qsearchs({
3363 'table' => 'h_cust_main',
3364 'hashref' => { custnum => $self->custnum },
3365 'extra_sql' => $h_search[1],
3366 'addl_from' => $h_search[3],
3368 $default_locationnum = $h_cust_main->ship_locationnum;
3369 } elsif ( $self->prospectnum ) {
3370 my $cust_location = qsearchs('cust_location',
3371 { prospectnum => $self->prospectnum,
3373 $default_locationnum = $cust_location->locationnum if $cust_location;
3376 my @b = (); # accumulator for the line item hashes that we'll return
3377 my ($s, $r, $u, $d) = ( undef, undef, undef, undef );
3378 # the 'current' line item hashes for setup, recur, usage, discount
3379 foreach my $cust_bill_pkg ( @$cust_bill_pkgs )
3381 # if the current line item is waiting to go out, and the one we're about
3382 # to start is not bundled, then push out the current one and start a new
3385 $d->{amount} = $d->{setup_amount} + $d->{recur_amount};
3387 foreach ( $s, $r, ($opt{skip_usage} ? () : $u ), $d ) {
3388 if ( $_ && !$cust_bill_pkg->hidden ) {
3389 $_->{amount} = sprintf( "%.2f", $_->{amount} );
3390 $_->{amount} =~ s/^\-0\.00$/0.00/;
3391 if (exists($_->{unit_amount})) {
3392 $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} );
3395 # we already decided to create this display line; don't reconsider it
3397 # if $_->{amount} != 0
3398 # || $discount_show_always
3399 # || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
3400 # || ( $_->{_is_setup} && $_->{setup_show_zero} )
3406 if ( $locationnum ) {
3407 # this is a location section; skip packages that aren't at this
3409 next if $cust_bill_pkg->pkgnum == 0; # skips fees...
3410 next if $self->cust_pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum
3414 # Consider display records for this item to determine if it belongs
3415 # in this section. Note that if there are no display records, there
3416 # will be a default pseudo-record that includes all charge types
3417 # and has no section name.
3418 my @cust_bill_pkg_display = $cust_bill_pkg->can('cust_bill_pkg_display')
3419 ? $cust_bill_pkg->cust_bill_pkg_display
3420 : ( $cust_bill_pkg );
3422 warn "$me _items_cust_bill_pkg considering cust_bill_pkg ".
3423 $cust_bill_pkg->billpkgnum. ", pkgnum ". $cust_bill_pkg->pkgnum. "\n"
3426 if ( defined($category) ) {
3427 # then this is a package category section; process all display records
3428 # that belong to this section.
3429 @cust_bill_pkg_display = grep { $_->section eq $category }
3430 @cust_bill_pkg_display;
3432 # otherwise, process all display records that aren't usage summaries
3433 # (I don't think there should be usage summaries if you aren't using
3434 # category sections, but this is the historical behavior)
3435 @cust_bill_pkg_display = grep { !$_->summary }
3436 @cust_bill_pkg_display;
3439 my $classname = ''; # package class name, will fill in later
3441 foreach my $display (@cust_bill_pkg_display) {
3443 warn "$me _items_cust_bill_pkg considering cust_bill_pkg_display ".
3444 $display->billpkgdisplaynum. "\n"
3447 my $type = $display->type;
3449 my $desc = $cust_bill_pkg->desc( $cust_main ? $cust_main->locale : '' );
3450 $desc = substr($desc, 0, $maxlength). '...'
3451 if $format eq 'latex' && length($desc) > $maxlength;
3453 my %details_opt = ( 'format' => $format,
3454 'escape_function' => $escape_function,
3455 'format_function' => $format_function,
3456 'no_usage' => $opt{'no_usage'},
3459 if ( $cust_bill_pkg->pkgnum > 0 ) {
3460 # a "normal" package line item (not a quotation, not a fee, not a tax)
3462 warn "$me _items_cust_bill_pkg cust_bill_pkg is non-tax\n"
3465 my $cust_pkg = $cust_bill_pkg->cust_pkg;
3467 unless ( $cust_pkg ) {
3468 # There is no related row in cust_pkg for this cust_bill_pkg.pkgnum.
3469 # This invoice may have been broken by an unusual combination
3470 # of manually editing package dates, and aborted package changes
3471 # when the manually edited dates used are nonsensical.
3474 'cust_bill_pkg(billpkgnum:%s) '.
3475 'is missing related row in cust_pkg(pkgnum:%s)! '.
3476 'cust_bill(invnum:%s) is corrupted by bad database data, '.
3477 'and should be investigated',
3478 $cust_bill_pkg->billpkgnum,
3479 $cust_bill_pkg->pkgnum,
3480 $cust_bill_pkg->invnum;
3482 FS::Log->new('FS::cust_bill_pkg')->critical( $error );
3487 my $part_pkg = $cust_pkg->part_pkg;
3489 # which pkgpart to show for display purposes?
3490 my $pkgpart = $cust_bill_pkg->pkgpart_override || $cust_pkg->pkgpart;
3492 # start/end dates for invoice formats that do nonstandard
3494 my %item_dates = ();
3495 %item_dates = map { $_ => $cust_bill_pkg->$_ } ('sdate', 'edate')
3496 unless $part_pkg->option('disable_line_item_date_ranges',1);
3498 # not normally used, but pass this to the template anyway
3499 $classname = $part_pkg->classname;
3501 my @pkg_tax = $cust_bill_pkg->_pkg_tax_list
3502 if $opt{section_with_taxes};
3504 if ( (!$type || $type eq 'S')
3505 && ( $cust_bill_pkg->setup != 0
3506 || $cust_bill_pkg->setup_show_zero
3507 || ($discount_show_always and $cust_bill_pkg->unitsetup > 0)
3512 warn "$me _items_cust_bill_pkg adding setup\n"
3515 # append the word 'Setup' to the setup line if there's going to be
3516 # a recur line for the same package (i.e. not a one-time charge)
3518 my $description = $desc;
3519 $description .= ' Setup'
3520 if $cust_bill_pkg->recur != 0
3521 || ($discount_show_always and $cust_bill_pkg->unitrecur > 0)
3522 || $cust_bill_pkg->recur_show_zero;
3524 my $disable_date_ranges =
3525 $opt{disable_line_item_date_ranges}
3526 || $part_pkg->option('disable_line_item_date_ranges', 1);
3528 $description .= $cust_bill_pkg->time_period_pretty(
3531 disable_date_ranges => $disable_date_ranges,
3533 if $part_pkg->is_prepaid #for prepaid, "display the validity period
3534 # triggered by the recurring charge freq
3536 && $cust_bill_pkg->recur == 0
3537 && ! $cust_bill_pkg->recur_show_zero;
3540 my @svc_labels = ();
3543 unless ( $part_pkg->hide_svc_detail ) {
3545 # still pass the svc_label through to the template, even if
3546 # not displaying it as an ext_description
3547 @svc_labels = map &{$escape_function}($_),
3548 $cust_pkg->h_labels_short($self->_date,
3551 $self->conf->{locale},
3553 $svc_label = $svc_labels[0];
3557 unless ( $part_pkg->hide_svc_detail
3558 || $cust_bill_pkg->hidden )
3561 push @d, @svc_labels
3562 unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
3563 # show the location label if it's not the customer's default
3564 # location, and we're not grouping items by location already
3565 if ( $cust_pkg->locationnum != $default_locationnum
3566 and !defined($locationnum) ) {
3567 my $loc = $cust_pkg->location_label;
3568 $loc = substr($loc, 0, $maxlength). '...'
3569 if $format eq 'latex' && length($loc) > $maxlength;
3570 push @d, &{$escape_function}($loc);
3573 } #unless hiding service details
3575 push @d, $cust_bill_pkg->details(%details_opt)
3576 if $cust_bill_pkg->recur == 0;
3578 if ( $cust_bill_pkg->hidden ) {
3579 $s->{amount} += $cust_bill_pkg->setup;
3580 $s->{unit_amount} += $cust_bill_pkg->unitsetup;
3581 push @{ $s->{ext_description} }, @d;
3584 billpkgnum => $cust_bill_pkg->billpkgnum,
3586 description => $description,
3587 pkgpart => $pkgpart,
3588 pkgnum => $cust_bill_pkg->pkgnum,
3589 amount => $cust_bill_pkg->setup,
3590 setup_show_zero => $cust_bill_pkg->setup_show_zero,
3591 unit_amount => $cust_bill_pkg->unitsetup,
3592 quantity => $cust_bill_pkg->quantity,
3593 ext_description => \@d,
3594 svc_label => ($svc_label || ''),
3595 locationnum => $cust_pkg->locationnum, # sure, why not?
3596 pkg_tax => \@pkg_tax,
3602 # should we show a recur line?
3603 # if type eq 'S', then NO, because we've been told not to.
3604 # otherwise, show the recur line if:
3605 # - there's a recurring charge
3606 # - or recur_show_zero is on
3607 # - or there's a positive unitrecur (so it's been discounted to zero)
3608 # and discount-show-always is on
3609 if ( ( !$type || $type eq 'R' || $type eq 'U' )
3611 $cust_bill_pkg->recur != 0
3613 || ($discount_show_always and $cust_bill_pkg->unitrecur > 0)
3614 || $cust_bill_pkg->recur_show_zero
3619 warn "$me _items_cust_bill_pkg adding recur/usage\n"
3622 my $is_summary = $display->summary;
3623 my $description = $desc;
3624 if ( $type eq 'U' and defined($r) ) {
3625 # don't just show the same description as the recur line
3626 $description = $self->mt('Usage charges');
3629 my $disable_date_ranges =
3630 $opt{disable_line_item_date_ranges}
3631 || $part_pkg->option('disable_line_item_date_ranges', 1);
3633 $description .= $cust_bill_pkg->time_period_pretty(
3636 disable_date_ranges => $disable_date_ranges,
3640 my @seconds = (); # for display of usage info
3641 my @svc_labels = ();
3644 #at least until cust_bill_pkg has "past" ranges in addition to
3645 #the "future" sdate/edate ones... see #3032
3646 my @dates = ( $self->_date );
3647 my $prev = $cust_bill_pkg->previous_cust_bill_pkg;
3648 push @dates, $prev->sdate if $prev;
3649 push @dates, undef if !$prev;
3651 unless ( $part_pkg->hide_svc_detail ) {
3652 @svc_labels = map &{$escape_function}($_),
3653 $cust_pkg->h_labels_short(@dates,
3655 $self->conf->{locale});
3656 $svc_label = $svc_labels[0];
3659 # show service labels, unless...
3660 # the package is set not to display them
3661 unless ( $part_pkg->hide_svc_detail
3662 # or this is a tax-like line item
3663 || $cust_bill_pkg->itemdesc
3664 # or this is a hidden (bundled) line item
3665 || $cust_bill_pkg->hidden
3666 # or this is a usage summary line
3667 || $is_summary && $type && $type eq 'U'
3668 # or this is a usage line and there's a recurring line
3669 # for the package in the same section (which will
3670 # have service labels already)
3671 || ($type eq 'U' and defined($r))
3675 warn "$me _items_cust_bill_pkg adding service details\n"
3678 push @d, @svc_labels
3679 unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
3680 warn "$me _items_cust_bill_pkg done adding service details\n"
3683 # show the location label if it's not the customer's default
3684 # location, and we're not grouping items by location already
3685 if ( $cust_pkg->locationnum != $default_locationnum
3686 and !defined($locationnum) ) {
3687 my $loc = $cust_pkg->location_label;
3688 $loc = substr($loc, 0, $maxlength). '...'
3689 if $format eq 'latex' && length($loc) > $maxlength;
3690 push @d, &{$escape_function}($loc);
3693 # Display of seconds_since_sqlradacct:
3694 # On the invoice, when processing @detail_items, look for a field
3695 # named 'seconds'. This will contain total seconds for each
3696 # service, in the same order as @ext_description. For services
3697 # that don't support this it will show undef.
3698 if ( $conf->exists('svc_acct-usage_seconds')
3699 and ! $cust_bill_pkg->pkgpart_override ) {
3700 foreach my $cust_svc (
3701 $cust_pkg->h_cust_svc(@dates, 'I')
3704 # eval because not having any part_export_usage exports
3705 # is a fatal error, last_bill/_date because that's how
3706 # sqlradius_hour billing does it
3708 $cust_svc->seconds_since_sqlradacct($dates[1] || 0, $dates[0]);
3710 push @seconds, $sec;
3712 } #if svc_acct-usage_seconds
3714 } # if we are showing service labels
3716 unless ( $is_summary ) {
3717 warn "$me _items_cust_bill_pkg adding details\n"
3720 #instead of omitting details entirely in this case (unwanted side
3721 # effects), just omit CDRs
3722 $details_opt{'no_usage'} = 1
3723 if $type && $type eq 'R';
3725 push @d, $cust_bill_pkg->details(%details_opt);
3728 warn "$me _items_cust_bill_pkg calculating amount\n"
3733 $amount = $cust_bill_pkg->recur;
3734 } elsif ($type eq 'R') {
3735 $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
3736 } elsif ($type eq 'U') {
3737 $amount = $cust_bill_pkg->usage;
3740 if ( !$type || $type eq 'R' ) {
3742 warn "$me _items_cust_bill_pkg adding recur\n"
3746 ( $cust_bill_pkg->unitrecur > 0 ) ? $cust_bill_pkg->unitrecur
3749 if ( $cust_bill_pkg->hidden ) {
3750 $r->{amount} += $amount;
3751 $r->{unit_amount} += $unit_amount;
3752 push @{ $r->{ext_description} }, @d;
3755 billpkgnum => $cust_bill_pkg->billpkgnum,
3756 description => $description,
3757 pkgpart => $pkgpart,
3758 pkgnum => $cust_bill_pkg->pkgnum,
3760 recur_show_zero => $cust_bill_pkg->recur_show_zero,
3761 unit_amount => $unit_amount,
3762 quantity => $cust_bill_pkg->quantity,
3764 ext_description => \@d,
3765 svc_label => ($svc_label || ''),
3766 locationnum => $cust_pkg->locationnum,
3767 pkg_tax => \@pkg_tax,
3769 $r->{'seconds'} = \@seconds if grep {defined $_} @seconds;
3772 } else { # $type eq 'U'
3774 warn "$me _items_cust_bill_pkg adding usage\n"
3777 if ( $cust_bill_pkg->hidden and defined($u) ) {
3778 # if this is a hidden package and there's already a usage
3779 # line for the bundle, add this package's total amount and
3780 # usage details to it
3781 $u->{amount} += $amount;
3782 push @{ $u->{ext_description} }, @d;
3783 } elsif ( $amount ) {
3784 # create a new usage line
3786 billpkgnum => $cust_bill_pkg->billpkgnum,
3787 description => $description,
3788 pkgpart => $pkgpart,
3789 pkgnum => $cust_bill_pkg->pkgnum,
3792 recur_show_zero => $cust_bill_pkg->recur_show_zero,
3794 ext_description => \@d,
3795 locationnum => $cust_pkg->locationnum,
3796 pkg_tax => \@pkg_tax,
3798 } # else this has no usage, so don't create a usage section
3801 } # recurring or usage with recurring charge
3803 } else { # taxes and fees
3805 warn "$me _items_cust_bill_pkg cust_bill_pkg is tax\n"
3808 # items of this kind should normally not have sdate/edate.
3810 'description' => $desc,
3811 'amount' => sprintf('%.2f', $cust_bill_pkg->setup
3812 + $cust_bill_pkg->recur)
3815 } # if package line item / other line item
3817 # decide whether to show active discounts here
3819 # case 1: we are showing a single line for the package
3821 # case 2: we are showing a setup line for a package that has
3822 # no base recurring fee
3823 or ( $type eq 'S' and $cust_bill_pkg->unitrecur == 0 )
3824 # case 3: we are showing a recur line for a package that has
3825 # a base recurring fee
3826 or ( $type eq 'R' and $cust_bill_pkg->unitrecur > 0 )
3829 my $item_discount = $cust_bill_pkg->_item_discount;
3830 if ( $item_discount ) {
3831 # $item_discount->{amount} is negative
3833 if ( $d and $cust_bill_pkg->hidden ) {
3834 $d->{setup_amount} += $item_discount->{setup_amount};
3835 $d->{recur_amount} += $item_discount->{recur_amount};
3837 $d = $item_discount;
3838 $_ = &{$escape_function}($_) foreach @{ $d->{ext_description} };
3841 # update the active line (before the discount) to show the
3842 # original price (whether this is a hidden line or not)
3844 $s->{amount} -= $item_discount->{setup_amount} if $s;
3845 $r->{amount} -= $item_discount->{recur_amount} if $r;
3847 } # if there are any discounts
3848 } # if this is an appropriate place to show discounts
3850 } # foreach $display
3854 # discount amount is internally split up
3856 $d->{amount} = $d->{setup_amount} + $d->{recur_amount};
3859 foreach ( $s, $r, ($opt{skip_usage} ? () : $u ), $d ) {
3861 $_->{amount} = sprintf( "%.2f", $_->{amount} ),
3862 if exists($_->{amount});
3863 $_->{amount} =~ s/^\-0\.00$/0.00/;
3864 if (exists($_->{unit_amount})) {
3865 $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} );
3869 #if $_->{amount} != 0
3870 # || $discount_show_always
3871 # || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
3872 # || ( $_->{_is_setup} && $_->{setup_show_zero} )
3876 warn "$me _items_cust_bill_pkg done considering cust_bill_pkgs\n"
3883 =item _items_discounts_avail
3885 Returns an array of line item hashrefs representing available term discounts
3886 for this invoice. This makes the same assumptions that apply to term
3887 discounts in general: that the package is billed monthly, at a flat rate,
3888 with no usage charges. A prorated first month will be handled, as will
3889 a setup fee if the discount is allowed to apply to setup fees.
3893 sub _items_discounts_avail {
3896 #maybe move this method from cust_bill when quotations support discount_plans
3897 return () unless $self->can('discount_plans');
3898 my %plans = $self->discount_plans;
3900 my $list_pkgnums = 0; # if any packages are not eligible for all discounts
3901 $list_pkgnums = grep { $_->list_pkgnums } values %plans;
3905 my $plan = $plans{$months};
3907 my $term_total = sprintf('%.2f', $plan->discounted_total);
3908 my $percent = sprintf('%.0f',
3909 100 * (1 - $term_total / $plan->base_total) );
3910 my $permonth = sprintf('%.2f', $term_total / $months);
3911 my $detail = $self->mt('discount on item'). ' '.
3912 join(', ', map { "#$_" } $plan->pkgnums)
3915 # discounts for non-integer months don't work anyway
3916 $months = sprintf("%d", $months);
3919 description => $self->mt('Save [_1]% by paying for [_2] months',
3921 amount => $self->mt('[_1] ([_2] per month)',
3922 $term_total, $money_char.$permonth),
3923 ext_description => ($detail || ''),
3926 sort { $b <=> $a } keys %plans;
3930 =item has_sections AGENTNUM
3932 Return true if invoice_sections should be enabled for this bill.
3933 (Inherited by both cust_bill and cust_bill_void)
3936 * False if not an invoice
3937 * True always if conf invoice_sections is enabled
3938 * True always if sections_by_location is enabled
3939 * True if conf invoice_sections_multilocation > 1,
3940 and location_count >= invoice_sections_multilocation
3946 my ($self, $agentnum) = @_;
3948 return 0 unless $self->invnum > 0;
3950 $agentnum ||= $self->agentnum;
3951 return 1 if $self->conf->config_bool('invoice_sections', $agentnum);
3952 return 1 if $self->conf->exists('sections_by_location', $agentnum);
3954 my $location_min = $self->conf->config(
3955 'invoice_sections_multilocation', $agentnum,
3960 && $self->location_count >= $location_min;
3966 =item location_count
3968 Return the number of locations billed on this invoice
3972 sub location_count {
3974 return 0 unless $self->invnum;
3976 # SELECT COUNT( DISTINCT cust_pkg.locationnum )
3977 # FROM cust_bill_pkg
3978 # LEFT JOIN cust_pkg USING (pkgnum)
3979 # WHERE invnum = 278
3980 # AND cust_bill_pkg.pkgnum > 0
3982 my $result = qsearchs({
3983 select => 'COUNT(DISTINCT cust_pkg.locationnum) as location_count',
3984 table => 'cust_bill_pkg',
3985 addl_from => 'LEFT JOIN cust_pkg USING (pkgnum)',
3986 extra_sql => 'WHERE invnum = '.dbh->quote( $self->invnum )
3987 . ' AND cust_bill_pkg.pkgnum > 0'
3989 ref $result ? $result->location_count : 0;