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 );
19 use FS::cust_statement;
20 use FS::cust_bill_pkg;
21 use FS::cust_bill_pkg_display;
22 use FS::cust_bill_pkg_detail;
26 use FS::cust_credit_bill;
28 use FS::cust_pay_batch;
29 use FS::cust_bill_event;
32 use FS::cust_bill_pay;
33 use FS::cust_bill_pay_batch;
34 use FS::part_bill_event;
37 use FS::cust_bill_batch;
38 use FS::cust_bill_pay_pkg;
39 use FS::cust_credit_bill_pkg;
40 use FS::discount_plan;
41 use FS::cust_bill_void;
45 $me = '[FS::cust_bill]';
49 FS::cust_bill - Object methods for cust_bill records
55 $record = new FS::cust_bill \%hash;
56 $record = new FS::cust_bill { 'column' => 'value' };
58 $error = $record->insert;
60 $error = $new_record->replace($old_record);
62 $error = $record->delete;
64 $error = $record->check;
66 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
68 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
70 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
72 @cust_pay_objects = $cust_bill->cust_pay;
74 $tax_amount = $record->tax;
76 @lines = $cust_bill->print_text;
77 @lines = $cust_bill->print_text('time' => $time);
81 An FS::cust_bill object represents an invoice; a declaration that a customer
82 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
83 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
84 following fields are currently supported:
90 =item invnum - primary key (assigned automatically for new invoices)
92 =item custnum - customer (see L<FS::cust_main>)
94 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
95 L<Time::Local> and L<Date::Parse> for conversion functions.
97 =item charged - amount of this invoice
99 =item invoice_terms - optional terms override for this specific invoice
107 =item billing_balance - the customer's balance immediately before generating
108 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
109 to determine the customer's balance at a specific time.
111 =item previous_balance - the customer's balance immediately after generating
112 the invoice before this one. DEPRECATED.
114 =item printed - formerly used to track the number of times an invoice had
115 been printed; no longer used.
123 =item closed - books closed flag, empty or `Y'
125 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
127 =item agent_invid - legacy invoice number
129 =item promised_date - customer promised payment date, for collection
139 Creates a new invoice. To add the invoice to the database, see L<"insert">.
140 Invoices are normally created by calling the bill method of a customer object
141 (see L<FS::cust_main>).
145 sub table { 'cust_bill'; }
147 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
148 # (except email_subject and invnum_date_pretty)
151 $self->conf->config('notice_name') || 'Invoice'
154 sub cust_linked { $_[0]->cust_main_custnum; }
155 sub cust_unlinked_msg {
157 "WARNING: can't find cust_main.custnum ". $self->custnum.
158 ' (cust_bill.invnum '. $self->invnum. ')';
163 Adds this invoice to the database ("Posts" the invoice). If there is an error,
164 returns the error, otherwise returns false.
170 warn "$me insert called\n" if $DEBUG;
172 local $SIG{HUP} = 'IGNORE';
173 local $SIG{INT} = 'IGNORE';
174 local $SIG{QUIT} = 'IGNORE';
175 local $SIG{TERM} = 'IGNORE';
176 local $SIG{TSTP} = 'IGNORE';
177 local $SIG{PIPE} = 'IGNORE';
179 my $oldAutoCommit = $FS::UID::AutoCommit;
180 local $FS::UID::AutoCommit = 0;
183 my $error = $self->SUPER::insert;
185 $dbh->rollback if $oldAutoCommit;
189 if ( $self->get('cust_bill_pkg') ) {
190 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
191 $cust_bill_pkg->invnum($self->invnum);
192 my $error = $cust_bill_pkg->insert;
194 $dbh->rollback if $oldAutoCommit;
195 return "can't create invoice line item: $error";
200 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
207 Voids this invoice: deletes the invoice and adds a record of the voided invoice
208 to the FS::cust_bill_void table (and related tables starting from
209 FS::cust_bill_pkg_void).
215 my $reason = scalar(@_) ? shift : '';
217 local $SIG{HUP} = 'IGNORE';
218 local $SIG{INT} = 'IGNORE';
219 local $SIG{QUIT} = 'IGNORE';
220 local $SIG{TERM} = 'IGNORE';
221 local $SIG{TSTP} = 'IGNORE';
222 local $SIG{PIPE} = 'IGNORE';
224 my $oldAutoCommit = $FS::UID::AutoCommit;
225 local $FS::UID::AutoCommit = 0;
228 my $cust_bill_void = new FS::cust_bill_void ( {
229 map { $_ => $self->get($_) } $self->fields
231 $cust_bill_void->reason($reason);
232 my $error = $cust_bill_void->insert;
234 $dbh->rollback if $oldAutoCommit;
238 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
239 my $error = $cust_bill_pkg->void($reason);
241 $dbh->rollback if $oldAutoCommit;
246 $error = $self->delete;
248 $dbh->rollback if $oldAutoCommit;
252 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
260 This method now works but you probably shouldn't use it. Instead, apply a
261 credit against the invoice, or use the new void method.
263 Using this method to delete invoices outright is really, really bad. There
264 would be no record you ever posted this invoice, and there are no check to
265 make sure charged = 0 or that there are no associated cust_bill_pkg records.
267 Really, don't use it.
273 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
275 local $SIG{HUP} = 'IGNORE';
276 local $SIG{INT} = 'IGNORE';
277 local $SIG{QUIT} = 'IGNORE';
278 local $SIG{TERM} = 'IGNORE';
279 local $SIG{TSTP} = 'IGNORE';
280 local $SIG{PIPE} = 'IGNORE';
282 my $oldAutoCommit = $FS::UID::AutoCommit;
283 local $FS::UID::AutoCommit = 0;
286 foreach my $table (qw(
297 foreach my $linked ( $self->$table() ) {
298 my $error = $linked->delete;
300 $dbh->rollback if $oldAutoCommit;
307 my $error = $self->SUPER::delete(@_);
309 $dbh->rollback if $oldAutoCommit;
313 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
319 =item replace [ OLD_RECORD ]
321 You can, but probably shouldn't modify invoices...
323 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
324 supplied, replaces this record. If there is an error, returns the error,
325 otherwise returns false.
329 #replace can be inherited from Record.pm
331 # replace_check is now the preferred way to #implement replace data checks
332 # (so $object->replace() works without an argument)
335 my( $new, $old ) = ( shift, shift );
336 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
337 #return "Can't change _date!" unless $old->_date eq $new->_date;
338 return "Can't change _date" unless $old->_date == $new->_date;
339 return "Can't change charged" unless $old->charged == $new->charged
340 || $old->charged == 0
341 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
347 =item add_cc_surcharge
353 sub add_cc_surcharge {
354 my ($self, $pkgnum, $amount) = (shift, shift, shift);
357 my $cust_bill_pkg = new FS::cust_bill_pkg({
358 'invnum' => $self->invnum,
362 $error = $cust_bill_pkg->insert;
363 return $error if $error;
365 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
366 $self->charged($self->charged+$amount);
367 $error = $self->replace;
368 return $error if $error;
370 $self->apply_payments_and_credits;
376 Checks all fields to make sure this is a valid invoice. If there is an error,
377 returns the error, otherwise returns false. Called by the insert and replace
386 $self->ut_numbern('invnum')
387 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
388 || $self->ut_numbern('_date')
389 || $self->ut_money('charged')
390 || $self->ut_numbern('printed')
391 || $self->ut_enum('closed', [ '', 'Y' ])
392 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
393 || $self->ut_numbern('agent_invid') #varchar?
395 return $error if $error;
397 $self->_date(time) unless $self->_date;
399 $self->printed(0) if $self->printed eq '';
406 Returns the displayed invoice number for this invoice: agent_invid if
407 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
413 if ( $self->agent_invid
414 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
415 return $self->agent_invid;
417 return $self->invnum;
423 Returns the customer's last invoice before this one.
429 if ( !$self->get('previous_bill') ) {
430 $self->set('previous_bill', qsearchs({
431 'table' => 'cust_bill',
432 'hashref' => { 'custnum' => $self->custnum,
433 '_date' => { op=>'<', value=>$self->_date } },
434 'order_by' => 'ORDER BY _date DESC LIMIT 1',
437 $self->get('previous_bill');
442 Returns a list consisting of the total previous balance for this customer,
443 followed by the previous outstanding invoices (as FS::cust_bill objects also).
450 my @cust_bill = sort { $a->_date <=> $b->_date }
451 grep { $_->owed != 0 }
452 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
453 #'_date' => { op=>'<', value=>$self->_date },
454 'invnum' => { op=>'<', value=>$self->invnum },
457 foreach ( @cust_bill ) { $total += $_->owed; }
461 =item enable_previous
463 Whether to show the 'Previous Charges' section when printing this invoice.
464 The negation of the 'disable_previous_balance' config setting.
468 sub enable_previous {
470 my $agentnum = $self->cust_main->agentnum;
471 !$self->conf->exists('disable_previous_balance', $agentnum);
476 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
483 { 'table' => 'cust_bill_pkg',
484 'hashref' => { 'invnum' => $self->invnum },
485 'order_by' => 'ORDER BY billpkgnum',
490 =item cust_bill_pkg_pkgnum PKGNUM
492 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
497 sub cust_bill_pkg_pkgnum {
498 my( $self, $pkgnum ) = @_;
500 { 'table' => 'cust_bill_pkg',
501 'hashref' => { 'invnum' => $self->invnum,
504 'order_by' => 'ORDER BY billpkgnum',
511 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
518 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
519 $self->cust_bill_pkg;
521 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
526 Returns true if any of the packages (or their definitions) corresponding to the
527 line items for this invoice have the no_auto flag set.
533 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
536 =item open_cust_bill_pkg
538 Returns the open line items for this invoice.
540 Note that cust_bill_pkg with both setup and recur fees are returned as two
541 separate line items, each with only one fee.
545 # modeled after cust_main::open_cust_bill
546 sub open_cust_bill_pkg {
549 # grep { $_->owed > 0 } $self->cust_bill_pkg
551 my %other = ( 'recur' => 'setup',
552 'setup' => 'recur', );
554 foreach my $field ( qw( recur setup )) {
555 push @open, map { $_->set( $other{$field}, 0 ); $_; }
556 grep { $_->owed($field) > 0 }
557 $self->cust_bill_pkg;
563 =item cust_bill_event
565 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
569 sub cust_bill_event {
571 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
574 =item num_cust_bill_event
576 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
580 sub num_cust_bill_event {
583 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
584 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
585 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
586 $sth->fetchrow_arrayref->[0];
591 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
595 #false laziness w/cust_pkg.pm
599 'table' => 'cust_event',
600 'addl_from' => 'JOIN part_event USING ( eventpart )',
601 'hashref' => { 'tablenum' => $self->invnum },
602 'extra_sql' => " AND eventtable = 'cust_bill' ",
608 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
612 #false laziness w/cust_pkg.pm
616 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
617 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
618 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
619 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
620 $sth->fetchrow_arrayref->[0];
625 Returns the customer (see L<FS::cust_main>) for this invoice.
631 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
634 =item cust_suspend_if_balance_over AMOUNT
636 Suspends the customer associated with this invoice if the total amount owed on
637 this invoice and all older invoices is greater than the specified amount.
639 Returns a list: an empty list on success or a list of errors.
643 sub cust_suspend_if_balance_over {
644 my( $self, $amount ) = ( shift, shift );
645 my $cust_main = $self->cust_main;
646 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
649 $cust_main->suspend(@_);
655 Depreciated. See the cust_credited method.
657 #Returns a list consisting of the total previous credited (see
658 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
659 #outstanding credits (FS::cust_credit objects).
665 croak "FS::cust_bill->cust_credit depreciated; see ".
666 "FS::cust_bill->cust_credit_bill";
669 #my @cust_credit = sort { $a->_date <=> $b->_date }
670 # grep { $_->credited != 0 && $_->_date < $self->_date }
671 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
673 #foreach (@cust_credit) { $total += $_->credited; }
674 #$total, @cust_credit;
679 Depreciated. See the cust_bill_pay method.
681 #Returns all payments (see L<FS::cust_pay>) for this invoice.
687 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
689 #sort { $a->_date <=> $b->_date }
690 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
696 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
699 sub cust_bill_pay_batch {
701 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
706 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
712 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
713 sort { $a->_date <=> $b->_date }
714 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
719 =item cust_credit_bill
721 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
727 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
728 sort { $a->_date <=> $b->_date }
729 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
733 sub cust_credit_bill {
734 shift->cust_credited(@_);
737 #=item cust_bill_pay_pkgnum PKGNUM
739 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
740 #with matching pkgnum.
744 #sub cust_bill_pay_pkgnum {
745 # my( $self, $pkgnum ) = @_;
746 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
747 # sort { $a->_date <=> $b->_date }
748 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
749 # 'pkgnum' => $pkgnum,
754 =item cust_bill_pay_pkg PKGNUM
756 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
757 applied against the matching pkgnum.
761 sub cust_bill_pay_pkg {
762 my( $self, $pkgnum ) = @_;
765 'select' => 'cust_bill_pay_pkg.*',
766 'table' => 'cust_bill_pay_pkg',
767 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
768 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
769 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
770 " AND cust_bill_pkg.pkgnum = $pkgnum",
775 #=item cust_credited_pkgnum PKGNUM
777 #=item cust_credit_bill_pkgnum PKGNUM
779 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
780 #with matching pkgnum.
784 #sub cust_credited_pkgnum {
785 # my( $self, $pkgnum ) = @_;
786 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
787 # sort { $a->_date <=> $b->_date }
788 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
789 # 'pkgnum' => $pkgnum,
794 #sub cust_credit_bill_pkgnum {
795 # shift->cust_credited_pkgnum(@_);
798 =item cust_credit_bill_pkg PKGNUM
800 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
801 applied against the matching pkgnum.
805 sub cust_credit_bill_pkg {
806 my( $self, $pkgnum ) = @_;
809 'select' => 'cust_credit_bill_pkg.*',
810 'table' => 'cust_credit_bill_pkg',
811 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
812 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
813 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
814 " AND cust_bill_pkg.pkgnum = $pkgnum",
819 =item cust_bill_batch
821 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
825 sub cust_bill_batch {
827 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
832 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
833 hash keyed by term length.
839 FS::discount_plan->all($self);
844 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
851 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
853 foreach (@taxlines) { $total += $_->setup; }
859 Returns the amount owed (still outstanding) on this invoice, which is charged
860 minus all payment applications (see L<FS::cust_bill_pay>) and credit
861 applications (see L<FS::cust_credit_bill>).
867 my $balance = $self->charged;
868 $balance -= $_->amount foreach ( $self->cust_bill_pay );
869 $balance -= $_->amount foreach ( $self->cust_credited );
870 $balance = sprintf( "%.2f", $balance);
871 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
876 my( $self, $pkgnum ) = @_;
878 #my $balance = $self->charged;
880 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
882 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
883 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
885 $balance = sprintf( "%.2f", $balance);
886 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
892 Returns true if this invoice should be hidden. See the
893 selfservice-hide_invoices-taxclass configuraiton setting.
899 my $conf = $self->conf;
900 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
902 my @cust_bill_pkg = $self->cust_bill_pkg;
903 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
904 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
907 =item apply_payments_and_credits [ OPTION => VALUE ... ]
909 Applies unapplied payments and credits to this invoice.
911 A hash of optional arguments may be passed. Currently "manual" is supported.
912 If true, a payment receipt is sent instead of a statement when
913 'payment_receipt_email' configuration option is set.
915 If there is an error, returns the error, otherwise returns false.
919 sub apply_payments_and_credits {
920 my( $self, %options ) = @_;
921 my $conf = $self->conf;
923 local $SIG{HUP} = 'IGNORE';
924 local $SIG{INT} = 'IGNORE';
925 local $SIG{QUIT} = 'IGNORE';
926 local $SIG{TERM} = 'IGNORE';
927 local $SIG{TSTP} = 'IGNORE';
928 local $SIG{PIPE} = 'IGNORE';
930 my $oldAutoCommit = $FS::UID::AutoCommit;
931 local $FS::UID::AutoCommit = 0;
934 $self->select_for_update; #mutex
936 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
937 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
939 if ( $conf->exists('pkg-balances') ) {
940 # limit @payments & @credits to those w/ a pkgnum grepped from $self
941 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
942 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
943 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
946 while ( $self->owed > 0 and ( @payments || @credits ) ) {
949 if ( @payments && @credits ) {
951 #decide which goes first by weight of top (unapplied) line item
953 my @open_lineitems = $self->open_cust_bill_pkg;
956 max( map { $_->part_pkg->pay_weight || 0 }
961 my $max_credit_weight =
962 max( map { $_->part_pkg->credit_weight || 0 }
968 #if both are the same... payments first? it has to be something
969 if ( $max_pay_weight >= $max_credit_weight ) {
975 } elsif ( @payments ) {
977 } elsif ( @credits ) {
980 die "guru meditation #12 and 35";
984 if ( $app eq 'pay' ) {
986 my $payment = shift @payments;
987 $unapp_amount = $payment->unapplied;
988 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
989 $app->pkgnum( $payment->pkgnum )
990 if $conf->exists('pkg-balances') && $payment->pkgnum;
992 } elsif ( $app eq 'credit' ) {
994 my $credit = shift @credits;
995 $unapp_amount = $credit->credited;
996 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
997 $app->pkgnum( $credit->pkgnum )
998 if $conf->exists('pkg-balances') && $credit->pkgnum;
1001 die "guru meditation #12 and 35";
1005 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1006 warn "owed_pkgnum ". $app->pkgnum;
1007 $owed = $self->owed_pkgnum($app->pkgnum);
1009 $owed = $self->owed;
1011 next unless $owed > 0;
1013 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1014 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1016 $app->invnum( $self->invnum );
1018 my $error = $app->insert(%options);
1020 $dbh->rollback if $oldAutoCommit;
1021 return "Error inserting ". $app->table. " record: $error";
1023 die $error if $error;
1027 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1032 =item generate_email OPTION => VALUE ...
1040 sender address, required
1044 alternate template name, optional
1048 text attachment arrayref, optional
1052 email subject, optional
1056 notice name instead of "Invoice", optional
1060 Returns an argument list to be passed to L<FS::Misc::send_email>.
1066 sub generate_email {
1070 my $conf = $self->conf;
1072 my $me = '[FS::cust_bill::generate_email]';
1075 'from' => $args{'from'},
1076 'subject' => ($args{'subject'} || $self->email_subject),
1077 'custnum' => $self->custnum,
1078 'msgtype' => 'invoice',
1081 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1083 my $cust_main = $self->cust_main;
1085 if (ref($args{'to'}) eq 'ARRAY') {
1086 $return{'to'} = $args{'to'};
1088 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1089 $cust_main->invoicing_list
1093 if ( $conf->exists('invoice_html') ) {
1095 warn "$me creating HTML/text multipart message"
1098 $return{'nobody'} = 1;
1100 my $alternative = build MIME::Entity
1101 'Type' => 'multipart/alternative',
1102 #'Encoding' => '7bit',
1103 'Disposition' => 'inline'
1107 if ( $conf->exists('invoice_email_pdf')
1108 and scalar($conf->config('invoice_email_pdf_note')) ) {
1110 warn "$me using 'invoice_email_pdf_note' in multipart message"
1112 $data = [ map { $_ . "\n" }
1113 $conf->config('invoice_email_pdf_note')
1118 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1120 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1121 $data = $args{'print_text'};
1123 $data = [ $self->print_text(\%args) ];
1128 $alternative->attach(
1129 'Type' => 'text/plain',
1130 'Encoding' => 'quoted-printable',
1131 #'Encoding' => '7bit',
1133 'Disposition' => 'inline',
1140 if ( $conf->exists('invoice_email_pdf')
1141 and scalar($conf->config('invoice_email_pdf_note')) ) {
1143 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1147 $args{'from'} =~ /\@([\w\.\-]+)/;
1148 my $from = $1 || 'example.com';
1149 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1152 my $agentnum = $cust_main->agentnum;
1153 if ( defined($args{'template'}) && length($args{'template'})
1154 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1157 $logo = 'logo_'. $args{'template'}. '.png';
1161 my $image_data = $conf->config_binary( $logo, $agentnum);
1163 $image = build MIME::Entity
1164 'Type' => 'image/png',
1165 'Encoding' => 'base64',
1166 'Data' => $image_data,
1167 'Filename' => 'logo.png',
1168 'Content-ID' => "<$content_id>",
1171 if ($conf->exists('invoice-barcode')) {
1172 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1173 $barcode = build MIME::Entity
1174 'Type' => 'image/png',
1175 'Encoding' => 'base64',
1176 'Data' => $self->invoice_barcode(0),
1177 'Filename' => 'barcode.png',
1178 'Content-ID' => "<$barcode_content_id>",
1180 $args{'barcode_cid'} = $barcode_content_id;
1183 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1186 $alternative->attach(
1187 'Type' => 'text/html',
1188 'Encoding' => 'quoted-printable',
1189 'Data' => [ '<html>',
1192 ' '. encode_entities($return{'subject'}),
1195 ' <body bgcolor="#e8e8e8">',
1200 'Disposition' => 'inline',
1201 #'Filename' => 'invoice.pdf',
1205 my @otherparts = ();
1206 if ( $cust_main->email_csv_cdr ) {
1208 push @otherparts, build MIME::Entity
1209 'Type' => 'text/csv',
1210 'Encoding' => '7bit',
1211 'Data' => [ map { "$_\n" }
1212 $self->call_details('prepend_billed_number' => 1)
1214 'Disposition' => 'attachment',
1215 'Filename' => 'usage-'. $self->invnum. '.csv',
1220 if ( $conf->exists('invoice_email_pdf') ) {
1225 # multipart/alternative
1231 my $related = build MIME::Entity 'Type' => 'multipart/related',
1232 'Encoding' => '7bit';
1234 #false laziness w/Misc::send_email
1235 $related->head->replace('Content-type',
1236 $related->mime_type.
1237 '; boundary="'. $related->head->multipart_boundary. '"'.
1238 '; type=multipart/alternative'
1241 $related->add_part($alternative);
1243 $related->add_part($image) if $image;
1245 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1247 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1251 #no other attachment:
1253 # multipart/alternative
1258 $return{'content-type'} = 'multipart/related';
1259 if ($conf->exists('invoice-barcode') && $barcode) {
1260 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1262 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1264 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1265 #$return{'disposition'} = 'inline';
1271 if ( $conf->exists('invoice_email_pdf') ) {
1272 warn "$me creating PDF attachment"
1275 #mime parts arguments a la MIME::Entity->build().
1276 $return{'mimeparts'} = [
1277 { $self->mimebuild_pdf(\%args) }
1281 if ( $conf->exists('invoice_email_pdf')
1282 and scalar($conf->config('invoice_email_pdf_note')) ) {
1284 warn "$me using 'invoice_email_pdf_note'"
1286 $return{'body'} = [ map { $_ . "\n" }
1287 $conf->config('invoice_email_pdf_note')
1292 warn "$me not using 'invoice_email_pdf_note'"
1294 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1295 $return{'body'} = $args{'print_text'};
1297 $return{'body'} = [ $self->print_text(\%args) ];
1310 Returns a list suitable for passing to MIME::Entity->build(), representing
1311 this invoice as PDF attachment.
1318 'Type' => 'application/pdf',
1319 'Encoding' => 'base64',
1320 'Data' => [ $self->print_pdf(@_) ],
1321 'Disposition' => 'attachment',
1322 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1328 Sends this invoice to the destinations configured for this customer: sends
1329 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1331 Options can be passed as a hashref. Positional parameters are no longer
1334 I<template>: a suffix for alternate invoices
1336 I<agentnum>: obsolete, now does nothing.
1338 I<invoice_from> overrides the default email invoice From: address.
1340 I<amount>: obsolete, does nothing
1342 I<notice_name> overrides "Invoice" as the name of the sent document
1343 (templates from 10/2009 or newer required).
1345 I<lpr> overrides the system 'lpr' option as the command to print a document
1346 from standard input.
1352 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1353 my $conf = $self->conf;
1355 my $cust_main = $self->cust_main;
1357 my @invoicing_list = $cust_main->invoicing_list;
1360 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1361 && ! $self->invoice_noemail;
1364 if grep { $_ eq 'POST' } @invoicing_list; #postal
1366 #this has never been used post-$ORIGINAL_ISP afaik
1367 $self->fax_invoice($opt)
1368 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1374 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1376 Sends this invoice to the customer's email destination(s).
1378 Options must be passed as a hashref. Positional parameters are no longer
1381 I<template>, if specified, is the name of a suffix for alternate invoices.
1383 I<invoice_from>, if specified, overrides the default email invoice From:
1386 I<notice_name> is the name of the sent document.
1390 sub queueable_email {
1393 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1394 or die "invalid invoice number: " . $opt{invnum};
1396 my %args = map {$_ => $opt{$_}}
1398 qw( invoice_from notice_name no_coupon template );
1400 my $error = $self->email( \%args );
1401 die $error if $error;
1407 return if $self->hide;
1408 my $conf = $self->conf;
1409 my $opt = shift || {};
1410 if ($opt and !ref($opt)) {
1411 die "FS::cust_bill::email called with positional parameters";
1414 my $template = $opt->{template};
1415 my $from = delete $opt->{invoice_from};
1417 # this is where we set the From: address
1418 $from ||= $self->_agent_invoice_from || #XXX should go away
1419 $conf->config('invoice_from', $self->cust_main->agentnum );
1421 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1422 $self->cust_main->invoicing_list;
1424 if ( ! @invoicing_list ) { #no recipients
1425 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1426 die 'No recipients for customer #'. $self->custnum;
1428 #default: better to notify this person than silence
1429 @invoicing_list = ($from);
1433 # this is where we set the Subject:
1434 my $subject = $self->email_subject($template);
1436 my $error = send_email(
1437 $self->generate_email(
1439 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1440 'subject' => $subject,
1441 %$opt, # template, etc.
1444 die "can't email invoice: $error\n" if $error;
1445 #die "$error\n" if $error;
1451 my $conf = $self->conf;
1453 #my $template = scalar(@_) ? shift : '';
1456 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1459 my $cust_main = $self->cust_main;
1460 my $name = $cust_main->name;
1461 my $name_short = $cust_main->name_short;
1462 my $invoice_number = $self->invnum;
1463 my $invoice_date = $self->_date_pretty;
1465 eval qq("$subject");
1468 =item lpr_data HASHREF
1470 Returns the postscript or plaintext for this invoice as an arrayref.
1472 Options must be passed as a hashref. Positional parameters are no longer
1475 I<template>, if specified, is the name of a suffix for alternate invoices.
1477 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1483 my $conf = $self->conf;
1484 my $opt = shift || {};
1485 if ($opt and !ref($opt)) {
1486 # nobody does this anyway
1487 die "FS::cust_bill::lpr_data called with positional parameters";
1490 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1491 [ $self->$method( $opt ) ];
1496 Prints this invoice.
1498 Options must be passed as a hashref.
1500 I<template>, if specified, is the name of a suffix for alternate invoices.
1502 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1508 return if $self->hide;
1509 my $conf = $self->conf;
1510 my $opt = shift || {};
1511 if ($opt and !ref($opt)) {
1512 die "FS::cust_bill::print called with positional parameters";
1515 my $lpr = delete $opt->{lpr};
1516 if($conf->exists('invoice_print_pdf')) {
1517 # Add the invoice to the current batch.
1518 $self->batch_invoice($opt);
1522 $self->lpr_data($opt),
1523 'agentnum' => $self->cust_main->agentnum,
1529 =item fax_invoice HASHREF
1533 Options must be passed as a hashref.
1535 I<template>, if specified, is the name of a suffix for alternate invoices.
1537 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1543 return if $self->hide;
1544 my $conf = $self->conf;
1545 my $opt = shift || {};
1546 if ($opt and !ref($opt)) {
1547 die "FS::cust_bill::fax_invoice called with positional parameters";
1550 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1551 unless $conf->exists('invoice_latex');
1553 my $dialstring = $self->cust_main->getfield('fax');
1556 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1557 'dialstring' => $dialstring,
1559 die $error if $error;
1563 =item batch_invoice [ HASHREF ]
1565 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1566 isn't an open batch, one will be created.
1571 my ($self, $opt) = @_;
1572 my $bill_batch = $self->get_open_bill_batch;
1573 my $cust_bill_batch = FS::cust_bill_batch->new({
1574 batchnum => $bill_batch->batchnum,
1575 invnum => $self->invnum,
1577 return $cust_bill_batch->insert($opt);
1580 =item get_open_batch
1582 Returns the currently open batch as an FS::bill_batch object, creating a new
1583 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1588 sub get_open_bill_batch {
1590 my $conf = $self->conf;
1591 my $hashref = { status => 'O' };
1592 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1593 ? $self->cust_main->agentnum
1595 my $batch = qsearchs('bill_batch', $hashref);
1596 return $batch if $batch;
1597 $batch = FS::bill_batch->new($hashref);
1598 my $error = $batch->insert;
1599 die $error if $error;
1603 =item ftp_invoice [ TEMPLATENAME ]
1605 Sends this invoice data via FTP.
1607 TEMPLATENAME is unused?
1613 my $conf = $self->conf;
1614 my $template = scalar(@_) ? shift : '';
1617 'protocol' => 'ftp',
1618 'server' => $conf->config('cust_bill-ftpserver'),
1619 'username' => $conf->config('cust_bill-ftpusername'),
1620 'password' => $conf->config('cust_bill-ftppassword'),
1621 'dir' => $conf->config('cust_bill-ftpdir'),
1622 'format' => $conf->config('cust_bill-ftpformat'),
1626 =item spool_invoice [ TEMPLATENAME ]
1628 Spools this invoice data (see L<FS::spool_csv>)
1630 TEMPLATENAME is unused?
1636 my $conf = $self->conf;
1637 my $template = scalar(@_) ? shift : '';
1640 'format' => $conf->config('cust_bill-spoolformat'),
1641 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1645 =item send_csv OPTION => VALUE, ...
1647 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1651 protocol - currently only "ftp"
1657 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1658 and YYMMDDHHMMSS is a timestamp.
1660 See L</print_csv> for a description of the output format.
1665 my($self, %opt) = @_;
1669 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1670 mkdir $spooldir, 0700 unless -d $spooldir;
1672 # don't localize dates here, they're a defined format
1673 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1674 my $file = "$spooldir/$tracctnum.csv";
1676 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1678 open(CSV, ">$file") or die "can't open $file: $!";
1686 if ( $opt{protocol} eq 'ftp' ) {
1687 eval "use Net::FTP;";
1689 $net = Net::FTP->new($opt{server}) or die @$;
1691 die "unknown protocol: $opt{protocol}";
1694 $net->login( $opt{username}, $opt{password} )
1695 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1697 $net->binary or die "can't set binary mode";
1699 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1701 $net->put($file) or die "can't put $file: $!";
1711 Spools CSV invoice data.
1717 =item format - any of FS::Misc::::Invoicing::spool_formats
1719 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1720 customer has the corresponding invoice destinations set (see
1721 L<FS::cust_main_invoice>).
1723 =item agent_spools - if set to a true value, will spool to per-agent files
1724 rather than a single global file
1726 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1727 append to that spool. L<FS::Cron::upload> will then send the spool file to
1730 =item balanceover - if set, only spools the invoice if the total amount owed on
1731 this invoice and all older invoices is greater than the specified amount.
1733 =item time - the "current time". Controls the printing of past due messages
1741 my($self, %opt) = @_;
1743 my $time = $opt{'time'} || time;
1744 my $cust_main = $self->cust_main;
1746 if ( $opt{'dest'} ) {
1747 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1748 $cust_main->invoicing_list;
1749 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1750 || ! keys %invoicing_list;
1753 if ( $opt{'balanceover'} ) {
1755 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1758 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1759 mkdir $spooldir, 0700 unless -d $spooldir;
1761 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1764 if ( $opt{'agent_spools'} ) {
1765 $file = 'agentnum'.$cust_main->agentnum;
1770 if ( $opt{'upload_targetnum'} ) {
1771 $spooldir .= '/target'.$opt{'upload_targetnum'};
1772 mkdir $spooldir, 0700 unless -d $spooldir;
1773 } # otherwise it just goes into export.xxx/cust_bill
1775 if ( lc($opt{'format'}) eq 'billco' ) {
1779 $file = "$spooldir/$file.csv";
1781 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1783 open(CSV, ">>$file") or die "can't open $file: $!";
1784 flock(CSV, LOCK_EX);
1789 if ( lc($opt{'format'}) eq 'billco' ) {
1791 flock(CSV, LOCK_UN);
1794 $file =~ s/-header.csv$/-detail.csv/;
1796 open(CSV,">>$file") or die "can't open $file: $!";
1797 flock(CSV, LOCK_EX);
1801 print CSV $detail if defined($detail);
1803 flock(CSV, LOCK_UN);
1810 =item print_csv OPTION => VALUE, ...
1812 Returns CSV data for this invoice.
1816 format - 'default', 'billco', 'oneline', 'bridgestone'
1818 Returns a list consisting of two scalars. The first is a single line of CSV
1819 header information for this invoice. The second is one or more lines of CSV
1820 detail information for this invoice.
1822 If I<format> is not specified or "default", the fields of the CSV file are as
1825 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1826 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1830 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1832 B<record_type> is C<cust_bill> for the initial header line only. The
1833 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1834 fields are filled in.
1836 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1837 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1840 =item invnum - invoice number
1842 =item custnum - customer number
1844 =item _date - invoice date
1846 =item charged - total invoice amount
1848 =item first - customer first name
1850 =item last - customer first name
1852 =item company - company name
1854 =item address1 - address line 1
1856 =item address2 - address line 1
1866 =item pkg - line item description
1868 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1870 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1872 =item sdate - start date for recurring fee
1874 =item edate - end date for recurring fee
1878 If I<format> is "billco", the fields of the header CSV file are as follows:
1880 +-------------------------------------------------------------------+
1881 | FORMAT HEADER FILE |
1882 |-------------------------------------------------------------------|
1883 | Field | Description | Name | Type | Width |
1884 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1885 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1886 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1887 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1888 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1889 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1890 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1891 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1892 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1893 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1894 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1895 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1896 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1897 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1898 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1899 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1900 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1901 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1902 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1903 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1904 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1905 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1906 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1907 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1908 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1909 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1910 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1911 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1912 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1913 +-------+-------------------------------+------------+------+-------+
1915 If I<format> is "billco", the fields of the detail CSV file are as follows:
1917 FORMAT FOR DETAIL FILE
1919 Field | Description | Name | Type | Width
1920 1 | N/A-Leave Empty | RC | CHAR | 2
1921 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1922 3 | Account Number | TRACCTNUM | CHAR | 15
1923 4 | Invoice Number | TRINVOICE | CHAR | 15
1924 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1925 6 | Transaction Detail | DETAILS | CHAR | 100
1926 7 | Amount | AMT | NUM* | 9
1927 8 | Line Format Control** | LNCTRL | CHAR | 2
1928 9 | Grouping Code | GROUP | CHAR | 2
1929 10 | User Defined | ACCT CODE | CHAR | 15
1931 If format is 'oneline', there is no detail file. Each invoice has a
1932 header line only, with the fields:
1934 Agent number, agent name, customer number, first name, last name, address
1935 line 1, address line 2, city, state, zip, invoice date, invoice number,
1936 amount charged, amount due, previous balance, due date.
1938 and then, for each line item, three columns containing the package number,
1939 description, and amount.
1941 If format is 'bridgestone', there is no detail file. Each invoice has a
1942 header line with the following fields in a fixed-width format:
1944 Customer number (in display format), date, name (first last), company,
1945 address 1, address 2, city, state, zip.
1947 This is a mailing list format, and has no per-invoice fields. To avoid
1948 sending redundant notices, the spooling event should have a "once" or
1949 "once_percust_every" condition.
1954 my($self, %opt) = @_;
1956 eval "use Text::CSV_XS";
1959 my $cust_main = $self->cust_main;
1961 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1962 my $format = lc($opt{'format'});
1964 my $time = $opt{'time'} || time;
1966 my $tracctnum = ''; #leaking out from billco-specific sections :/
1967 if ( $format eq 'billco' ) {
1970 $self->conf->config('billco-account_num', $cust_main->agentnum);
1972 $tracctnum = $account_num eq 'display_custnum'
1973 ? $cust_main->display_custnum
1974 : $opt{'tracctnum'};
1977 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1979 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1981 my( $previous_balance, @unused ) = $self->previous; #previous balance
1983 my $pmt_cr_applied = 0;
1984 $pmt_cr_applied += $_->{'amount'}
1985 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1987 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1990 '', # 1 | N/A-Leave Empty CHAR 2
1991 '', # 2 | N/A-Leave Empty CHAR 15
1992 $tracctnum, # 3 | Transaction Account No CHAR 15
1993 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1994 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1995 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1996 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1997 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1998 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1999 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
2000 '', # 10 | Ancillary Billing Information CHAR 30
2001 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
2002 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
2005 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
2008 $duedate, # 14 | Bill Due Date CHAR 10
2010 $previous_balance, # 15 | Previous Balance NUM* 9
2011 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2012 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2013 $totaldue, # 18 | Total Amt Due NUM* 9
2014 $totaldue, # 19 | Total Amt Due NUM* 9
2015 '', # 20 | 30 Day Aging NUM* 9
2016 '', # 21 | 60 Day Aging NUM* 9
2017 '', # 22 | 90 Day Aging NUM* 9
2018 'N', # 23 | Y/N CHAR 1
2019 '', # 24 | Remittance automation CHAR 100
2020 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2021 $self->custnum, # 26 | Customer Reference Number CHAR 15
2022 '0', # 27 | Federal Tax*** NUM* 9
2023 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2024 '0', # 29 | Other Taxes & Fees*** NUM* 9
2027 } elsif ( $format eq 'oneline' ) { #name
2029 my ($previous_balance) = $self->previous;
2030 $previous_balance = sprintf('%.2f', $previous_balance);
2031 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2037 $self->_items_pkg, #_items_nontax? no sections or anything
2042 $cust_main->agentnum,
2043 $cust_main->agent->agent,
2047 $cust_main->company,
2048 $cust_main->address1,
2049 $cust_main->address2,
2055 time2str("%x", $self->_date),
2060 $self->due_date2str("%x"),
2065 } elsif ( $format eq 'bridgestone' ) {
2067 # bypass the CSV stuff and just return this
2068 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2069 my $zip = $cust_main->zip;
2071 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2075 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2077 $cust_main->display_custnum,
2079 uc(substr($cust_main->contact_firstlast,0,30)),
2080 uc(substr($cust_main->company ,0,30)),
2081 uc(substr($cust_main->address1 ,0,30)),
2082 uc(substr($cust_main->address2 ,0,30)),
2083 uc(substr($cust_main->city ,0,20)),
2084 uc($cust_main->state),
2090 } elsif ( $format eq 'ics' ) {
2092 my $bill = $cust_main->bill_location;
2093 my $zip = $bill->zip;
2097 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2102 # minor false laziness with print_generic
2103 my ($previous_balance) = $self->previous;
2104 my $balance_due = $self->owed + $previous_balance;
2105 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2106 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2109 if ( $self->due_date and $time >= $self->due_date ) {
2110 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2114 my $header = sprintf(
2115 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2116 $cust_main->display_custnum, #BID
2117 uc($cust_main->first), #FNAME
2118 uc($cust_main->last), #LNAME
2119 '00', #BATCH, should this ever be anything else?
2120 uc($cust_main->company), #COMP
2121 uc($bill->address1), #STREET1
2122 uc($bill->address2), #STREET2
2123 uc($bill->city), #CITY
2124 uc($bill->state), #STATE
2127 time2str('%Y%m%d', $self->_date), #BILL_DATE
2128 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2129 ( map {sprintf('%0.2f', $_)}
2130 $balance_due, #AMNT_DUE
2131 $previous_balance, #PREV_BAL
2132 $payment_total, #PYMT_RCVD
2133 $credit_total, #CREDITS
2134 $previous_balance, #BEG_BAL--is this correct?
2135 $self->charged, #NEW_CHRG
2138 $past_due, #PAST_MSG
2142 my %svc_class = ('' => ''); # maybe cache this more persistently?
2144 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2146 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2147 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2151 my @dates = ( $self->_date, undef );
2152 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2153 $dates[1] = $prev->sdate; #questionable
2156 # generate an 01 detail for each service
2157 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2158 foreach my $cust_svc ( @svcs ) {
2159 $show_pkgnum = ''; # hide it if we're showing svcnums
2161 my $svcpart = $cust_svc->svcpart;
2162 if (!exists($svc_class{$svcpart})) {
2163 my $classnum = $cust_svc->part_svc->classnum;
2164 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2166 $svc_class{$svcpart} = $part_svc_class ?
2167 $part_svc_class->classname :
2171 my @h_label = $cust_svc->label(@dates, 'I');
2172 push @details, sprintf('01%-9s%-20s%-47s',
2174 $svc_class{$svcpart},
2177 } #foreach $cust_svc
2180 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2181 if ($cust_bill_pkg->recur > 0) {
2182 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2183 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2185 push @details, sprintf('02%-6s%-60s%-10s',
2188 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2190 } #foreach $cust_bill_pkg
2192 # Tag this row so that we know whether this is one page (1), two pages
2193 # (2), # or "big" (B). The tag will be stripped off before uploading.
2194 if ( scalar(@details) < 12 ) {
2196 } elsif ( scalar(@details) < 58 ) {
2202 return join('', $header, @details, "\n");
2210 time2str("%x", $self->_date),
2211 sprintf("%.2f", $self->charged),
2212 ( map { $cust_main->getfield($_) }
2213 qw( first last company address1 address2 city state zip country ) ),
2215 ) or die "can't create csv";
2218 my $header = $csv->string. "\n";
2221 if ( lc($opt{'format'}) eq 'billco' ) {
2224 foreach my $item ( $self->_items_pkg ) {
2227 '', # 1 | N/A-Leave Empty CHAR 2
2228 '', # 2 | N/A-Leave Empty CHAR 15
2229 $tracctnum, # 3 | Account Number CHAR 15
2230 $self->invnum, # 4 | Invoice Number CHAR 15
2231 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2232 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2233 $item->{'amount'}, # 7 | Amount NUM* 9
2234 '', # 8 | Line Format Control** CHAR 2
2235 '', # 9 | Grouping Code CHAR 2
2236 '', # 10 | User Defined CHAR 15
2239 $detail .= $csv->string. "\n";
2243 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2249 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2251 my($pkg, $setup, $recur, $sdate, $edate);
2252 if ( $cust_bill_pkg->pkgnum ) {
2254 ($pkg, $setup, $recur, $sdate, $edate) = (
2255 $cust_bill_pkg->part_pkg->pkg,
2256 ( $cust_bill_pkg->setup != 0
2257 ? sprintf("%.2f", $cust_bill_pkg->setup )
2259 ( $cust_bill_pkg->recur != 0
2260 ? sprintf("%.2f", $cust_bill_pkg->recur )
2262 ( $cust_bill_pkg->sdate
2263 ? time2str("%x", $cust_bill_pkg->sdate)
2265 ($cust_bill_pkg->edate
2266 ? time2str("%x", $cust_bill_pkg->edate)
2270 } else { #pkgnum tax
2271 next unless $cust_bill_pkg->setup != 0;
2272 $pkg = $cust_bill_pkg->desc;
2273 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2274 ( $sdate, $edate ) = ( '', '' );
2280 ( map { '' } (1..11) ),
2281 ($pkg, $setup, $recur, $sdate, $edate)
2282 ) or die "can't create csv";
2284 $detail .= $csv->string. "\n";
2290 ( $header, $detail );
2296 Pays this invoice with a compliemntary payment. If there is an error,
2297 returns the error, otherwise returns false.
2303 my $cust_pay = new FS::cust_pay ( {
2304 'invnum' => $self->invnum,
2305 'paid' => $self->owed,
2308 'payinfo' => $self->cust_main->payinfo,
2316 Attempts to pay this invoice with a credit card payment via a
2317 Business::OnlinePayment realtime gateway. See
2318 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2319 for supported processors.
2325 $self->realtime_bop( 'CC', @_ );
2330 Attempts to pay this invoice with an electronic check (ACH) payment via a
2331 Business::OnlinePayment realtime gateway. See
2332 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2333 for supported processors.
2339 $self->realtime_bop( 'ECHECK', @_ );
2344 Attempts to pay this invoice with phone bill (LEC) payment via a
2345 Business::OnlinePayment realtime gateway. See
2346 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2347 for supported processors.
2353 $self->realtime_bop( 'LEC', @_ );
2357 my( $self, $method ) = (shift,shift);
2358 my $conf = $self->conf;
2361 my $cust_main = $self->cust_main;
2362 my $balance = $cust_main->balance;
2363 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2364 $amount = sprintf("%.2f", $amount);
2365 return "not run (balance $balance)" unless $amount > 0;
2367 my $description = 'Internet Services';
2368 if ( $conf->exists('business-onlinepayment-description') ) {
2369 my $dtempl = $conf->config('business-onlinepayment-description');
2371 my $agent_obj = $cust_main->agent
2372 or die "can't retreive agent for $cust_main (agentnum ".
2373 $cust_main->agentnum. ")";
2374 my $agent = $agent_obj->agent;
2375 my $pkgs = join(', ',
2376 map { $_->part_pkg->pkg }
2377 grep { $_->pkgnum } $self->cust_bill_pkg
2379 $description = eval qq("$dtempl");
2382 $cust_main->realtime_bop($method, $amount,
2383 'description' => $description,
2384 'invnum' => $self->invnum,
2385 #this didn't do what we want, it just calls apply_payments_and_credits
2387 'apply_to_invoice' => 1,
2390 #this changes application behavior: auto payments
2391 #triggered against a specific invoice are now applied
2392 #to that invoice instead of oldest open.
2398 =item batch_card OPTION => VALUE...
2400 Adds a payment for this invoice to the pending credit card batch (see
2401 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2402 runs the payment using a realtime gateway.
2407 my ($self, %options) = @_;
2408 my $cust_main = $self->cust_main;
2410 $options{invnum} = $self->invnum;
2412 $cust_main->batch_card(%options);
2415 sub _agent_template {
2417 $self->cust_main->agent_template;
2420 sub _agent_invoice_from {
2422 $self->cust_main->agent_invoice_from;
2425 =item invoice_barcode DIR_OR_FALSE
2427 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2428 it is taken as the temp directory where the PNG file will be generated and the
2429 PNG file name is returned. Otherwise, the PNG image itself is returned.
2433 sub invoice_barcode {
2434 my ($self, $dir) = (shift,shift);
2436 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2437 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2438 my $gd = $gdbar->plot(Height => 30);
2441 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2445 ) or die "can't open temp file: $!\n";
2446 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2447 my $png_file = $bh->filename;
2454 =item invnum_date_pretty
2456 Returns a string with the invoice number and date, for example:
2457 "Invoice #54 (3/20/2008)".
2459 Intended for back-end context, with regard to translation and date formatting.
2463 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2464 # for backend use (and also does the wrong thing, localizing for end customer
2465 # instead of backoffice configured date format)
2466 sub invnum_date_pretty {
2468 #$self->mt('Invoice #').
2469 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2470 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2473 #sub _items_extra_usage_sections {
2475 # my $escape = shift;
2477 # my %sections = ();
2479 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2480 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2482 # next unless $cust_bill_pkg->pkgnum > 0;
2484 # foreach my $section ( keys %usage_class ) {
2486 # my $usage = $cust_bill_pkg->usage($section);
2488 # next unless $usage && $usage > 0;
2490 # $sections{$section} ||= 0;
2491 # $sections{$section} += $usage;
2497 # map { { 'description' => &{$escape}($_),
2498 # 'subtotal' => $sections{$_},
2499 # 'summarized' => '',
2500 # 'tax_section' => '',
2503 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2507 sub _items_extra_usage_sections {
2509 my $conf = $self->conf;
2517 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2519 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2520 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2521 next unless $cust_bill_pkg->pkgnum > 0;
2523 foreach my $classnum ( keys %usage_class ) {
2524 my $section = $usage_class{$classnum}->classname;
2525 $classnums{$section} = $classnum;
2527 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2528 my $amount = $detail->amount;
2529 next unless $amount && $amount > 0;
2531 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2532 $sections{$section}{amount} += $amount; #subtotal
2533 $sections{$section}{calls}++;
2534 $sections{$section}{duration} += $detail->duration;
2536 my $desc = $detail->regionname;
2537 my $description = $desc;
2538 $description = substr($desc, 0, $maxlength). '...'
2539 if $format eq 'latex' && length($desc) > $maxlength;
2541 $lines{$section}{$desc} ||= {
2542 description => &{$escape}($description),
2543 #pkgpart => $part_pkg->pkgpart,
2544 pkgnum => $cust_bill_pkg->pkgnum,
2549 #unit_amount => $cust_bill_pkg->unitrecur,
2550 quantity => $cust_bill_pkg->quantity,
2551 product_code => 'N/A',
2552 ext_description => [],
2555 $lines{$section}{$desc}{amount} += $amount;
2556 $lines{$section}{$desc}{calls}++;
2557 $lines{$section}{$desc}{duration} += $detail->duration;
2563 my %sectionmap = ();
2564 foreach (keys %sections) {
2565 my $usage_class = $usage_class{$classnums{$_}};
2566 $sectionmap{$_} = { 'description' => &{$escape}($_),
2567 'amount' => $sections{$_}{amount}, #subtotal
2568 'calls' => $sections{$_}{calls},
2569 'duration' => $sections{$_}{duration},
2571 'tax_section' => '',
2572 'sort_weight' => $usage_class->weight,
2573 ( $usage_class->format
2574 ? ( map { $_ => $usage_class->$_($format) }
2575 qw( description_generator header_generator total_generator total_line_generator )
2582 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2586 foreach my $section ( keys %lines ) {
2587 foreach my $line ( keys %{$lines{$section}} ) {
2588 my $l = $lines{$section}{$line};
2589 $l->{section} = $sectionmap{$section};
2590 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2591 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2596 return(\@sections, \@lines);
2602 my $end = $self->_date;
2604 # start at date of previous invoice + 1 second or 0 if no previous invoice
2605 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2606 $start = 0 if !$start;
2609 my $cust_main = $self->cust_main;
2610 my @pkgs = $cust_main->all_pkgs;
2611 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2614 foreach my $pkg ( @pkgs ) {
2615 my @h_cust_svc = $pkg->h_cust_svc($end);
2616 foreach my $h_cust_svc ( @h_cust_svc ) {
2617 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2618 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2620 my $inserted = $h_cust_svc->date_inserted;
2621 my $deleted = $h_cust_svc->date_deleted;
2622 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2624 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2626 # DID either activated or ported in; cannot be both for same DID simultaneously
2627 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2628 && (!$phone_inserted->lnp_status
2629 || $phone_inserted->lnp_status eq ''
2630 || $phone_inserted->lnp_status eq 'native')) {
2633 else { # this one not so clean, should probably move to (h_)svc_phone
2634 my $phone_portedin = qsearchs( 'h_svc_phone',
2635 { 'svcnum' => $h_cust_svc->svcnum,
2636 'lnp_status' => 'portedin' },
2637 FS::h_svc_phone->sql_h_searchs($end),
2639 $num_portedin++ if $phone_portedin;
2642 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2643 if($deleted >= $start && $deleted <= $end && $phone_deleted
2644 && (!$phone_deleted->lnp_status
2645 || $phone_deleted->lnp_status ne 'portingout')) {
2648 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2649 && $phone_deleted->lnp_status
2650 && $phone_deleted->lnp_status eq 'portingout') {
2654 # increment usage minutes
2655 if ( $phone_inserted ) {
2656 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2657 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2660 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2663 # don't look at this service again
2664 push @seen, $h_cust_svc->svcnum;
2668 $minutes = sprintf("%d", $minutes);
2669 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2670 . "$num_deactivated Ported-Out: $num_portedout ",
2671 "Total Minutes: $minutes");
2674 sub _items_accountcode_cdr {
2679 my $section = { 'amount' => 0,
2682 'sort_weight' => '',
2684 'description' => 'Usage by Account Code',
2690 my %accountcodes = ();
2692 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2693 next unless $cust_bill_pkg->pkgnum > 0;
2695 my @header = $cust_bill_pkg->details_header;
2696 next unless scalar(@header);
2697 $section->{'header'} = join(',',@header);
2699 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2701 $section->{'header'} = $detail->formatted('format' => $format)
2702 if($detail->detail eq $section->{'header'});
2704 my $accountcode = $detail->accountcode;
2705 next unless $accountcode;
2707 my $amount = $detail->amount;
2708 next unless $amount && $amount > 0;
2710 $accountcodes{$accountcode} ||= {
2711 description => $accountcode,
2718 product_code => 'N/A',
2719 section => $section,
2720 ext_description => [ $section->{'header'} ],
2724 $section->{'amount'} += $amount;
2725 $accountcodes{$accountcode}{'amount'} += $amount;
2726 $accountcodes{$accountcode}{calls}++;
2727 $accountcodes{$accountcode}{duration} += $detail->duration;
2728 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2732 foreach my $l ( values %accountcodes ) {
2733 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2734 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2735 foreach my $sorted_detail ( @sorted_detail ) {
2736 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2738 delete $l->{detail_temp};
2742 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2744 return ($section,\@sorted_lines);
2747 sub _items_svc_phone_sections {
2749 my $conf = $self->conf;
2757 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2759 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2760 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2762 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2763 next unless $cust_bill_pkg->pkgnum > 0;
2765 my @header = $cust_bill_pkg->details_header;
2766 next unless scalar(@header);
2768 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2770 my $phonenum = $detail->phonenum;
2771 next unless $phonenum;
2773 my $amount = $detail->amount;
2774 next unless $amount && $amount > 0;
2776 $sections{$phonenum} ||= { 'amount' => 0,
2779 'sort_weight' => -1,
2780 'phonenum' => $phonenum,
2782 $sections{$phonenum}{amount} += $amount; #subtotal
2783 $sections{$phonenum}{calls}++;
2784 $sections{$phonenum}{duration} += $detail->duration;
2786 my $desc = $detail->regionname;
2787 my $description = $desc;
2788 $description = substr($desc, 0, $maxlength). '...'
2789 if $format eq 'latex' && length($desc) > $maxlength;
2791 $lines{$phonenum}{$desc} ||= {
2792 description => &{$escape}($description),
2793 #pkgpart => $part_pkg->pkgpart,
2801 product_code => 'N/A',
2802 ext_description => [],
2805 $lines{$phonenum}{$desc}{amount} += $amount;
2806 $lines{$phonenum}{$desc}{calls}++;
2807 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2809 my $line = $usage_class{$detail->classnum}->classname;
2810 $sections{"$phonenum $line"} ||=
2814 'sort_weight' => $usage_class{$detail->classnum}->weight,
2815 'phonenum' => $phonenum,
2816 'header' => [ @header ],
2818 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2819 $sections{"$phonenum $line"}{calls}++;
2820 $sections{"$phonenum $line"}{duration} += $detail->duration;
2822 $lines{"$phonenum $line"}{$desc} ||= {
2823 description => &{$escape}($description),
2824 #pkgpart => $part_pkg->pkgpart,
2832 product_code => 'N/A',
2833 ext_description => [],
2836 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2837 $lines{"$phonenum $line"}{$desc}{calls}++;
2838 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2839 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2840 $detail->formatted('format' => $format);
2845 my %sectionmap = ();
2846 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2847 foreach ( keys %sections ) {
2848 my @header = @{ $sections{$_}{header} || [] };
2850 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2851 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2852 my $usage_class = $summary ? $simple : $usage_simple;
2853 my $ending = $summary ? ' usage charges' : '';
2856 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2858 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2859 'amount' => $sections{$_}{amount}, #subtotal
2860 'calls' => $sections{$_}{calls},
2861 'duration' => $sections{$_}{duration},
2863 'tax_section' => '',
2864 'phonenum' => $sections{$_}{phonenum},
2865 'sort_weight' => $sections{$_}{sort_weight},
2866 'post_total' => $summary, #inspire pagebreak
2868 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2869 qw( description_generator
2872 total_line_generator
2879 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2880 $a->{sort_weight} <=> $b->{sort_weight}
2885 foreach my $section ( keys %lines ) {
2886 foreach my $line ( keys %{$lines{$section}} ) {
2887 my $l = $lines{$section}{$line};
2888 $l->{section} = $sectionmap{$section};
2889 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2890 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2895 if($conf->exists('phone_usage_class_summary')) {
2896 # this only works with Latex
2900 # after this, we'll have only two sections per DID:
2901 # Calls Summary and Calls Detail
2902 foreach my $section ( @sections ) {
2903 if($section->{'post_total'}) {
2904 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2905 $section->{'total_line_generator'} = sub { '' };
2906 $section->{'total_generator'} = sub { '' };
2907 $section->{'header_generator'} = sub { '' };
2908 $section->{'description_generator'} = '';
2909 push @newsections, $section;
2910 my %calls_detail = %$section;
2911 $calls_detail{'post_total'} = '';
2912 $calls_detail{'sort_weight'} = '';
2913 $calls_detail{'description_generator'} = sub { '' };
2914 $calls_detail{'header_generator'} = sub {
2915 return ' & Date/Time & Called Number & Duration & Price'
2916 if $format eq 'latex';
2919 $calls_detail{'description'} = 'Calls Detail: '
2920 . $section->{'phonenum'};
2921 push @newsections, \%calls_detail;
2925 # after this, each usage class is collapsed/summarized into a single
2926 # line under the Calls Summary section
2927 foreach my $newsection ( @newsections ) {
2928 if($newsection->{'post_total'}) { # this means Calls Summary
2929 foreach my $section ( @sections ) {
2930 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2931 && !$section->{'post_total'});
2932 my $newdesc = $section->{'description'};
2933 my $tn = $section->{'phonenum'};
2934 $newdesc =~ s/$tn//g;
2935 my $line = { ext_description => [],
2939 calls => $section->{'calls'},
2940 section => $newsection,
2941 duration => $section->{'duration'},
2942 description => $newdesc,
2943 amount => sprintf("%.2f",$section->{'amount'}),
2944 product_code => 'N/A',
2946 push @newlines, $line;
2951 # after this, Calls Details is populated with all CDRs
2952 foreach my $newsection ( @newsections ) {
2953 if(!$newsection->{'post_total'}) { # this means Calls Details
2954 foreach my $line ( @lines ) {
2955 next unless (scalar(@{$line->{'ext_description'}}) &&
2956 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2958 my @extdesc = @{$line->{'ext_description'}};
2960 foreach my $extdesc ( @extdesc ) {
2961 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2962 push @newextdesc, $extdesc;
2964 $line->{'ext_description'} = \@newextdesc;
2965 $line->{'section'} = $newsection;
2966 push @newlines, $line;
2971 return(\@newsections, \@newlines);
2974 return(\@sections, \@lines);
2978 =sub _items_usage_class_summary OPTIONS
2980 Returns a list of detail items summarizing the usage charges on this
2981 invoice. Each one will have 'amount', 'description' (the usage charge name),
2982 and 'usage_classnum'.
2984 OPTIONS can include 'escape' (a function to escape the descriptions).
2988 sub _items_usage_class_summary {
2992 my $escape = $opt{escape} || sub { $_[0] };
2993 my $invnum = $self->invnum;
2994 my @classes = qsearch({
2995 'table' => 'usage_class',
2996 'select' => 'classnum, classname, SUM(amount) AS amount',
2997 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2998 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2999 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
3000 ' GROUP BY classnum, classname, weight'.
3001 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
3002 ' ORDER BY weight ASC',
3006 description => &{$escape}($self->mt('Usage Summary')),
3010 foreach my $class (@classes) {
3012 'description' => &{$escape}($class->classname),
3013 'amount' => sprintf('%.2f', $class->amount),
3014 'usage_classnum' => $class->classnum,
3015 'section' => $section,
3021 sub _items_previous {
3023 my $conf = $self->conf;
3024 my $cust_main = $self->cust_main;
3025 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
3027 foreach ( @pr_cust_bill ) {
3028 my $date = $conf->exists('invoice_show_prior_due_date')
3029 ? 'due '. $_->due_date2str('short')
3030 : $self->time2str_local('short', $_->_date);
3032 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
3033 #'pkgpart' => 'N/A',
3035 'amount' => sprintf("%.2f", $_->owed),
3041 # 'description' => 'Previous Balance',
3042 # #'pkgpart' => 'N/A',
3043 # 'pkgnum' => 'N/A',
3044 # 'amount' => sprintf("%10.2f", $pr_total ),
3045 # 'ext_description' => [ map {
3046 # "Invoice ". $_->invnum.
3047 # " (". time2str("%x",$_->_date). ") ".
3048 # sprintf("%10.2f", $_->owed)
3049 # } @pr_cust_bill ],
3054 sub _items_credits {
3055 my( $self, %opt ) = @_;
3056 my $trim_len = $opt{'trim_len'} || 60;
3061 if ( $self->conf->exists('previous_balance-payments_since') ) {
3062 if ( $opt{'template'} eq 'statement' ) {
3063 # then the current bill is a "statement" (i.e. an invoice sent as
3064 # a payment receipt)
3065 # and in that case we want to see payments on or after THIS invoice
3066 @objects = qsearch('cust_credit', {
3067 'custnum' => $self->custnum,
3068 '_date' => {op => '>=', value => $self->_date},
3072 $date = $self->previous_bill->_date if $self->previous_bill;
3073 @objects = qsearch('cust_credit', {
3074 'custnum' => $self->custnum,
3075 '_date' => {op => '>=', value => $date},
3079 @objects = $self->cust_credited;
3082 foreach my $obj ( @objects ) {
3083 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3085 my $reason = substr($cust_credit->reason, 0, $trim_len);
3086 $reason .= '...' if length($reason) < length($cust_credit->reason);
3087 $reason = " ($reason) " if $reason;
3090 #'description' => 'Credit ref\#'. $_->crednum.
3091 # " (". time2str("%x",$_->cust_credit->_date) .")".
3093 'description' => $self->mt('Credit applied').' '.
3094 $self->time2str_local('short', $obj->_date). $reason,
3095 'amount' => sprintf("%.2f",$obj->amount),
3103 sub _items_payments {
3108 my $detailed = $self->conf->exists('invoice_payment_details');
3110 if ( $self->conf->exists('previous_balance-payments_since') ) {
3111 # then show payments dated on/after the previous bill...
3112 if ( $opt{'template'} eq 'statement' ) {
3113 # then the current bill is a "statement" (i.e. an invoice sent as
3114 # a payment receipt)
3115 # and in that case we want to see payments on or after THIS invoice
3116 @objects = qsearch('cust_pay', {
3117 'custnum' => $self->custnum,
3118 '_date' => {op => '>=', value => $self->_date},
3121 # the normal case: payments on or after the previous invoice
3123 $date = $self->previous_bill->_date if $self->previous_bill;
3124 @objects = qsearch('cust_pay', {
3125 'custnum' => $self->custnum,
3126 '_date' => {op => '>=', value => $date},
3128 # and before the current bill...
3129 @objects = grep { $_->_date < $self->_date } @objects;
3132 @objects = $self->cust_bill_pay;
3135 foreach my $obj (@objects) {
3136 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3137 my $desc = $self->mt('Payment received').' '.
3138 $self->time2str_local('short', $cust_pay->_date );
3139 $desc .= $self->mt(' via ') .
3140 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3144 'description' => $desc,
3145 'amount' => sprintf("%.2f", $obj->amount )
3153 =item call_details [ OPTION => VALUE ... ]
3155 Returns an array of CSV strings representing the call details for this invoice
3156 The only option available is the boolean prepend_billed_number
3161 my ($self, %opt) = @_;
3163 my $format_function = sub { shift };
3165 if ($opt{prepend_billed_number}) {
3166 $format_function = sub {
3170 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3175 my @details = map { $_->details( 'format_function' => $format_function,
3176 'escape_function' => sub{ return() },
3180 $self->cust_bill_pkg;
3181 my $header = $details[0];
3182 ( $header, grep { $_ ne $header } @details );
3192 =item process_reprint
3196 sub process_reprint {
3197 process_re_X('print', @_);
3200 =item process_reemail
3204 sub process_reemail {
3205 process_re_X('email', @_);
3213 process_re_X('fax', @_);
3221 process_re_X('ftp', @_);
3228 sub process_respool {
3229 process_re_X('spool', @_);
3232 use Storable qw(thaw);
3236 my( $method, $job ) = ( shift, shift );
3237 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3239 my $param = thaw(decode_base64(shift));
3240 warn Dumper($param) if $DEBUG;
3251 # spool_invoice ftp_invoice fax_invoice print_invoice
3252 my($method, $job, %param ) = @_;
3254 warn "re_X $method for job $job with param:\n".
3255 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3258 #some false laziness w/search/cust_bill.html
3260 my $orderby = 'ORDER BY cust_bill._date';
3262 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3264 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3266 my @cust_bill = qsearch( {
3267 #'select' => "cust_bill.*",
3268 'table' => 'cust_bill',
3269 'addl_from' => $addl_from,
3271 'extra_sql' => $extra_sql,
3272 'order_by' => $orderby,
3276 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3278 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3281 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3282 foreach my $cust_bill ( @cust_bill ) {
3283 $cust_bill->$method();
3285 if ( $job ) { #progressbar foo
3287 if ( time - $min_sec > $last ) {
3288 my $error = $job->update_statustext(
3289 int( 100 * $num / scalar(@cust_bill) )
3291 die $error if $error;
3302 =head1 CLASS METHODS
3308 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3313 my ($class, $start, $end) = @_;
3315 $class->paid_sql($start, $end). ' - '.
3316 $class->credited_sql($start, $end);
3321 Returns an SQL fragment to retreive the net amount (charged minus credited).
3326 my ($class, $start, $end) = @_;
3327 'charged - '. $class->credited_sql($start, $end);
3332 Returns an SQL fragment to retreive the amount paid against this invoice.
3337 my ($class, $start, $end) = @_;
3338 $start &&= "AND cust_bill_pay._date <= $start";
3339 $end &&= "AND cust_bill_pay._date > $end";
3340 $start = '' unless defined($start);
3341 $end = '' unless defined($end);
3342 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3343 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3348 Returns an SQL fragment to retreive the amount credited against this invoice.
3353 my ($class, $start, $end) = @_;
3354 $start &&= "AND cust_credit_bill._date <= $start";
3355 $end &&= "AND cust_credit_bill._date > $end";
3356 $start = '' unless defined($start);
3357 $end = '' unless defined($end);
3358 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3359 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3364 Returns an SQL fragment to retrieve the due date of an invoice.
3365 Currently only supported on PostgreSQL.
3370 my $conf = new FS::Conf;
3374 cust_bill.invoice_terms,
3375 cust_main.invoice_terms,
3376 \''.($conf->config('invoice_default_terms') || '').'\'
3377 ), E\'Net (\\\\d+)\'
3379 ) * 86400 + cust_bill._date'
3382 =item search_sql_where HASHREF
3384 Class method which returns an SQL WHERE fragment to search for parameters
3385 specified in HASHREF. Valid parameters are
3391 List reference of start date, end date, as UNIX timestamps.
3401 List reference of charged limits (exclusive).
3405 List reference of charged limits (exclusive).
3409 flag, return open invoices only
3413 flag, return net invoices only
3417 =item newest_percust
3421 Return only invoices belonging to that customer.
3425 Limit to that customer class (single value or arrayref).
3429 Limit to customers with that payment method (single value or arrayref).
3433 Limit to customers with that advertising source.
3437 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3441 sub search_sql_where {
3442 my($class, $param) = @_;
3444 warn "$me search_sql_where called with params: \n".
3445 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3451 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3452 push @search, "cust_main.agentnum = $1";
3456 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3457 push @search, "cust_main.refnum = $1";
3461 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3462 push @search, "cust_bill.custnum = $1";
3465 #customer classnum (false laziness w/ cust_main/Search.pm)
3466 if ( $param->{'cust_classnum'} ) {
3468 my @classnum = ref( $param->{'cust_classnum'} )
3469 ? @{ $param->{'cust_classnum'} }
3470 : ( $param->{'cust_classnum'} );
3472 @classnum = grep /^(\d*)$/, @classnum;
3475 push @search, '( '. join(' OR ', map {
3476 $_ ? "cust_main.classnum = $_"
3477 : "cust_main.classnum IS NULL"
3487 if ( $param->{payby} ) {
3488 my $payby = $param->{payby};
3489 $payby = [ $payby ] unless ref $payby;
3490 my $payby_in = join(',', map {dbh->quote($_)} @$payby);
3491 push @search, "cust_main.payby IN($payby_in)" if length($payby_in);
3495 if ( $param->{_date} ) {
3496 my($beginning, $ending) = @{$param->{_date}};
3498 push @search, "cust_bill._date >= $beginning",
3499 "cust_bill._date < $ending";
3503 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3504 push @search, "cust_bill.invnum >= $1";
3506 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3507 push @search, "cust_bill.invnum <= $1";
3511 if ( $param->{charged} ) {
3512 my @charged = ref($param->{charged})
3513 ? @{ $param->{charged} }
3514 : ($param->{charged});
3516 push @search, map { s/^charged/cust_bill.charged/; $_; }
3520 my $owed_sql = FS::cust_bill->owed_sql;
3523 if ( $param->{owed} ) {
3524 my @owed = ref($param->{owed})
3525 ? @{ $param->{owed} }
3527 push @search, map { s/^owed/$owed_sql/; $_; }
3532 push @search, "0 != $owed_sql"
3533 if $param->{'open'};
3534 push @search, '0 != '. FS::cust_bill->net_sql
3538 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3539 if $param->{'days'};
3542 if ( $param->{'newest_percust'} ) {
3544 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3545 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3547 my @newest_where = map { my $x = $_;
3548 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3551 grep ! /^cust_main./, @search;
3552 my $newest_where = scalar(@newest_where)
3553 ? ' AND '. join(' AND ', @newest_where)
3557 push @search, "cust_bill._date = (
3558 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3559 WHERE newest_cust_bill.custnum = cust_bill.custnum
3565 #promised_date - also has an option to accept nulls
3566 if ( $param->{promised_date} ) {
3567 my($beginning, $ending, $null) = @{$param->{promised_date}};
3569 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3570 "cust_bill.promised_date < $ending )" .
3571 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3574 #agent virtualization
3575 my $curuser = $FS::CurrentUser::CurrentUser;
3576 if ( $curuser->username eq 'fs_queue'
3577 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3579 my $newuser = qsearchs('access_user', {
3580 'username' => $username,
3584 $curuser = $newuser;
3586 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3589 push @search, $curuser->agentnums_sql;
3591 join(' AND ', @search );
3603 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3604 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base