2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $DEBUG $me );
7 use Fcntl qw(:flock); #for spool_csv
9 use List::Util qw(min max sum);
13 use Storable qw( freeze thaw );
15 use FS::UID qw( datasrc );
16 use FS::Misc qw( send_email send_fax do_print );
17 use FS::Record qw( qsearch qsearchs dbh );
18 use FS::cust_statement;
19 use FS::cust_bill_pkg;
20 use FS::cust_bill_pkg_display;
21 use FS::cust_bill_pkg_detail;
25 use FS::cust_credit_bill;
27 use FS::cust_bill_event;
30 use FS::cust_bill_pay;
31 use FS::part_bill_event;
34 use FS::cust_bill_batch;
35 use FS::cust_bill_pay_pkg;
36 use FS::cust_credit_bill_pkg;
37 use FS::discount_plan;
38 use FS::cust_bill_void;
42 $me = '[FS::cust_bill]';
46 FS::cust_bill - Object methods for cust_bill records
52 $record = new FS::cust_bill \%hash;
53 $record = new FS::cust_bill { 'column' => 'value' };
55 $error = $record->insert;
57 $error = $new_record->replace($old_record);
59 $error = $record->delete;
61 $error = $record->check;
63 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
65 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
67 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
69 @cust_pay_objects = $cust_bill->cust_pay;
71 $tax_amount = $record->tax;
73 @lines = $cust_bill->print_text;
74 @lines = $cust_bill->print_text('time' => $time);
78 An FS::cust_bill object represents an invoice; a declaration that a customer
79 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
80 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
81 following fields are currently supported:
87 =item invnum - primary key (assigned automatically for new invoices)
89 =item custnum - customer (see L<FS::cust_main>)
91 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
92 L<Time::Local> and L<Date::Parse> for conversion functions.
94 =item charged - amount of this invoice
96 =item invoice_terms - optional terms override for this specific invoice
100 Customer info at invoice generation time
104 =item billing_balance - the customer's balance at the time the invoice was
105 generated (not including charges on this invoice)
107 =item previous_balance - the billing_balance of this customer's previous
108 invoice plus the charges on that invoice
116 =item printed - deprecated
124 =item closed - books closed flag, empty or `Y'
126 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
128 =item agent_invid - legacy invoice number
130 =item promised_date - customer promised payment date, for collection
140 Creates a new invoice. To add the invoice to the database, see L<"insert">.
141 Invoices are normally created by calling the bill method of a customer object
142 (see L<FS::cust_main>).
146 sub table { 'cust_bill'; }
148 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
149 # (except email_subject and invnum_date_pretty)
152 $self->conf->config('notice_name') || 'Invoice'
155 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
156 sub cust_unlinked_msg {
158 "WARNING: can't find cust_main.custnum ". $self->custnum.
159 ' (cust_bill.invnum '. $self->invnum. ')';
164 Adds this invoice to the database ("Posts" the invoice). If there is an error,
165 returns the error, otherwise returns false.
171 warn "$me insert called\n" if $DEBUG;
173 local $SIG{HUP} = 'IGNORE';
174 local $SIG{INT} = 'IGNORE';
175 local $SIG{QUIT} = 'IGNORE';
176 local $SIG{TERM} = 'IGNORE';
177 local $SIG{TSTP} = 'IGNORE';
178 local $SIG{PIPE} = 'IGNORE';
180 my $oldAutoCommit = $FS::UID::AutoCommit;
181 local $FS::UID::AutoCommit = 0;
184 my $error = $self->SUPER::insert;
186 $dbh->rollback if $oldAutoCommit;
190 if ( $self->get('cust_bill_pkg') ) {
191 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
192 $cust_bill_pkg->invnum($self->invnum);
193 my $error = $cust_bill_pkg->insert;
195 $dbh->rollback if $oldAutoCommit;
196 return "can't create invoice line item: $error";
201 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
208 Voids this invoice: deletes the invoice and adds a record of the voided invoice
209 to the FS::cust_bill_void table (and related tables starting from
210 FS::cust_bill_pkg_void).
216 my $reason = scalar(@_) ? shift : '';
218 local $SIG{HUP} = 'IGNORE';
219 local $SIG{INT} = 'IGNORE';
220 local $SIG{QUIT} = 'IGNORE';
221 local $SIG{TERM} = 'IGNORE';
222 local $SIG{TSTP} = 'IGNORE';
223 local $SIG{PIPE} = 'IGNORE';
225 my $oldAutoCommit = $FS::UID::AutoCommit;
226 local $FS::UID::AutoCommit = 0;
229 my $cust_bill_void = new FS::cust_bill_void ( {
230 map { $_ => $self->get($_) } $self->fields
232 $cust_bill_void->reason($reason);
233 my $error = $cust_bill_void->insert;
235 $dbh->rollback if $oldAutoCommit;
239 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
240 my $error = $cust_bill_pkg->void($reason);
242 $dbh->rollback if $oldAutoCommit;
247 $error = $self->delete;
249 $dbh->rollback if $oldAutoCommit;
253 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
261 This method now works but you probably shouldn't use it. Instead, apply a
262 credit against the invoice, or use the new void method.
264 Using this method to delete invoices outright is really, really bad. There
265 would be no record you ever posted this invoice, and there are no check to
266 make sure charged = 0 or that there are no associated cust_bill_pkg records.
268 Really, don't use it.
274 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
276 local $SIG{HUP} = 'IGNORE';
277 local $SIG{INT} = 'IGNORE';
278 local $SIG{QUIT} = 'IGNORE';
279 local $SIG{TERM} = 'IGNORE';
280 local $SIG{TSTP} = 'IGNORE';
281 local $SIG{PIPE} = 'IGNORE';
283 my $oldAutoCommit = $FS::UID::AutoCommit;
284 local $FS::UID::AutoCommit = 0;
287 foreach my $table (qw(
298 foreach my $linked ( $self->$table() ) {
299 my $error = $linked->delete;
301 $dbh->rollback if $oldAutoCommit;
308 my $error = $self->SUPER::delete(@_);
310 $dbh->rollback if $oldAutoCommit;
314 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
320 =item replace [ OLD_RECORD ]
322 You can, but probably shouldn't modify invoices...
324 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
325 supplied, replaces this record. If there is an error, returns the error,
326 otherwise returns false.
330 #replace can be inherited from Record.pm
332 # replace_check is now the preferred way to #implement replace data checks
333 # (so $object->replace() works without an argument)
336 my( $new, $old ) = ( shift, shift );
337 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
338 #return "Can't change _date!" unless $old->_date eq $new->_date;
339 return "Can't change _date" unless $old->_date == $new->_date;
340 return "Can't change charged" unless $old->charged == $new->charged
341 || $old->charged == 0
342 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
348 =item add_cc_surcharge
354 sub add_cc_surcharge {
355 my ($self, $pkgnum, $amount) = (shift, shift, shift);
358 my $cust_bill_pkg = new FS::cust_bill_pkg({
359 'invnum' => $self->invnum,
363 $error = $cust_bill_pkg->insert;
364 return $error if $error;
366 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
367 $self->charged($self->charged+$amount);
368 $error = $self->replace;
369 return $error if $error;
371 $self->apply_payments_and_credits;
377 Checks all fields to make sure this is a valid invoice. If there is an error,
378 returns the error, otherwise returns false. Called by the insert and replace
387 $self->ut_numbern('invnum')
388 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
389 || $self->ut_numbern('_date')
390 || $self->ut_money('charged')
391 || $self->ut_numbern('printed')
392 || $self->ut_enum('closed', [ '', 'Y' ])
393 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
394 || $self->ut_numbern('agent_invid') #varchar?
396 return $error if $error;
398 $self->_date(time) unless $self->_date;
400 $self->printed(0) if $self->printed eq '';
407 Returns the displayed invoice number for this invoice: agent_invid if
408 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
414 if ( $self->agent_invid
415 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
416 return $self->agent_invid;
418 return $self->invnum;
424 Returns the customer's last invoice before this one.
430 if ( !$self->get('previous_bill') ) {
431 $self->set('previous_bill', qsearchs({
432 'table' => 'cust_bill',
433 'hashref' => { 'custnum' => $self->custnum,
434 '_date' => { op=>'<', value=>$self->_date } },
435 'order_by' => 'ORDER BY _date DESC LIMIT 1',
438 $self->get('previous_bill');
443 Returns a list consisting of the total previous balance for this customer,
444 followed by the previous outstanding invoices (as FS::cust_bill objects also).
451 my @cust_bill = sort { $a->_date <=> $b->_date }
452 grep { $_->owed != 0 }
453 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
454 #'_date' => { op=>'<', value=>$self->_date },
455 'invnum' => { op=>'<', value=>$self->invnum },
458 foreach ( @cust_bill ) { $total += $_->owed; }
462 =item enable_previous
464 Whether to show the 'Previous Charges' section when printing this invoice.
465 The negation of the 'disable_previous_balance' config setting.
469 sub enable_previous {
471 my $agentnum = $self->cust_main->agentnum;
472 !$self->conf->exists('disable_previous_balance', $agentnum);
477 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
484 { 'table' => 'cust_bill_pkg',
485 'hashref' => { 'invnum' => $self->invnum },
486 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
487 # the AUTLOADED FK search. or should
488 # that default to ORDER by the pkey?
493 =item cust_bill_pkg_pkgnum PKGNUM
495 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
500 sub cust_bill_pkg_pkgnum {
501 my( $self, $pkgnum ) = @_;
503 { 'table' => 'cust_bill_pkg',
504 'hashref' => { 'invnum' => $self->invnum,
507 'order_by' => 'ORDER BY billpkgnum',
514 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
521 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
522 $self->cust_bill_pkg;
524 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
529 Returns true if any of the packages (or their definitions) corresponding to the
530 line items for this invoice have the no_auto flag set.
536 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
539 =item open_cust_bill_pkg
541 Returns the open line items for this invoice.
543 Note that cust_bill_pkg with both setup and recur fees are returned as two
544 separate line items, each with only one fee.
548 # modeled after cust_main::open_cust_bill
549 sub open_cust_bill_pkg {
552 # grep { $_->owed > 0 } $self->cust_bill_pkg
554 my %other = ( 'recur' => 'setup',
555 'setup' => 'recur', );
557 foreach my $field ( qw( recur setup )) {
558 push @open, map { $_->set( $other{$field}, 0 ); $_; }
559 grep { $_->owed($field) > 0 }
560 $self->cust_bill_pkg;
566 =item cust_bill_event
568 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
572 sub cust_bill_event {
574 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
577 =item num_cust_bill_event
579 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
583 sub num_cust_bill_event {
586 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
587 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
588 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
589 $sth->fetchrow_arrayref->[0];
594 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
598 #false laziness w/cust_pkg.pm
602 'table' => 'cust_event',
603 'addl_from' => 'JOIN part_event USING ( eventpart )',
604 'hashref' => { 'tablenum' => $self->invnum },
605 'extra_sql' => " AND eventtable = 'cust_bill' ",
611 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
615 #false laziness w/cust_pkg.pm
619 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
620 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
621 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
622 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
623 $sth->fetchrow_arrayref->[0];
628 Returns the customer (see L<FS::cust_main>) for this invoice.
630 =item cust_suspend_if_balance_over AMOUNT
632 Suspends the customer associated with this invoice if the total amount owed on
633 this invoice and all older invoices is greater than the specified amount.
635 Returns a list: an empty list on success or a list of errors.
639 sub cust_suspend_if_balance_over {
640 my( $self, $amount ) = ( shift, shift );
641 my $cust_main = $self->cust_main;
642 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
645 $cust_main->suspend(@_);
651 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
657 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
658 sort { $a->_date <=> $b->_date }
659 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
664 =item cust_credit_bill
666 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
672 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
673 sort { $a->_date <=> $b->_date }
674 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
678 sub cust_credit_bill {
679 shift->cust_credited(@_);
682 #=item cust_bill_pay_pkgnum PKGNUM
684 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
685 #with matching pkgnum.
689 #sub cust_bill_pay_pkgnum {
690 # my( $self, $pkgnum ) = @_;
691 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
692 # sort { $a->_date <=> $b->_date }
693 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
694 # 'pkgnum' => $pkgnum,
699 =item cust_bill_pay_pkg PKGNUM
701 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
702 applied against the matching pkgnum.
706 sub cust_bill_pay_pkg {
707 my( $self, $pkgnum ) = @_;
710 'select' => 'cust_bill_pay_pkg.*',
711 'table' => 'cust_bill_pay_pkg',
712 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
713 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
714 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
715 " AND cust_bill_pkg.pkgnum = $pkgnum",
720 #=item cust_credited_pkgnum PKGNUM
722 #=item cust_credit_bill_pkgnum PKGNUM
724 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
725 #with matching pkgnum.
729 #sub cust_credited_pkgnum {
730 # my( $self, $pkgnum ) = @_;
731 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
732 # sort { $a->_date <=> $b->_date }
733 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
734 # 'pkgnum' => $pkgnum,
739 #sub cust_credit_bill_pkgnum {
740 # shift->cust_credited_pkgnum(@_);
743 =item cust_credit_bill_pkg PKGNUM
745 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
746 applied against the matching pkgnum.
750 sub cust_credit_bill_pkg {
751 my( $self, $pkgnum ) = @_;
754 'select' => 'cust_credit_bill_pkg.*',
755 'table' => 'cust_credit_bill_pkg',
756 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
757 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
758 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
759 " AND cust_bill_pkg.pkgnum = $pkgnum",
764 =item cust_bill_batch
766 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
770 sub cust_bill_batch {
772 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
777 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
778 hash keyed by term length.
784 FS::discount_plan->all($self);
789 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
796 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
798 foreach (@taxlines) { $total += $_->setup; }
804 Returns the amount owed (still outstanding) on this invoice, which is charged
805 minus all payment applications (see L<FS::cust_bill_pay>) and credit
806 applications (see L<FS::cust_credit_bill>).
812 my $balance = $self->charged;
813 $balance -= $_->amount foreach ( $self->cust_bill_pay );
814 $balance -= $_->amount foreach ( $self->cust_credited );
815 $balance = sprintf( "%.2f", $balance);
816 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
821 my( $self, $pkgnum ) = @_;
823 #my $balance = $self->charged;
825 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
827 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
828 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
830 $balance = sprintf( "%.2f", $balance);
831 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
837 Returns true if this invoice should be hidden. See the
838 selfservice-hide_invoices-taxclass configuraiton setting.
844 my $conf = $self->conf;
845 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
847 my @cust_bill_pkg = $self->cust_bill_pkg;
848 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
849 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
852 =item apply_payments_and_credits [ OPTION => VALUE ... ]
854 Applies unapplied payments and credits to this invoice.
856 A hash of optional arguments may be passed. Currently "manual" is supported.
857 If true, a payment receipt is sent instead of a statement when
858 'payment_receipt_email' configuration option is set.
860 If there is an error, returns the error, otherwise returns false.
864 sub apply_payments_and_credits {
865 my( $self, %options ) = @_;
866 my $conf = $self->conf;
868 local $SIG{HUP} = 'IGNORE';
869 local $SIG{INT} = 'IGNORE';
870 local $SIG{QUIT} = 'IGNORE';
871 local $SIG{TERM} = 'IGNORE';
872 local $SIG{TSTP} = 'IGNORE';
873 local $SIG{PIPE} = 'IGNORE';
875 my $oldAutoCommit = $FS::UID::AutoCommit;
876 local $FS::UID::AutoCommit = 0;
879 $self->select_for_update; #mutex
881 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
882 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
884 if ( $conf->exists('pkg-balances') ) {
885 # limit @payments & @credits to those w/ a pkgnum grepped from $self
886 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
887 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
888 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
891 while ( $self->owed > 0 and ( @payments || @credits ) ) {
894 if ( @payments && @credits ) {
896 #decide which goes first by weight of top (unapplied) line item
898 my @open_lineitems = $self->open_cust_bill_pkg;
901 max( map { $_->part_pkg->pay_weight || 0 }
906 my $max_credit_weight =
907 max( map { $_->part_pkg->credit_weight || 0 }
913 #if both are the same... payments first? it has to be something
914 if ( $max_pay_weight >= $max_credit_weight ) {
920 } elsif ( @payments ) {
922 } elsif ( @credits ) {
925 die "guru meditation #12 and 35";
929 if ( $app eq 'pay' ) {
931 my $payment = shift @payments;
932 $unapp_amount = $payment->unapplied;
933 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
934 $app->pkgnum( $payment->pkgnum )
935 if $conf->exists('pkg-balances') && $payment->pkgnum;
937 } elsif ( $app eq 'credit' ) {
939 my $credit = shift @credits;
940 $unapp_amount = $credit->credited;
941 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
942 $app->pkgnum( $credit->pkgnum )
943 if $conf->exists('pkg-balances') && $credit->pkgnum;
946 die "guru meditation #12 and 35";
950 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
951 warn "owed_pkgnum ". $app->pkgnum;
952 $owed = $self->owed_pkgnum($app->pkgnum);
956 next unless $owed > 0;
958 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
959 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
961 $app->invnum( $self->invnum );
963 my $error = $app->insert(%options);
965 $dbh->rollback if $oldAutoCommit;
966 return "Error inserting ". $app->table. " record: $error";
968 die $error if $error;
972 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
977 =item generate_email OPTION => VALUE ...
985 sender address, required
989 alternate template name, optional
993 text attachment arrayref, optional
997 email subject, optional
1001 notice name instead of "Invoice", optional
1005 Returns an argument list to be passed to L<FS::Misc::send_email>.
1011 sub generate_email {
1015 my $conf = $self->conf;
1017 my $me = '[FS::cust_bill::generate_email]';
1020 'from' => $args{'from'},
1021 'subject' => ($args{'subject'} || $self->email_subject),
1022 'custnum' => $self->custnum,
1023 'msgtype' => 'invoice',
1026 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1028 my $cust_main = $self->cust_main;
1030 if (ref($args{'to'}) eq 'ARRAY') {
1031 $return{'to'} = $args{'to'};
1033 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1034 $cust_main->invoicing_list
1038 if ( $conf->exists('invoice_html') ) {
1040 warn "$me creating HTML/text multipart message"
1043 $return{'nobody'} = 1;
1045 my $alternative = build MIME::Entity
1046 'Type' => 'multipart/alternative',
1047 #'Encoding' => '7bit',
1048 'Disposition' => 'inline'
1052 if ( $conf->exists('invoice_email_pdf')
1053 and scalar($conf->config('invoice_email_pdf_note')) ) {
1055 warn "$me using 'invoice_email_pdf_note' in multipart message"
1057 $data = [ map { $_ . "\n" }
1058 $conf->config('invoice_email_pdf_note')
1063 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1065 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1066 $data = $args{'print_text'};
1068 $data = [ $self->print_text(\%args) ];
1073 $alternative->attach(
1074 'Type' => 'text/plain',
1075 'Encoding' => 'quoted-printable',
1076 'Charset' => 'UTF-8',
1077 #'Encoding' => '7bit',
1079 'Disposition' => 'inline',
1086 if ( $conf->exists('invoice_email_pdf')
1087 and scalar($conf->config('invoice_email_pdf_note')) ) {
1089 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1093 $args{'from'} =~ /\@([\w\.\-]+)/;
1094 my $from = $1 || 'example.com';
1095 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1098 my $agentnum = $cust_main->agentnum;
1099 if ( defined($args{'template'}) && length($args{'template'})
1100 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1103 $logo = 'logo_'. $args{'template'}. '.png';
1107 my $image_data = $conf->config_binary( $logo, $agentnum);
1109 $image = build MIME::Entity
1110 'Type' => 'image/png',
1111 'Encoding' => 'base64',
1112 'Data' => $image_data,
1113 'Filename' => 'logo.png',
1114 'Content-ID' => "<$content_id>",
1117 if ($conf->exists('invoice-barcode')) {
1118 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1119 $barcode = build MIME::Entity
1120 'Type' => 'image/png',
1121 'Encoding' => 'base64',
1122 'Data' => $self->invoice_barcode(0),
1123 'Filename' => 'barcode.png',
1124 'Content-ID' => "<$barcode_content_id>",
1126 $args{'barcode_cid'} = $barcode_content_id;
1129 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1132 $alternative->attach(
1133 'Type' => 'text/html',
1134 'Encoding' => 'quoted-printable',
1135 'Data' => [ '<html>',
1138 ' '. encode_entities($return{'subject'}),
1141 ' <body bgcolor="#e8e8e8">',
1146 'Disposition' => 'inline',
1147 #'Filename' => 'invoice.pdf',
1151 my @otherparts = ();
1152 if ( $cust_main->email_csv_cdr ) {
1154 push @otherparts, build MIME::Entity
1155 'Type' => 'text/csv',
1156 'Encoding' => '7bit',
1157 'Data' => [ map { "$_\n" }
1158 $self->call_details('prepend_billed_number' => 1)
1160 'Disposition' => 'attachment',
1161 'Filename' => 'usage-'. $self->invnum. '.csv',
1166 if ( $conf->exists('invoice_email_pdf') ) {
1171 # multipart/alternative
1177 my $related = build MIME::Entity 'Type' => 'multipart/related',
1178 'Encoding' => '7bit';
1180 #false laziness w/Misc::send_email
1181 $related->head->replace('Content-type',
1182 $related->mime_type.
1183 '; boundary="'. $related->head->multipart_boundary. '"'.
1184 '; type=multipart/alternative'
1187 $related->add_part($alternative);
1189 $related->add_part($image) if $image;
1191 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1193 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1197 #no other attachment:
1199 # multipart/alternative
1204 $return{'content-type'} = 'multipart/related';
1205 if ($conf->exists('invoice-barcode') && $barcode) {
1206 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1208 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1210 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1211 #$return{'disposition'} = 'inline';
1217 if ( $conf->exists('invoice_email_pdf') ) {
1218 warn "$me creating PDF attachment"
1221 #mime parts arguments a la MIME::Entity->build().
1222 $return{'mimeparts'} = [
1223 { $self->mimebuild_pdf(\%args) }
1227 if ( $conf->exists('invoice_email_pdf')
1228 and scalar($conf->config('invoice_email_pdf_note')) ) {
1230 warn "$me using 'invoice_email_pdf_note'"
1232 $return{'body'} = [ map { $_ . "\n" }
1233 $conf->config('invoice_email_pdf_note')
1238 warn "$me not using 'invoice_email_pdf_note'"
1240 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1241 $return{'body'} = $args{'print_text'};
1243 $return{'body'} = [ $self->print_text(\%args) ];
1256 Returns a list suitable for passing to MIME::Entity->build(), representing
1257 this invoice as PDF attachment.
1264 'Type' => 'application/pdf',
1265 'Encoding' => 'base64',
1266 'Data' => [ $self->print_pdf(@_) ],
1267 'Disposition' => 'attachment',
1268 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1274 Sends this invoice to the destinations configured for this customer: sends
1275 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1277 Options can be passed as a hashref. Positional parameters are no longer
1280 I<template>: a suffix for alternate invoices
1282 I<agentnum>: obsolete, now does nothing.
1284 I<invoice_from> overrides the default email invoice From: address.
1286 I<amount>: obsolete, does nothing
1288 I<notice_name> overrides "Invoice" as the name of the sent document
1289 (templates from 10/2009 or newer required).
1291 I<lpr> overrides the system 'lpr' option as the command to print a document
1292 from standard input.
1298 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1299 my $conf = $self->conf;
1301 my $cust_main = $self->cust_main;
1303 my @invoicing_list = $cust_main->invoicing_list;
1306 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1307 && ! $self->invoice_noemail;
1310 if grep { $_ eq 'POST' } @invoicing_list; #postal
1312 #this has never been used post-$ORIGINAL_ISP afaik
1313 $self->fax_invoice($opt)
1314 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1320 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1322 Sends this invoice to the customer's email destination(s).
1324 Options must be passed as a hashref. Positional parameters are no longer
1327 I<template>, if specified, is the name of a suffix for alternate invoices.
1329 I<invoice_from>, if specified, overrides the default email invoice From:
1332 I<notice_name> is the name of the sent document.
1336 sub queueable_email {
1339 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1340 or die "invalid invoice number: " . $opt{invnum};
1342 my %args = map {$_ => $opt{$_}}
1344 qw( invoice_from notice_name no_coupon template );
1346 my $error = $self->email( \%args );
1347 die $error if $error;
1353 return if $self->hide;
1354 my $conf = $self->conf;
1355 my $opt = shift || {};
1356 if ($opt and !ref($opt)) {
1357 die "FS::cust_bill::email called with positional parameters";
1360 my $template = $opt->{template};
1361 my $from = delete $opt->{invoice_from};
1363 # this is where we set the From: address
1364 $from ||= $self->_agent_invoice_from || #XXX should go away
1365 $conf->config('invoice_from', $self->cust_main->agentnum );
1367 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1368 $self->cust_main->invoicing_list;
1370 if ( ! @invoicing_list ) { #no recipients
1371 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1372 die 'No recipients for customer #'. $self->custnum;
1374 #default: better to notify this person than silence
1375 @invoicing_list = ($from);
1379 # this is where we set the Subject:
1380 my $subject = $self->email_subject($template);
1382 my $error = send_email(
1383 $self->generate_email(
1385 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1386 'subject' => $subject,
1387 %$opt, # template, etc.
1390 die "can't email invoice: $error\n" if $error;
1391 #die "$error\n" if $error;
1397 my $conf = $self->conf;
1399 #my $template = scalar(@_) ? shift : '';
1402 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1405 my $cust_main = $self->cust_main;
1406 my $name = $cust_main->name;
1407 my $name_short = $cust_main->name_short;
1408 my $invoice_number = $self->invnum;
1409 my $invoice_date = $self->_date_pretty;
1411 eval qq("$subject");
1414 =item lpr_data HASHREF
1416 Returns the postscript or plaintext for this invoice as an arrayref.
1418 Options must be passed as a hashref. Positional parameters are no longer
1421 I<template>, if specified, is the name of a suffix for alternate invoices.
1423 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1429 my $conf = $self->conf;
1430 my $opt = shift || {};
1431 if ($opt and !ref($opt)) {
1432 # nobody does this anyway
1433 die "FS::cust_bill::lpr_data called with positional parameters";
1436 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1437 [ $self->$method( $opt ) ];
1442 Prints this invoice.
1444 Options must be passed as a hashref.
1446 I<template>, if specified, is the name of a suffix for alternate invoices.
1448 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1454 return if $self->hide;
1455 my $conf = $self->conf;
1456 my $opt = shift || {};
1457 if ($opt and !ref($opt)) {
1458 die "FS::cust_bill::print called with positional parameters";
1461 my $lpr = delete $opt->{lpr};
1462 if($conf->exists('invoice_print_pdf')) {
1463 # Add the invoice to the current batch.
1464 $self->batch_invoice($opt);
1468 $self->lpr_data($opt),
1469 'agentnum' => $self->cust_main->agentnum,
1475 =item fax_invoice HASHREF
1479 Options must be passed as a hashref.
1481 I<template>, if specified, is the name of a suffix for alternate invoices.
1483 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1489 return if $self->hide;
1490 my $conf = $self->conf;
1491 my $opt = shift || {};
1492 if ($opt and !ref($opt)) {
1493 die "FS::cust_bill::fax_invoice called with positional parameters";
1496 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1497 unless $conf->exists('invoice_latex');
1499 my $dialstring = $self->cust_main->getfield('fax');
1502 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1503 'dialstring' => $dialstring,
1505 die $error if $error;
1509 =item batch_invoice [ HASHREF ]
1511 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1512 isn't an open batch, one will be created.
1517 my ($self, $opt) = @_;
1518 my $bill_batch = $self->get_open_bill_batch;
1519 my $cust_bill_batch = FS::cust_bill_batch->new({
1520 batchnum => $bill_batch->batchnum,
1521 invnum => $self->invnum,
1523 return $cust_bill_batch->insert($opt);
1526 =item get_open_batch
1528 Returns the currently open batch as an FS::bill_batch object, creating a new
1529 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1534 sub get_open_bill_batch {
1536 my $conf = $self->conf;
1537 my $hashref = { status => 'O' };
1538 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1539 ? $self->cust_main->agentnum
1541 my $batch = qsearchs('bill_batch', $hashref);
1542 return $batch if $batch;
1543 $batch = FS::bill_batch->new($hashref);
1544 my $error = $batch->insert;
1545 die $error if $error;
1549 =item ftp_invoice [ TEMPLATENAME ]
1551 Sends this invoice data via FTP.
1553 TEMPLATENAME is unused?
1559 my $conf = $self->conf;
1560 my $template = scalar(@_) ? shift : '';
1563 'protocol' => 'ftp',
1564 'server' => $conf->config('cust_bill-ftpserver'),
1565 'username' => $conf->config('cust_bill-ftpusername'),
1566 'password' => $conf->config('cust_bill-ftppassword'),
1567 'dir' => $conf->config('cust_bill-ftpdir'),
1568 'format' => $conf->config('cust_bill-ftpformat'),
1572 =item spool_invoice [ TEMPLATENAME ]
1574 Spools this invoice data (see L<FS::spool_csv>)
1576 TEMPLATENAME is unused?
1582 my $conf = $self->conf;
1583 my $template = scalar(@_) ? shift : '';
1586 'format' => $conf->config('cust_bill-spoolformat'),
1587 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1591 =item send_csv OPTION => VALUE, ...
1593 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1597 protocol - currently only "ftp"
1603 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1604 and YYMMDDHHMMSS is a timestamp.
1606 See L</print_csv> for a description of the output format.
1611 my($self, %opt) = @_;
1615 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1616 mkdir $spooldir, 0700 unless -d $spooldir;
1618 # don't localize dates here, they're a defined format
1619 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1620 my $file = "$spooldir/$tracctnum.csv";
1622 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1624 open(CSV, ">$file") or die "can't open $file: $!";
1632 if ( $opt{protocol} eq 'ftp' ) {
1633 eval "use Net::FTP;";
1635 $net = Net::FTP->new($opt{server}) or die @$;
1637 die "unknown protocol: $opt{protocol}";
1640 $net->login( $opt{username}, $opt{password} )
1641 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1643 $net->binary or die "can't set binary mode";
1645 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1647 $net->put($file) or die "can't put $file: $!";
1657 Spools CSV invoice data.
1663 =item format - any of FS::Misc::::Invoicing::spool_formats
1665 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1666 customer has the corresponding invoice destinations set (see
1667 L<FS::cust_main_invoice>).
1669 =item agent_spools - if set to a true value, will spool to per-agent files
1670 rather than a single global file
1672 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1673 append to that spool. L<FS::Cron::upload> will then send the spool file to
1676 =item balanceover - if set, only spools the invoice if the total amount owed on
1677 this invoice and all older invoices is greater than the specified amount.
1679 =item time - the "current time". Controls the printing of past due messages
1687 my($self, %opt) = @_;
1689 my $time = $opt{'time'} || time;
1690 my $cust_main = $self->cust_main;
1692 if ( $opt{'dest'} ) {
1693 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1694 $cust_main->invoicing_list;
1695 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1696 || ! keys %invoicing_list;
1699 if ( $opt{'balanceover'} ) {
1701 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1704 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1705 mkdir $spooldir, 0700 unless -d $spooldir;
1707 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1710 if ( $opt{'agent_spools'} ) {
1711 $file = 'agentnum'.$cust_main->agentnum;
1716 if ( $opt{'upload_targetnum'} ) {
1717 $spooldir .= '/target'.$opt{'upload_targetnum'};
1718 mkdir $spooldir, 0700 unless -d $spooldir;
1719 } # otherwise it just goes into export.xxx/cust_bill
1721 if ( lc($opt{'format'}) eq 'billco' ) {
1725 $file = "$spooldir/$file.csv";
1727 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1729 open(CSV, ">>$file") or die "can't open $file: $!";
1730 flock(CSV, LOCK_EX);
1735 if ( lc($opt{'format'}) eq 'billco' ) {
1737 flock(CSV, LOCK_UN);
1740 $file =~ s/-header.csv$/-detail.csv/;
1742 open(CSV,">>$file") or die "can't open $file: $!";
1743 flock(CSV, LOCK_EX);
1747 print CSV $detail if defined($detail);
1749 flock(CSV, LOCK_UN);
1756 =item print_csv OPTION => VALUE, ...
1758 Returns CSV data for this invoice.
1762 format - 'default', 'billco', 'oneline', 'bridgestone'
1764 Returns a list consisting of two scalars. The first is a single line of CSV
1765 header information for this invoice. The second is one or more lines of CSV
1766 detail information for this invoice.
1768 If I<format> is not specified or "default", the fields of the CSV file are as
1771 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1772 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1776 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1778 B<record_type> is C<cust_bill> for the initial header line only. The
1779 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1780 fields are filled in.
1782 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1783 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1786 =item invnum - invoice number
1788 =item custnum - customer number
1790 =item _date - invoice date
1792 =item charged - total invoice amount
1794 =item first - customer first name
1796 =item last - customer first name
1798 =item company - company name
1800 =item address1 - address line 1
1802 =item address2 - address line 1
1812 =item pkg - line item description
1814 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1816 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1818 =item sdate - start date for recurring fee
1820 =item edate - end date for recurring fee
1824 If I<format> is "billco", the fields of the header CSV file are as follows:
1826 +-------------------------------------------------------------------+
1827 | FORMAT HEADER FILE |
1828 |-------------------------------------------------------------------|
1829 | Field | Description | Name | Type | Width |
1830 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1831 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1832 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1833 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1834 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1835 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1836 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1837 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1838 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1839 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1840 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1841 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1842 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1843 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1844 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1845 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1846 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1847 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1848 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1849 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1850 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1851 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1852 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1853 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1854 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1855 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1856 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1857 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1858 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1859 +-------+-------------------------------+------------+------+-------+
1861 If I<format> is "billco", the fields of the detail CSV file are as follows:
1863 FORMAT FOR DETAIL FILE
1865 Field | Description | Name | Type | Width
1866 1 | N/A-Leave Empty | RC | CHAR | 2
1867 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1868 3 | Account Number | TRACCTNUM | CHAR | 15
1869 4 | Invoice Number | TRINVOICE | CHAR | 15
1870 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1871 6 | Transaction Detail | DETAILS | CHAR | 100
1872 7 | Amount | AMT | NUM* | 9
1873 8 | Line Format Control** | LNCTRL | CHAR | 2
1874 9 | Grouping Code | GROUP | CHAR | 2
1875 10 | User Defined | ACCT CODE | CHAR | 15
1877 If format is 'oneline', there is no detail file. Each invoice has a
1878 header line only, with the fields:
1880 Agent number, agent name, customer number, first name, last name, address
1881 line 1, address line 2, city, state, zip, invoice date, invoice number,
1882 amount charged, amount due, previous balance, due date.
1884 and then, for each line item, three columns containing the package number,
1885 description, and amount.
1887 If format is 'bridgestone', there is no detail file. Each invoice has a
1888 header line with the following fields in a fixed-width format:
1890 Customer number (in display format), date, name (first last), company,
1891 address 1, address 2, city, state, zip.
1893 This is a mailing list format, and has no per-invoice fields. To avoid
1894 sending redundant notices, the spooling event should have a "once" or
1895 "once_percust_every" condition.
1900 my($self, %opt) = @_;
1902 eval "use Text::CSV_XS";
1905 my $cust_main = $self->cust_main;
1907 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1908 my $format = lc($opt{'format'});
1910 my $time = $opt{'time'} || time;
1912 my $tracctnum = ''; #leaking out from billco-specific sections :/
1913 if ( $format eq 'billco' ) {
1916 $self->conf->config('billco-account_num', $cust_main->agentnum);
1918 $tracctnum = $account_num eq 'display_custnum'
1919 ? $cust_main->display_custnum
1920 : $opt{'tracctnum'};
1923 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1925 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1927 my( $previous_balance, @unused ) = $self->previous; #previous balance
1929 my $pmt_cr_applied = 0;
1930 $pmt_cr_applied += $_->{'amount'}
1931 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1933 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1936 '', # 1 | N/A-Leave Empty CHAR 2
1937 '', # 2 | N/A-Leave Empty CHAR 15
1938 $tracctnum, # 3 | Transaction Account No CHAR 15
1939 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1940 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1941 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1942 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1943 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1944 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1945 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1946 '', # 10 | Ancillary Billing Information CHAR 30
1947 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1948 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1951 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1954 $duedate, # 14 | Bill Due Date CHAR 10
1956 $previous_balance, # 15 | Previous Balance NUM* 9
1957 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1958 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1959 $totaldue, # 18 | Total Amt Due NUM* 9
1960 $totaldue, # 19 | Total Amt Due NUM* 9
1961 '', # 20 | 30 Day Aging NUM* 9
1962 '', # 21 | 60 Day Aging NUM* 9
1963 '', # 22 | 90 Day Aging NUM* 9
1964 'N', # 23 | Y/N CHAR 1
1965 '', # 24 | Remittance automation CHAR 100
1966 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1967 $self->custnum, # 26 | Customer Reference Number CHAR 15
1968 '0', # 27 | Federal Tax*** NUM* 9
1969 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1970 '0', # 29 | Other Taxes & Fees*** NUM* 9
1973 } elsif ( $format eq 'oneline' ) { #name
1975 my ($previous_balance) = $self->previous;
1976 $previous_balance = sprintf('%.2f', $previous_balance);
1977 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1983 $self->_items_pkg, #_items_nontax? no sections or anything
1988 $cust_main->agentnum,
1989 $cust_main->agent->agent,
1993 $cust_main->company,
1994 $cust_main->address1,
1995 $cust_main->address2,
2001 time2str("%x", $self->_date),
2006 $self->due_date2str("%x"),
2011 } elsif ( $format eq 'bridgestone' ) {
2013 # bypass the CSV stuff and just return this
2014 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2015 my $zip = $cust_main->zip;
2017 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2021 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2023 $cust_main->display_custnum,
2025 uc(substr($cust_main->contact_firstlast,0,30)),
2026 uc(substr($cust_main->company ,0,30)),
2027 uc(substr($cust_main->address1 ,0,30)),
2028 uc(substr($cust_main->address2 ,0,30)),
2029 uc(substr($cust_main->city ,0,20)),
2030 uc($cust_main->state),
2036 } elsif ( $format eq 'ics' ) {
2038 my $bill = $cust_main->bill_location;
2039 my $zip = $bill->zip;
2043 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2048 # minor false laziness with print_generic
2049 my ($previous_balance) = $self->previous;
2050 my $balance_due = $self->owed + $previous_balance;
2051 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2052 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2055 if ( $self->due_date and $time >= $self->due_date ) {
2056 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2060 my $header = sprintf(
2061 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2062 $cust_main->display_custnum, #BID
2063 uc($cust_main->first), #FNAME
2064 uc($cust_main->last), #LNAME
2065 '00', #BATCH, should this ever be anything else?
2066 uc($cust_main->company), #COMP
2067 uc($bill->address1), #STREET1
2068 uc($bill->address2), #STREET2
2069 uc($bill->city), #CITY
2070 uc($bill->state), #STATE
2073 time2str('%Y%m%d', $self->_date), #BILL_DATE
2074 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2075 ( map {sprintf('%0.2f', $_)}
2076 $balance_due, #AMNT_DUE
2077 $previous_balance, #PREV_BAL
2078 $payment_total, #PYMT_RCVD
2079 $credit_total, #CREDITS
2080 $previous_balance, #BEG_BAL--is this correct?
2081 $self->charged, #NEW_CHRG
2084 $past_due, #PAST_MSG
2088 my %svc_class = ('' => ''); # maybe cache this more persistently?
2090 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2092 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2093 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2097 my @dates = ( $self->_date, undef );
2098 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2099 $dates[1] = $prev->sdate; #questionable
2102 # generate an 01 detail for each service
2103 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2104 foreach my $cust_svc ( @svcs ) {
2105 $show_pkgnum = ''; # hide it if we're showing svcnums
2107 my $svcpart = $cust_svc->svcpart;
2108 if (!exists($svc_class{$svcpart})) {
2109 my $classnum = $cust_svc->part_svc->classnum;
2110 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2112 $svc_class{$svcpart} = $part_svc_class ?
2113 $part_svc_class->classname :
2117 my @h_label = $cust_svc->label(@dates, 'I');
2118 push @details, sprintf('01%-9s%-20s%-47s',
2120 $svc_class{$svcpart},
2123 } #foreach $cust_svc
2126 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2127 if ($cust_bill_pkg->recur > 0) {
2128 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2129 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2131 push @details, sprintf('02%-6s%-60s%-10s',
2134 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2136 } #foreach $cust_bill_pkg
2138 # Tag this row so that we know whether this is one page (1), two pages
2139 # (2), # or "big" (B). The tag will be stripped off before uploading.
2140 if ( scalar(@details) < 12 ) {
2142 } elsif ( scalar(@details) < 58 ) {
2148 return join('', $header, @details, "\n");
2156 time2str("%x", $self->_date),
2157 sprintf("%.2f", $self->charged),
2158 ( map { $cust_main->getfield($_) }
2159 qw( first last company address1 address2 city state zip country ) ),
2161 ) or die "can't create csv";
2164 my $header = $csv->string. "\n";
2167 if ( lc($opt{'format'}) eq 'billco' ) {
2170 foreach my $item ( $self->_items_pkg ) {
2173 '', # 1 | N/A-Leave Empty CHAR 2
2174 '', # 2 | N/A-Leave Empty CHAR 15
2175 $tracctnum, # 3 | Account Number CHAR 15
2176 $self->invnum, # 4 | Invoice Number CHAR 15
2177 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2178 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2179 $item->{'amount'}, # 7 | Amount NUM* 9
2180 '', # 8 | Line Format Control** CHAR 2
2181 '', # 9 | Grouping Code CHAR 2
2182 '', # 10 | User Defined CHAR 15
2185 $detail .= $csv->string. "\n";
2189 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2195 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2197 my($pkg, $setup, $recur, $sdate, $edate);
2198 if ( $cust_bill_pkg->pkgnum ) {
2200 ($pkg, $setup, $recur, $sdate, $edate) = (
2201 $cust_bill_pkg->part_pkg->pkg,
2202 ( $cust_bill_pkg->setup != 0
2203 ? sprintf("%.2f", $cust_bill_pkg->setup )
2205 ( $cust_bill_pkg->recur != 0
2206 ? sprintf("%.2f", $cust_bill_pkg->recur )
2208 ( $cust_bill_pkg->sdate
2209 ? time2str("%x", $cust_bill_pkg->sdate)
2211 ($cust_bill_pkg->edate
2212 ? time2str("%x", $cust_bill_pkg->edate)
2216 } else { #pkgnum tax
2217 next unless $cust_bill_pkg->setup != 0;
2218 $pkg = $cust_bill_pkg->desc;
2219 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2220 ( $sdate, $edate ) = ( '', '' );
2226 ( map { '' } (1..11) ),
2227 ($pkg, $setup, $recur, $sdate, $edate)
2228 ) or die "can't create csv";
2230 $detail .= $csv->string. "\n";
2236 ( $header, $detail );
2242 Pays this invoice with a compliemntary payment. If there is an error,
2243 returns the error, otherwise returns false.
2249 my $cust_pay = new FS::cust_pay ( {
2250 'invnum' => $self->invnum,
2251 'paid' => $self->owed,
2254 'payinfo' => $self->cust_main->payinfo,
2262 Attempts to pay this invoice with a credit card payment via a
2263 Business::OnlinePayment realtime gateway. See
2264 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2265 for supported processors.
2271 $self->realtime_bop( 'CC', @_ );
2276 Attempts to pay this invoice with an electronic check (ACH) payment via a
2277 Business::OnlinePayment realtime gateway. See
2278 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2279 for supported processors.
2285 $self->realtime_bop( 'ECHECK', @_ );
2290 Attempts to pay this invoice with phone bill (LEC) payment via a
2291 Business::OnlinePayment realtime gateway. See
2292 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2293 for supported processors.
2299 $self->realtime_bop( 'LEC', @_ );
2303 my( $self, $method ) = (shift,shift);
2304 my $conf = $self->conf;
2307 my $cust_main = $self->cust_main;
2308 my $balance = $cust_main->balance;
2309 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2310 $amount = sprintf("%.2f", $amount);
2311 return "not run (balance $balance)" unless $amount > 0;
2313 my $description = 'Internet Services';
2314 if ( $conf->exists('business-onlinepayment-description') ) {
2315 my $dtempl = $conf->config('business-onlinepayment-description');
2317 my $agent_obj = $cust_main->agent
2318 or die "can't retreive agent for $cust_main (agentnum ".
2319 $cust_main->agentnum. ")";
2320 my $agent = $agent_obj->agent;
2321 my $pkgs = join(', ',
2322 map { $_->part_pkg->pkg }
2323 grep { $_->pkgnum } $self->cust_bill_pkg
2325 $description = eval qq("$dtempl");
2328 $cust_main->realtime_bop($method, $amount,
2329 'description' => $description,
2330 'invnum' => $self->invnum,
2331 #this didn't do what we want, it just calls apply_payments_and_credits
2333 'apply_to_invoice' => 1,
2336 #this changes application behavior: auto payments
2337 #triggered against a specific invoice are now applied
2338 #to that invoice instead of oldest open.
2344 =item batch_card OPTION => VALUE...
2346 Adds a payment for this invoice to the pending credit card batch (see
2347 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2348 runs the payment using a realtime gateway.
2353 my ($self, %options) = @_;
2354 my $cust_main = $self->cust_main;
2356 $options{invnum} = $self->invnum;
2358 $cust_main->batch_card(%options);
2361 sub _agent_template {
2363 $self->cust_main->agent_template;
2366 sub _agent_invoice_from {
2368 $self->cust_main->agent_invoice_from;
2371 =item invoice_barcode DIR_OR_FALSE
2373 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2374 it is taken as the temp directory where the PNG file will be generated and the
2375 PNG file name is returned. Otherwise, the PNG image itself is returned.
2379 sub invoice_barcode {
2380 my ($self, $dir) = (shift,shift);
2382 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2383 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2384 my $gd = $gdbar->plot(Height => 30);
2387 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2391 ) or die "can't open temp file: $!\n";
2392 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2393 my $png_file = $bh->filename;
2400 =item invnum_date_pretty
2402 Returns a string with the invoice number and date, for example:
2403 "Invoice #54 (3/20/2008)".
2405 Intended for back-end context, with regard to translation and date formatting.
2409 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2410 # for backend use (and also does the wrong thing, localizing for end customer
2411 # instead of backoffice configured date format)
2412 sub invnum_date_pretty {
2414 #$self->mt('Invoice #').
2415 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2416 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2419 #sub _items_extra_usage_sections {
2421 # my $escape = shift;
2423 # my %sections = ();
2425 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2426 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2428 # next unless $cust_bill_pkg->pkgnum > 0;
2430 # foreach my $section ( keys %usage_class ) {
2432 # my $usage = $cust_bill_pkg->usage($section);
2434 # next unless $usage && $usage > 0;
2436 # $sections{$section} ||= 0;
2437 # $sections{$section} += $usage;
2443 # map { { 'description' => &{$escape}($_),
2444 # 'subtotal' => $sections{$_},
2445 # 'summarized' => '',
2446 # 'tax_section' => '',
2449 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2453 sub _items_extra_usage_sections {
2455 my $conf = $self->conf;
2463 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2465 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2466 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2467 next unless $cust_bill_pkg->pkgnum > 0;
2469 foreach my $classnum ( keys %usage_class ) {
2470 my $section = $usage_class{$classnum}->classname;
2471 $classnums{$section} = $classnum;
2473 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2474 my $amount = $detail->amount;
2475 next unless $amount && $amount > 0;
2477 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2478 $sections{$section}{amount} += $amount; #subtotal
2479 $sections{$section}{calls}++;
2480 $sections{$section}{duration} += $detail->duration;
2482 my $desc = $detail->regionname;
2483 my $description = $desc;
2484 $description = substr($desc, 0, $maxlength). '...'
2485 if $format eq 'latex' && length($desc) > $maxlength;
2487 $lines{$section}{$desc} ||= {
2488 description => &{$escape}($description),
2489 #pkgpart => $part_pkg->pkgpart,
2490 pkgnum => $cust_bill_pkg->pkgnum,
2495 #unit_amount => $cust_bill_pkg->unitrecur,
2496 quantity => $cust_bill_pkg->quantity,
2497 product_code => 'N/A',
2498 ext_description => [],
2501 $lines{$section}{$desc}{amount} += $amount;
2502 $lines{$section}{$desc}{calls}++;
2503 $lines{$section}{$desc}{duration} += $detail->duration;
2509 my %sectionmap = ();
2510 foreach (keys %sections) {
2511 my $usage_class = $usage_class{$classnums{$_}};
2512 $sectionmap{$_} = { 'description' => &{$escape}($_),
2513 'amount' => $sections{$_}{amount}, #subtotal
2514 'calls' => $sections{$_}{calls},
2515 'duration' => $sections{$_}{duration},
2517 'tax_section' => '',
2518 'sort_weight' => $usage_class->weight,
2519 ( $usage_class->format
2520 ? ( map { $_ => $usage_class->$_($format) }
2521 qw( description_generator header_generator total_generator total_line_generator )
2528 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2532 foreach my $section ( keys %lines ) {
2533 foreach my $line ( keys %{$lines{$section}} ) {
2534 my $l = $lines{$section}{$line};
2535 $l->{section} = $sectionmap{$section};
2536 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2537 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2542 return(\@sections, \@lines);
2548 my $end = $self->_date;
2550 # start at date of previous invoice + 1 second or 0 if no previous invoice
2551 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2552 $start = 0 if !$start;
2555 my $cust_main = $self->cust_main;
2556 my @pkgs = $cust_main->all_pkgs;
2557 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2560 foreach my $pkg ( @pkgs ) {
2561 my @h_cust_svc = $pkg->h_cust_svc($end);
2562 foreach my $h_cust_svc ( @h_cust_svc ) {
2563 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2564 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2566 my $inserted = $h_cust_svc->date_inserted;
2567 my $deleted = $h_cust_svc->date_deleted;
2568 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2570 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2572 # DID either activated or ported in; cannot be both for same DID simultaneously
2573 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2574 && (!$phone_inserted->lnp_status
2575 || $phone_inserted->lnp_status eq ''
2576 || $phone_inserted->lnp_status eq 'native')) {
2579 else { # this one not so clean, should probably move to (h_)svc_phone
2580 my $phone_portedin = qsearchs( 'h_svc_phone',
2581 { 'svcnum' => $h_cust_svc->svcnum,
2582 'lnp_status' => 'portedin' },
2583 FS::h_svc_phone->sql_h_searchs($end),
2585 $num_portedin++ if $phone_portedin;
2588 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2589 if($deleted >= $start && $deleted <= $end && $phone_deleted
2590 && (!$phone_deleted->lnp_status
2591 || $phone_deleted->lnp_status ne 'portingout')) {
2594 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2595 && $phone_deleted->lnp_status
2596 && $phone_deleted->lnp_status eq 'portingout') {
2600 # increment usage minutes
2601 if ( $phone_inserted ) {
2602 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2603 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2606 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2609 # don't look at this service again
2610 push @seen, $h_cust_svc->svcnum;
2614 $minutes = sprintf("%d", $minutes);
2615 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2616 . "$num_deactivated Ported-Out: $num_portedout ",
2617 "Total Minutes: $minutes");
2620 sub _items_accountcode_cdr {
2625 my $section = { 'amount' => 0,
2628 'sort_weight' => '',
2630 'description' => 'Usage by Account Code',
2636 my %accountcodes = ();
2638 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2639 next unless $cust_bill_pkg->pkgnum > 0;
2641 my @header = $cust_bill_pkg->details_header;
2642 next unless scalar(@header);
2643 $section->{'header'} = join(',',@header);
2645 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2647 $section->{'header'} = $detail->formatted('format' => $format)
2648 if($detail->detail eq $section->{'header'});
2650 my $accountcode = $detail->accountcode;
2651 next unless $accountcode;
2653 my $amount = $detail->amount;
2654 next unless $amount && $amount > 0;
2656 $accountcodes{$accountcode} ||= {
2657 description => $accountcode,
2664 product_code => 'N/A',
2665 section => $section,
2666 ext_description => [ $section->{'header'} ],
2670 $section->{'amount'} += $amount;
2671 $accountcodes{$accountcode}{'amount'} += $amount;
2672 $accountcodes{$accountcode}{calls}++;
2673 $accountcodes{$accountcode}{duration} += $detail->duration;
2674 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2678 foreach my $l ( values %accountcodes ) {
2679 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2680 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2681 foreach my $sorted_detail ( @sorted_detail ) {
2682 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2684 delete $l->{detail_temp};
2688 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2690 return ($section,\@sorted_lines);
2693 sub _items_svc_phone_sections {
2695 my $conf = $self->conf;
2703 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2705 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2706 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2708 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2709 next unless $cust_bill_pkg->pkgnum > 0;
2711 my @header = $cust_bill_pkg->details_header;
2712 next unless scalar(@header);
2714 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2716 my $phonenum = $detail->phonenum;
2717 next unless $phonenum;
2719 my $amount = $detail->amount;
2720 next unless $amount && $amount > 0;
2722 $sections{$phonenum} ||= { 'amount' => 0,
2725 'sort_weight' => -1,
2726 'phonenum' => $phonenum,
2728 $sections{$phonenum}{amount} += $amount; #subtotal
2729 $sections{$phonenum}{calls}++;
2730 $sections{$phonenum}{duration} += $detail->duration;
2732 my $desc = $detail->regionname;
2733 my $description = $desc;
2734 $description = substr($desc, 0, $maxlength). '...'
2735 if $format eq 'latex' && length($desc) > $maxlength;
2737 $lines{$phonenum}{$desc} ||= {
2738 description => &{$escape}($description),
2739 #pkgpart => $part_pkg->pkgpart,
2747 product_code => 'N/A',
2748 ext_description => [],
2751 $lines{$phonenum}{$desc}{amount} += $amount;
2752 $lines{$phonenum}{$desc}{calls}++;
2753 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2755 my $line = $usage_class{$detail->classnum}->classname;
2756 $sections{"$phonenum $line"} ||=
2760 'sort_weight' => $usage_class{$detail->classnum}->weight,
2761 'phonenum' => $phonenum,
2762 'header' => [ @header ],
2764 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2765 $sections{"$phonenum $line"}{calls}++;
2766 $sections{"$phonenum $line"}{duration} += $detail->duration;
2768 $lines{"$phonenum $line"}{$desc} ||= {
2769 description => &{$escape}($description),
2770 #pkgpart => $part_pkg->pkgpart,
2778 product_code => 'N/A',
2779 ext_description => [],
2782 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2783 $lines{"$phonenum $line"}{$desc}{calls}++;
2784 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2785 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2786 $detail->formatted('format' => $format);
2791 my %sectionmap = ();
2792 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2793 foreach ( keys %sections ) {
2794 my @header = @{ $sections{$_}{header} || [] };
2796 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2797 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2798 my $usage_class = $summary ? $simple : $usage_simple;
2799 my $ending = $summary ? ' usage charges' : '';
2802 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2804 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2805 'amount' => $sections{$_}{amount}, #subtotal
2806 'calls' => $sections{$_}{calls},
2807 'duration' => $sections{$_}{duration},
2809 'tax_section' => '',
2810 'phonenum' => $sections{$_}{phonenum},
2811 'sort_weight' => $sections{$_}{sort_weight},
2812 'post_total' => $summary, #inspire pagebreak
2814 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2815 qw( description_generator
2818 total_line_generator
2825 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2826 $a->{sort_weight} <=> $b->{sort_weight}
2831 foreach my $section ( keys %lines ) {
2832 foreach my $line ( keys %{$lines{$section}} ) {
2833 my $l = $lines{$section}{$line};
2834 $l->{section} = $sectionmap{$section};
2835 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2836 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2841 if($conf->exists('phone_usage_class_summary')) {
2842 # this only works with Latex
2846 # after this, we'll have only two sections per DID:
2847 # Calls Summary and Calls Detail
2848 foreach my $section ( @sections ) {
2849 if($section->{'post_total'}) {
2850 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2851 $section->{'total_line_generator'} = sub { '' };
2852 $section->{'total_generator'} = sub { '' };
2853 $section->{'header_generator'} = sub { '' };
2854 $section->{'description_generator'} = '';
2855 push @newsections, $section;
2856 my %calls_detail = %$section;
2857 $calls_detail{'post_total'} = '';
2858 $calls_detail{'sort_weight'} = '';
2859 $calls_detail{'description_generator'} = sub { '' };
2860 $calls_detail{'header_generator'} = sub {
2861 return ' & Date/Time & Called Number & Duration & Price'
2862 if $format eq 'latex';
2865 $calls_detail{'description'} = 'Calls Detail: '
2866 . $section->{'phonenum'};
2867 push @newsections, \%calls_detail;
2871 # after this, each usage class is collapsed/summarized into a single
2872 # line under the Calls Summary section
2873 foreach my $newsection ( @newsections ) {
2874 if($newsection->{'post_total'}) { # this means Calls Summary
2875 foreach my $section ( @sections ) {
2876 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2877 && !$section->{'post_total'});
2878 my $newdesc = $section->{'description'};
2879 my $tn = $section->{'phonenum'};
2880 $newdesc =~ s/$tn//g;
2881 my $line = { ext_description => [],
2885 calls => $section->{'calls'},
2886 section => $newsection,
2887 duration => $section->{'duration'},
2888 description => $newdesc,
2889 amount => sprintf("%.2f",$section->{'amount'}),
2890 product_code => 'N/A',
2892 push @newlines, $line;
2897 # after this, Calls Details is populated with all CDRs
2898 foreach my $newsection ( @newsections ) {
2899 if(!$newsection->{'post_total'}) { # this means Calls Details
2900 foreach my $line ( @lines ) {
2901 next unless (scalar(@{$line->{'ext_description'}}) &&
2902 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2904 my @extdesc = @{$line->{'ext_description'}};
2906 foreach my $extdesc ( @extdesc ) {
2907 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2908 push @newextdesc, $extdesc;
2910 $line->{'ext_description'} = \@newextdesc;
2911 $line->{'section'} = $newsection;
2912 push @newlines, $line;
2917 return(\@newsections, \@newlines);
2920 return(\@sections, \@lines);
2924 =sub _items_usage_class_summary OPTIONS
2926 Returns a list of detail items summarizing the usage charges on this
2927 invoice. Each one will have 'amount', 'description' (the usage charge name),
2928 and 'usage_classnum'.
2930 OPTIONS can include 'escape' (a function to escape the descriptions).
2934 sub _items_usage_class_summary {
2938 my $escape = $opt{escape} || sub { $_[0] };
2939 my $invnum = $self->invnum;
2940 my @classes = qsearch({
2941 'table' => 'usage_class',
2942 'select' => 'classnum, classname, SUM(amount) AS amount',
2943 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2944 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2945 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2946 ' GROUP BY classnum, classname, weight'.
2947 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2948 ' ORDER BY weight ASC',
2952 description => &{$escape}($self->mt('Usage Summary')),
2956 foreach my $class (@classes) {
2958 'description' => &{$escape}($class->classname),
2959 'amount' => sprintf('%.2f', $class->amount),
2960 'usage_classnum' => $class->classnum,
2961 'section' => $section,
2967 sub _items_previous {
2969 my $conf = $self->conf;
2970 my $cust_main = $self->cust_main;
2971 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2973 foreach ( @pr_cust_bill ) {
2974 my $date = $conf->exists('invoice_show_prior_due_date')
2975 ? 'due '. $_->due_date2str('short')
2976 : $self->time2str_local('short', $_->_date);
2978 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2979 #'pkgpart' => 'N/A',
2981 'amount' => sprintf("%.2f", $_->owed),
2987 # 'description' => 'Previous Balance',
2988 # #'pkgpart' => 'N/A',
2989 # 'pkgnum' => 'N/A',
2990 # 'amount' => sprintf("%10.2f", $pr_total ),
2991 # 'ext_description' => [ map {
2992 # "Invoice ". $_->invnum.
2993 # " (". time2str("%x",$_->_date). ") ".
2994 # sprintf("%10.2f", $_->owed)
2995 # } @pr_cust_bill ],
3000 sub _items_credits {
3001 my( $self, %opt ) = @_;
3002 my $trim_len = $opt{'trim_len'} || 60;
3007 if ( $self->conf->exists('previous_balance-payments_since') ) {
3008 if ( $opt{'template'} eq 'statement' ) {
3009 # then the current bill is a "statement" (i.e. an invoice sent as
3010 # a payment receipt)
3011 # and in that case we want to see payments on or after THIS invoice
3012 @objects = qsearch('cust_credit', {
3013 'custnum' => $self->custnum,
3014 '_date' => {op => '>=', value => $self->_date},
3018 $date = $self->previous_bill->_date if $self->previous_bill;
3019 @objects = qsearch('cust_credit', {
3020 'custnum' => $self->custnum,
3021 '_date' => {op => '>=', value => $date},
3025 @objects = $self->cust_credited;
3028 foreach my $obj ( @objects ) {
3029 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3031 my $reason = substr($cust_credit->reason, 0, $trim_len);
3032 $reason .= '...' if length($reason) < length($cust_credit->reason);
3033 $reason = " ($reason) " if $reason;
3036 #'description' => 'Credit ref\#'. $_->crednum.
3037 # " (". time2str("%x",$_->cust_credit->_date) .")".
3039 'description' => $self->mt('Credit applied').' '.
3040 $self->time2str_local('short', $obj->_date). $reason,
3041 'amount' => sprintf("%.2f",$obj->amount),
3049 sub _items_payments {
3054 my $detailed = $self->conf->exists('invoice_payment_details');
3056 if ( $self->conf->exists('previous_balance-payments_since') ) {
3057 # then show payments dated on/after the previous bill...
3058 if ( $opt{'template'} eq 'statement' ) {
3059 # then the current bill is a "statement" (i.e. an invoice sent as
3060 # a payment receipt)
3061 # and in that case we want to see payments on or after THIS invoice
3062 @objects = qsearch('cust_pay', {
3063 'custnum' => $self->custnum,
3064 '_date' => {op => '>=', value => $self->_date},
3067 # the normal case: payments on or after the previous invoice
3069 $date = $self->previous_bill->_date if $self->previous_bill;
3070 @objects = qsearch('cust_pay', {
3071 'custnum' => $self->custnum,
3072 '_date' => {op => '>=', value => $date},
3074 # and before the current bill...
3075 @objects = grep { $_->_date < $self->_date } @objects;
3078 @objects = $self->cust_bill_pay;
3081 foreach my $obj (@objects) {
3082 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3083 my $desc = $self->mt('Payment received').' '.
3084 $self->time2str_local('short', $cust_pay->_date );
3085 $desc .= $self->mt(' via ') .
3086 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3090 'description' => $desc,
3091 'amount' => sprintf("%.2f", $obj->amount )
3099 =item call_details [ OPTION => VALUE ... ]
3101 Returns an array of CSV strings representing the call details for this invoice
3102 The only option available is the boolean prepend_billed_number
3107 my ($self, %opt) = @_;
3109 my $format_function = sub { shift };
3111 if ($opt{prepend_billed_number}) {
3112 $format_function = sub {
3116 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3121 my @details = map { $_->details( 'format_function' => $format_function,
3122 'escape_function' => sub{ return() },
3126 $self->cust_bill_pkg;
3127 my $header = $details[0];
3128 ( $header, grep { $_ ne $header } @details );
3138 =item process_reprint
3142 sub process_reprint {
3143 process_re_X('print', @_);
3146 =item process_reemail
3150 sub process_reemail {
3151 process_re_X('email', @_);
3159 process_re_X('fax', @_);
3167 process_re_X('ftp', @_);
3174 sub process_respool {
3175 process_re_X('spool', @_);
3178 use Storable qw(thaw);
3182 my( $method, $job ) = ( shift, shift );
3183 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3185 my $param = thaw(decode_base64(shift));
3186 warn Dumper($param) if $DEBUG;
3197 # spool_invoice ftp_invoice fax_invoice print_invoice
3198 my($method, $job, %param ) = @_;
3200 warn "re_X $method for job $job with param:\n".
3201 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3204 #some false laziness w/search/cust_bill.html
3206 my $orderby = 'ORDER BY cust_bill._date';
3208 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3210 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3212 my @cust_bill = qsearch( {
3213 #'select' => "cust_bill.*",
3214 'table' => 'cust_bill',
3215 'addl_from' => $addl_from,
3217 'extra_sql' => $extra_sql,
3218 'order_by' => $orderby,
3222 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3224 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3227 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3228 foreach my $cust_bill ( @cust_bill ) {
3229 $cust_bill->$method();
3231 if ( $job ) { #progressbar foo
3233 if ( time - $min_sec > $last ) {
3234 my $error = $job->update_statustext(
3235 int( 100 * $num / scalar(@cust_bill) )
3237 die $error if $error;
3248 =head1 CLASS METHODS
3254 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3259 my ($class, $start, $end) = @_;
3261 $class->paid_sql($start, $end). ' - '.
3262 $class->credited_sql($start, $end);
3267 Returns an SQL fragment to retreive the net amount (charged minus credited).
3272 my ($class, $start, $end) = @_;
3273 'charged - '. $class->credited_sql($start, $end);
3278 Returns an SQL fragment to retreive the amount paid against this invoice.
3283 my ($class, $start, $end) = @_;
3284 $start &&= "AND cust_bill_pay._date <= $start";
3285 $end &&= "AND cust_bill_pay._date > $end";
3286 $start = '' unless defined($start);
3287 $end = '' unless defined($end);
3288 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3289 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3294 Returns an SQL fragment to retreive the amount credited against this invoice.
3299 my ($class, $start, $end) = @_;
3300 $start &&= "AND cust_credit_bill._date <= $start";
3301 $end &&= "AND cust_credit_bill._date > $end";
3302 $start = '' unless defined($start);
3303 $end = '' unless defined($end);
3304 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3305 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3310 Returns an SQL fragment to retrieve the due date of an invoice.
3311 Currently only supported on PostgreSQL.
3316 my $conf = new FS::Conf;
3320 cust_bill.invoice_terms,
3321 cust_main.invoice_terms,
3322 \''.($conf->config('invoice_default_terms') || '').'\'
3323 ), E\'Net (\\\\d+)\'
3325 ) * 86400 + cust_bill._date'
3328 =item search_sql_where HASHREF
3330 Class method which returns an SQL WHERE fragment to search for parameters
3331 specified in HASHREF. Valid parameters are
3337 List reference of start date, end date, as UNIX timestamps.
3347 List reference of charged limits (exclusive).
3351 List reference of charged limits (exclusive).
3355 flag, return open invoices only
3359 flag, return net invoices only
3363 =item newest_percust
3367 Return only invoices belonging to that customer.
3371 Limit to that customer class (single value or arrayref).
3375 Limit to customers with that payment method (single value or arrayref).
3379 Limit to customers with that advertising source.
3383 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3387 sub search_sql_where {
3388 my($class, $param) = @_;
3390 warn "$me search_sql_where called with params: \n".
3391 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3397 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3398 push @search, "cust_main.agentnum = $1";
3402 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3403 push @search, "cust_main.refnum = $1";
3407 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3408 push @search, "cust_bill.custnum = $1";
3411 #customer classnum (false laziness w/ cust_main/Search.pm)
3412 if ( $param->{'cust_classnum'} ) {
3414 my @classnum = ref( $param->{'cust_classnum'} )
3415 ? @{ $param->{'cust_classnum'} }
3416 : ( $param->{'cust_classnum'} );
3418 @classnum = grep /^(\d*)$/, @classnum;
3421 push @search, '( '. join(' OR ', map {
3422 $_ ? "cust_main.classnum = $_"
3423 : "cust_main.classnum IS NULL"
3433 if ( $param->{payby} ) {
3434 my $payby = $param->{payby};
3435 $payby = [ $payby ] unless ref $payby;
3436 my $payby_in = join(',', map {dbh->quote($_)} @$payby);
3437 push @search, "cust_main.payby IN($payby_in)" if length($payby_in);
3441 if ( $param->{_date} ) {
3442 my($beginning, $ending) = @{$param->{_date}};
3444 push @search, "cust_bill._date >= $beginning",
3445 "cust_bill._date < $ending";
3449 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3450 push @search, "cust_bill.invnum >= $1";
3452 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3453 push @search, "cust_bill.invnum <= $1";
3457 if ( $param->{charged} ) {
3458 my @charged = ref($param->{charged})
3459 ? @{ $param->{charged} }
3460 : ($param->{charged});
3462 push @search, map { s/^charged/cust_bill.charged/; $_; }
3466 my $owed_sql = FS::cust_bill->owed_sql;
3469 if ( $param->{owed} ) {
3470 my @owed = ref($param->{owed})
3471 ? @{ $param->{owed} }
3473 push @search, map { s/^owed/$owed_sql/; $_; }
3478 push @search, "0 != $owed_sql"
3479 if $param->{'open'};
3480 push @search, '0 != '. FS::cust_bill->net_sql
3484 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3485 if $param->{'days'};
3488 if ( $param->{'newest_percust'} ) {
3490 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3491 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3493 my @newest_where = map { my $x = $_;
3494 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3497 grep ! /^cust_main./, @search;
3498 my $newest_where = scalar(@newest_where)
3499 ? ' AND '. join(' AND ', @newest_where)
3503 push @search, "cust_bill._date = (
3504 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3505 WHERE newest_cust_bill.custnum = cust_bill.custnum
3511 #promised_date - also has an option to accept nulls
3512 if ( $param->{promised_date} ) {
3513 my($beginning, $ending, $null) = @{$param->{promised_date}};
3515 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3516 "cust_bill.promised_date < $ending )" .
3517 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3520 #agent virtualization
3521 my $curuser = $FS::CurrentUser::CurrentUser;
3522 if ( $curuser->username eq 'fs_queue'
3523 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3525 my $newuser = qsearchs('access_user', {
3526 'username' => $username,
3530 $curuser = $newuser;
3532 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3535 push @search, $curuser->agentnums_sql;
3537 join(' AND ', @search );
3549 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3550 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base