2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $DEBUG $me $date_format );
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]';
44 #ask FS::UID to run this stuff for us later
45 FS::UID->install_callback( sub {
46 my $conf = new FS::Conf; #global
47 $date_format = $conf->config('date_format') || '%x'; #/YY
52 FS::cust_bill - Object methods for cust_bill records
58 $record = new FS::cust_bill \%hash;
59 $record = new FS::cust_bill { 'column' => 'value' };
61 $error = $record->insert;
63 $error = $new_record->replace($old_record);
65 $error = $record->delete;
67 $error = $record->check;
69 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
71 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
73 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
75 @cust_pay_objects = $cust_bill->cust_pay;
77 $tax_amount = $record->tax;
79 @lines = $cust_bill->print_text;
80 @lines = $cust_bill->print_text('time' => $time);
84 An FS::cust_bill object represents an invoice; a declaration that a customer
85 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
86 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
87 following fields are currently supported:
93 =item invnum - primary key (assigned automatically for new invoices)
95 =item custnum - customer (see L<FS::cust_main>)
97 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
98 L<Time::Local> and L<Date::Parse> for conversion functions.
100 =item charged - amount of this invoice
102 =item invoice_terms - optional terms override for this specific invoice
106 Customer info at invoice generation time
110 =item billing_balance - the customer's balance at the time the invoice was
111 generated (not including charges on this invoice)
113 =item previous_balance - the billing_balance of this customer's previous
114 invoice plus the charges on that invoice
122 =item printed - deprecated
130 =item closed - books closed flag, empty or `Y'
132 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
134 =item agent_invid - legacy invoice number
136 =item promised_date - customer promised payment date, for collection
146 Creates a new invoice. To add the invoice to the database, see L<"insert">.
147 Invoices are normally created by calling the bill method of a customer object
148 (see L<FS::cust_main>).
152 sub table { 'cust_bill'; }
154 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
155 # (except email_subject and invnum_date_pretty)
158 $self->conf->config('notice_name') || 'Invoice'
161 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
162 sub cust_unlinked_msg {
164 "WARNING: can't find cust_main.custnum ". $self->custnum.
165 ' (cust_bill.invnum '. $self->invnum. ')';
170 Adds this invoice to the database ("Posts" the invoice). If there is an error,
171 returns the error, otherwise returns false.
177 warn "$me insert called\n" if $DEBUG;
179 local $SIG{HUP} = 'IGNORE';
180 local $SIG{INT} = 'IGNORE';
181 local $SIG{QUIT} = 'IGNORE';
182 local $SIG{TERM} = 'IGNORE';
183 local $SIG{TSTP} = 'IGNORE';
184 local $SIG{PIPE} = 'IGNORE';
186 my $oldAutoCommit = $FS::UID::AutoCommit;
187 local $FS::UID::AutoCommit = 0;
190 my $error = $self->SUPER::insert;
192 $dbh->rollback if $oldAutoCommit;
196 if ( $self->get('cust_bill_pkg') ) {
197 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
198 $cust_bill_pkg->invnum($self->invnum);
199 my $error = $cust_bill_pkg->insert;
201 $dbh->rollback if $oldAutoCommit;
202 return "can't create invoice line item: $error";
207 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
214 Voids this invoice: deletes the invoice and adds a record of the voided invoice
215 to the FS::cust_bill_void table (and related tables starting from
216 FS::cust_bill_pkg_void).
222 my $reason = scalar(@_) ? shift : '';
224 local $SIG{HUP} = 'IGNORE';
225 local $SIG{INT} = 'IGNORE';
226 local $SIG{QUIT} = 'IGNORE';
227 local $SIG{TERM} = 'IGNORE';
228 local $SIG{TSTP} = 'IGNORE';
229 local $SIG{PIPE} = 'IGNORE';
231 my $oldAutoCommit = $FS::UID::AutoCommit;
232 local $FS::UID::AutoCommit = 0;
235 my $cust_bill_void = new FS::cust_bill_void ( {
236 map { $_ => $self->get($_) } $self->fields
238 $cust_bill_void->reason($reason);
239 my $error = $cust_bill_void->insert;
241 $dbh->rollback if $oldAutoCommit;
245 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
246 my $error = $cust_bill_pkg->void($reason);
248 $dbh->rollback if $oldAutoCommit;
253 $error = $self->delete;
255 $dbh->rollback if $oldAutoCommit;
259 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
267 This method now works but you probably shouldn't use it. Instead, apply a
268 credit against the invoice, or use the new void method.
270 Using this method to delete invoices outright is really, really bad. There
271 would be no record you ever posted this invoice, and there are no check to
272 make sure charged = 0 or that there are no associated cust_bill_pkg records.
274 Really, don't use it.
280 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
282 local $SIG{HUP} = 'IGNORE';
283 local $SIG{INT} = 'IGNORE';
284 local $SIG{QUIT} = 'IGNORE';
285 local $SIG{TERM} = 'IGNORE';
286 local $SIG{TSTP} = 'IGNORE';
287 local $SIG{PIPE} = 'IGNORE';
289 my $oldAutoCommit = $FS::UID::AutoCommit;
290 local $FS::UID::AutoCommit = 0;
293 foreach my $table (qw(
304 foreach my $linked ( $self->$table() ) {
305 my $error = $linked->delete;
307 $dbh->rollback if $oldAutoCommit;
314 my $error = $self->SUPER::delete(@_);
316 $dbh->rollback if $oldAutoCommit;
320 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
326 =item replace [ OLD_RECORD ]
328 You can, but probably shouldn't modify invoices...
330 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
331 supplied, replaces this record. If there is an error, returns the error,
332 otherwise returns false.
336 #replace can be inherited from Record.pm
338 # replace_check is now the preferred way to #implement replace data checks
339 # (so $object->replace() works without an argument)
342 my( $new, $old ) = ( shift, shift );
343 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
344 #return "Can't change _date!" unless $old->_date eq $new->_date;
345 return "Can't change _date" unless $old->_date == $new->_date;
346 return "Can't change charged" unless $old->charged == $new->charged
347 || $old->charged == 0
348 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
354 =item add_cc_surcharge
360 sub add_cc_surcharge {
361 my ($self, $pkgnum, $amount) = (shift, shift, shift);
364 my $cust_bill_pkg = new FS::cust_bill_pkg({
365 'invnum' => $self->invnum,
369 $error = $cust_bill_pkg->insert;
370 return $error if $error;
372 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
373 $self->charged($self->charged+$amount);
374 $error = $self->replace;
375 return $error if $error;
377 $self->apply_payments_and_credits;
383 Checks all fields to make sure this is a valid invoice. If there is an error,
384 returns the error, otherwise returns false. Called by the insert and replace
393 $self->ut_numbern('invnum')
394 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
395 || $self->ut_numbern('_date')
396 || $self->ut_money('charged')
397 || $self->ut_numbern('printed')
398 || $self->ut_enum('closed', [ '', 'Y' ])
399 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
400 || $self->ut_numbern('agent_invid') #varchar?
402 return $error if $error;
404 $self->_date(time) unless $self->_date;
406 $self->printed(0) if $self->printed eq '';
413 Returns the displayed invoice number for this invoice: agent_invid if
414 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
420 my $conf = $self->conf;
421 if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
422 return $self->agent_invid;
424 return $self->invnum;
430 Returns the customer's last invoice before this one.
436 if ( !$self->get('previous_bill') ) {
437 $self->set('previous_bill', qsearchs({
438 'table' => 'cust_bill',
439 'hashref' => { 'custnum' => $self->custnum,
440 '_date' => { op=>'<', value=>$self->_date } },
441 'order_by' => 'ORDER BY _date DESC LIMIT 1',
444 $self->get('previous_bill');
449 Returns a list consisting of the total previous balance for this customer,
450 followed by the previous outstanding invoices (as FS::cust_bill objects also).
457 my @cust_bill = sort { $a->_date <=> $b->_date }
458 grep { $_->owed != 0 }
459 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
460 #'_date' => { op=>'<', value=>$self->_date },
461 'invnum' => { op=>'<', value=>$self->invnum },
464 foreach ( @cust_bill ) { $total += $_->owed; }
468 =item enable_previous
470 Whether to show the 'Previous Charges' section when printing this invoice.
471 The negation of the 'disable_previous_balance' config setting.
475 sub enable_previous {
477 my $agentnum = $self->cust_main->agentnum;
478 !$self->conf->exists('disable_previous_balance', $agentnum);
483 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
490 { 'table' => 'cust_bill_pkg',
491 'hashref' => { 'invnum' => $self->invnum },
492 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
493 # the AUTLOADED FK search. or should
494 # that default to ORDER by the pkey?
499 =item cust_bill_pkg_pkgnum PKGNUM
501 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
506 sub cust_bill_pkg_pkgnum {
507 my( $self, $pkgnum ) = @_;
509 { 'table' => 'cust_bill_pkg',
510 'hashref' => { 'invnum' => $self->invnum,
513 'order_by' => 'ORDER BY billpkgnum',
520 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
527 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
528 $self->cust_bill_pkg;
530 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
535 Returns true if any of the packages (or their definitions) corresponding to the
536 line items for this invoice have the no_auto flag set.
542 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
545 =item open_cust_bill_pkg
547 Returns the open line items for this invoice.
549 Note that cust_bill_pkg with both setup and recur fees are returned as two
550 separate line items, each with only one fee.
554 # modeled after cust_main::open_cust_bill
555 sub open_cust_bill_pkg {
558 # grep { $_->owed > 0 } $self->cust_bill_pkg
560 my %other = ( 'recur' => 'setup',
561 'setup' => 'recur', );
563 foreach my $field ( qw( recur setup )) {
564 push @open, map { $_->set( $other{$field}, 0 ); $_; }
565 grep { $_->owed($field) > 0 }
566 $self->cust_bill_pkg;
572 =item cust_bill_event
574 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
578 sub cust_bill_event {
580 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
583 =item num_cust_bill_event
585 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
589 sub num_cust_bill_event {
592 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
593 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
594 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
595 $sth->fetchrow_arrayref->[0];
600 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
604 #false laziness w/cust_pkg.pm
608 'table' => 'cust_event',
609 'addl_from' => 'JOIN part_event USING ( eventpart )',
610 'hashref' => { 'tablenum' => $self->invnum },
611 'extra_sql' => " AND eventtable = 'cust_bill' ",
617 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
621 #false laziness w/cust_pkg.pm
625 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
626 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
627 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
628 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
629 $sth->fetchrow_arrayref->[0];
634 Returns the customer (see L<FS::cust_main>) for this invoice.
636 =item cust_suspend_if_balance_over AMOUNT
638 Suspends the customer associated with this invoice if the total amount owed on
639 this invoice and all older invoices is greater than the specified amount.
641 Returns a list: an empty list on success or a list of errors.
645 sub cust_suspend_if_balance_over {
646 my( $self, $amount ) = ( shift, shift );
647 my $cust_main = $self->cust_main;
648 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
651 $cust_main->suspend(@_);
657 Depreciated. See the cust_credited method.
659 #Returns a list consisting of the total previous credited (see
660 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
661 #outstanding credits (FS::cust_credit objects).
667 croak "FS::cust_bill->cust_credit depreciated; see ".
668 "FS::cust_bill->cust_credit_bill";
671 #my @cust_credit = sort { $a->_date <=> $b->_date }
672 # grep { $_->credited != 0 && $_->_date < $self->_date }
673 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
675 #foreach (@cust_credit) { $total += $_->credited; }
676 #$total, @cust_credit;
681 Depreciated. See the cust_bill_pay method.
683 #Returns all payments (see L<FS::cust_pay>) for this invoice.
689 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
691 #sort { $a->_date <=> $b->_date }
692 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
698 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
704 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
705 sort { $a->_date <=> $b->_date }
706 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
711 =item cust_credit_bill
713 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
719 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
720 sort { $a->_date <=> $b->_date }
721 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
725 sub cust_credit_bill {
726 shift->cust_credited(@_);
729 #=item cust_bill_pay_pkgnum PKGNUM
731 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
732 #with matching pkgnum.
736 #sub cust_bill_pay_pkgnum {
737 # my( $self, $pkgnum ) = @_;
738 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
739 # sort { $a->_date <=> $b->_date }
740 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
741 # 'pkgnum' => $pkgnum,
746 =item cust_bill_pay_pkg PKGNUM
748 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
749 applied against the matching pkgnum.
753 sub cust_bill_pay_pkg {
754 my( $self, $pkgnum ) = @_;
757 'select' => 'cust_bill_pay_pkg.*',
758 'table' => 'cust_bill_pay_pkg',
759 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
760 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
761 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
762 " AND cust_bill_pkg.pkgnum = $pkgnum",
767 #=item cust_credited_pkgnum PKGNUM
769 #=item cust_credit_bill_pkgnum PKGNUM
771 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
772 #with matching pkgnum.
776 #sub cust_credited_pkgnum {
777 # my( $self, $pkgnum ) = @_;
778 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
779 # sort { $a->_date <=> $b->_date }
780 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
781 # 'pkgnum' => $pkgnum,
786 #sub cust_credit_bill_pkgnum {
787 # shift->cust_credited_pkgnum(@_);
790 =item cust_credit_bill_pkg PKGNUM
792 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
793 applied against the matching pkgnum.
797 sub cust_credit_bill_pkg {
798 my( $self, $pkgnum ) = @_;
801 'select' => 'cust_credit_bill_pkg.*',
802 'table' => 'cust_credit_bill_pkg',
803 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
804 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
805 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
806 " AND cust_bill_pkg.pkgnum = $pkgnum",
811 =item cust_bill_batch
813 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
817 sub cust_bill_batch {
819 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
824 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
825 hash keyed by term length.
831 FS::discount_plan->all($self);
836 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
843 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
845 foreach (@taxlines) { $total += $_->setup; }
851 Returns the amount owed (still outstanding) on this invoice, which is charged
852 minus all payment applications (see L<FS::cust_bill_pay>) and credit
853 applications (see L<FS::cust_credit_bill>).
859 my $balance = $self->charged;
860 $balance -= $_->amount foreach ( $self->cust_bill_pay );
861 $balance -= $_->amount foreach ( $self->cust_credited );
862 $balance = sprintf( "%.2f", $balance);
863 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
868 my( $self, $pkgnum ) = @_;
870 #my $balance = $self->charged;
872 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
874 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
875 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
877 $balance = sprintf( "%.2f", $balance);
878 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
884 Returns true if this invoice should be hidden. See the
885 selfservice-hide_invoices-taxclass configuraiton setting.
891 my $conf = $self->conf;
892 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
894 my @cust_bill_pkg = $self->cust_bill_pkg;
895 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
896 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
899 =item apply_payments_and_credits [ OPTION => VALUE ... ]
901 Applies unapplied payments and credits to this invoice.
903 A hash of optional arguments may be passed. Currently "manual" is supported.
904 If true, a payment receipt is sent instead of a statement when
905 'payment_receipt_email' configuration option is set.
907 If there is an error, returns the error, otherwise returns false.
911 sub apply_payments_and_credits {
912 my( $self, %options ) = @_;
913 my $conf = $self->conf;
915 local $SIG{HUP} = 'IGNORE';
916 local $SIG{INT} = 'IGNORE';
917 local $SIG{QUIT} = 'IGNORE';
918 local $SIG{TERM} = 'IGNORE';
919 local $SIG{TSTP} = 'IGNORE';
920 local $SIG{PIPE} = 'IGNORE';
922 my $oldAutoCommit = $FS::UID::AutoCommit;
923 local $FS::UID::AutoCommit = 0;
926 $self->select_for_update; #mutex
928 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
929 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
931 if ( $conf->exists('pkg-balances') ) {
932 # limit @payments & @credits to those w/ a pkgnum grepped from $self
933 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
934 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
935 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
938 while ( $self->owed > 0 and ( @payments || @credits ) ) {
941 if ( @payments && @credits ) {
943 #decide which goes first by weight of top (unapplied) line item
945 my @open_lineitems = $self->open_cust_bill_pkg;
948 max( map { $_->part_pkg->pay_weight || 0 }
953 my $max_credit_weight =
954 max( map { $_->part_pkg->credit_weight || 0 }
960 #if both are the same... payments first? it has to be something
961 if ( $max_pay_weight >= $max_credit_weight ) {
967 } elsif ( @payments ) {
969 } elsif ( @credits ) {
972 die "guru meditation #12 and 35";
976 if ( $app eq 'pay' ) {
978 my $payment = shift @payments;
979 $unapp_amount = $payment->unapplied;
980 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
981 $app->pkgnum( $payment->pkgnum )
982 if $conf->exists('pkg-balances') && $payment->pkgnum;
984 } elsif ( $app eq 'credit' ) {
986 my $credit = shift @credits;
987 $unapp_amount = $credit->credited;
988 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
989 $app->pkgnum( $credit->pkgnum )
990 if $conf->exists('pkg-balances') && $credit->pkgnum;
993 die "guru meditation #12 and 35";
997 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
998 warn "owed_pkgnum ". $app->pkgnum;
999 $owed = $self->owed_pkgnum($app->pkgnum);
1001 $owed = $self->owed;
1003 next unless $owed > 0;
1005 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1006 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1008 $app->invnum( $self->invnum );
1010 my $error = $app->insert(%options);
1012 $dbh->rollback if $oldAutoCommit;
1013 return "Error inserting ". $app->table. " record: $error";
1015 die $error if $error;
1019 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1024 =item generate_email OPTION => VALUE ...
1032 sender address, required
1036 alternate template name, optional
1040 text attachment arrayref, optional
1044 email subject, optional
1048 notice name instead of "Invoice", optional
1052 Returns an argument list to be passed to L<FS::Misc::send_email>.
1058 sub generate_email {
1062 my $conf = $self->conf;
1064 my $me = '[FS::cust_bill::generate_email]';
1067 'from' => $args{'from'},
1068 'subject' => ($args{'subject'} || $self->email_subject),
1071 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1073 my $cust_main = $self->cust_main;
1075 if (ref($args{'to'}) eq 'ARRAY') {
1076 $return{'to'} = $args{'to'};
1078 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1079 $cust_main->invoicing_list
1083 if ( $conf->exists('invoice_html') ) {
1085 warn "$me creating HTML/text multipart message"
1088 $return{'nobody'} = 1;
1090 my $alternative = build MIME::Entity
1091 'Type' => 'multipart/alternative',
1092 #'Encoding' => '7bit',
1093 'Disposition' => 'inline'
1097 if ( $conf->exists('invoice_email_pdf')
1098 and scalar($conf->config('invoice_email_pdf_note')) ) {
1100 warn "$me using 'invoice_email_pdf_note' in multipart message"
1102 $data = [ map { $_ . "\n" }
1103 $conf->config('invoice_email_pdf_note')
1108 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1110 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1111 $data = $args{'print_text'};
1113 $data = [ $self->print_text(\%args) ];
1118 $alternative->attach(
1119 'Type' => 'text/plain',
1120 'Encoding' => 'quoted-printable',
1121 #'Encoding' => '7bit',
1123 'Disposition' => 'inline',
1130 if ( $conf->exists('invoice_email_pdf')
1131 and scalar($conf->config('invoice_email_pdf_note')) ) {
1133 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1137 $args{'from'} =~ /\@([\w\.\-]+)/;
1138 my $from = $1 || 'example.com';
1139 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1142 my $agentnum = $cust_main->agentnum;
1143 if ( defined($args{'template'}) && length($args{'template'})
1144 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1147 $logo = 'logo_'. $args{'template'}. '.png';
1151 my $image_data = $conf->config_binary( $logo, $agentnum);
1153 $image = build MIME::Entity
1154 'Type' => 'image/png',
1155 'Encoding' => 'base64',
1156 'Data' => $image_data,
1157 'Filename' => 'logo.png',
1158 'Content-ID' => "<$content_id>",
1161 if ($conf->exists('invoice-barcode')) {
1162 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1163 $barcode = build MIME::Entity
1164 'Type' => 'image/png',
1165 'Encoding' => 'base64',
1166 'Data' => $self->invoice_barcode(0),
1167 'Filename' => 'barcode.png',
1168 'Content-ID' => "<$barcode_content_id>",
1170 $args{'barcode_cid'} = $barcode_content_id;
1173 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1176 $alternative->attach(
1177 'Type' => 'text/html',
1178 'Encoding' => 'quoted-printable',
1179 'Data' => [ '<html>',
1182 ' '. encode_entities($return{'subject'}),
1185 ' <body bgcolor="#e8e8e8">',
1190 'Disposition' => 'inline',
1191 #'Filename' => 'invoice.pdf',
1195 my @otherparts = ();
1196 if ( $cust_main->email_csv_cdr ) {
1198 push @otherparts, build MIME::Entity
1199 'Type' => 'text/csv',
1200 'Encoding' => '7bit',
1201 'Data' => [ map { "$_\n" }
1202 $self->call_details('prepend_billed_number' => 1)
1204 'Disposition' => 'attachment',
1205 'Filename' => 'usage-'. $self->invnum. '.csv',
1210 if ( $conf->exists('invoice_email_pdf') ) {
1215 # multipart/alternative
1221 my $related = build MIME::Entity 'Type' => 'multipart/related',
1222 'Encoding' => '7bit';
1224 #false laziness w/Misc::send_email
1225 $related->head->replace('Content-type',
1226 $related->mime_type.
1227 '; boundary="'. $related->head->multipart_boundary. '"'.
1228 '; type=multipart/alternative'
1231 $related->add_part($alternative);
1233 $related->add_part($image) if $image;
1235 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1237 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1241 #no other attachment:
1243 # multipart/alternative
1248 $return{'content-type'} = 'multipart/related';
1249 if ($conf->exists('invoice-barcode') && $barcode) {
1250 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1252 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1254 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1255 #$return{'disposition'} = 'inline';
1261 if ( $conf->exists('invoice_email_pdf') ) {
1262 warn "$me creating PDF attachment"
1265 #mime parts arguments a la MIME::Entity->build().
1266 $return{'mimeparts'} = [
1267 { $self->mimebuild_pdf(\%args) }
1271 if ( $conf->exists('invoice_email_pdf')
1272 and scalar($conf->config('invoice_email_pdf_note')) ) {
1274 warn "$me using 'invoice_email_pdf_note'"
1276 $return{'body'} = [ map { $_ . "\n" }
1277 $conf->config('invoice_email_pdf_note')
1282 warn "$me not using 'invoice_email_pdf_note'"
1284 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1285 $return{'body'} = $args{'print_text'};
1287 $return{'body'} = [ $self->print_text(\%args) ];
1300 Returns a list suitable for passing to MIME::Entity->build(), representing
1301 this invoice as PDF attachment.
1308 'Type' => 'application/pdf',
1309 'Encoding' => 'base64',
1310 'Data' => [ $self->print_pdf(@_) ],
1311 'Disposition' => 'attachment',
1312 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1318 Sends this invoice to the destinations configured for this customer: sends
1319 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1321 Options can be passed as a hashref. Positional parameters are no longer
1324 I<template>: a suffix for alternate invoices
1326 I<agentnum>: obsolete, now does nothing.
1328 I<invoice_from> overrides the default email invoice From: address.
1330 I<amount>: obsolete, does nothing
1332 I<notice_name> overrides "Invoice" as the name of the sent document
1333 (templates from 10/2009 or newer required).
1335 I<lpr> overrides the system 'lpr' option as the command to print a document
1336 from standard input.
1342 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1343 my $conf = $self->conf;
1345 my $cust_main = $self->cust_main;
1347 my @invoicing_list = $cust_main->invoicing_list;
1350 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1351 && ! $self->invoice_noemail;
1354 if grep { $_ eq 'POST' } @invoicing_list; #postal
1356 #this has never been used post-$ORIGINAL_ISP afaik
1357 $self->fax_invoice($opt)
1358 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1364 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1366 Sends this invoice to the customer's email destination(s).
1368 Options must be passed as a hashref. Positional parameters are no longer
1371 I<template>, if specified, is the name of a suffix for alternate invoices.
1373 I<invoice_from>, if specified, overrides the default email invoice From:
1376 I<notice_name> is the name of the sent document.
1380 sub queueable_email {
1383 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1384 or die "invalid invoice number: " . $opt{invnum};
1386 my %args = map {$_ => $opt{$_}}
1388 qw( invoice_from notice_name no_coupon template );
1390 my $error = $self->email( \%args );
1391 die $error if $error;
1397 return if $self->hide;
1398 my $conf = $self->conf;
1399 my $opt = shift || {};
1400 if ($opt and !ref($opt)) {
1401 die "FS::cust_bill::email called with positional parameters";
1404 my $template = $opt->{template};
1405 my $from = delete $opt->{invoice_from};
1407 # this is where we set the From: address
1408 $from ||= $self->_agent_invoice_from || #XXX should go away
1409 $conf->config('invoice_from', $self->cust_main->agentnum );
1411 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1412 $self->cust_main->invoicing_list;
1414 if ( ! @invoicing_list ) { #no recipients
1415 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1416 die 'No recipients for customer #'. $self->custnum;
1418 #default: better to notify this person than silence
1419 @invoicing_list = ($from);
1423 # this is where we set the Subject:
1424 my $subject = $self->email_subject($template);
1426 my $error = send_email(
1427 $self->generate_email(
1429 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1430 'subject' => $subject,
1431 %$opt, # template, etc.
1434 die "can't email invoice: $error\n" if $error;
1435 #die "$error\n" if $error;
1441 my $conf = $self->conf;
1443 #my $template = scalar(@_) ? shift : '';
1446 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1449 my $cust_main = $self->cust_main;
1450 my $name = $cust_main->name;
1451 my $name_short = $cust_main->name_short;
1452 my $invoice_number = $self->invnum;
1453 my $invoice_date = $self->_date_pretty;
1455 eval qq("$subject");
1458 =item lpr_data HASHREF
1460 Returns the postscript or plaintext for this invoice as an arrayref.
1462 Options must be passed as a hashref. Positional parameters are no longer
1465 I<template>, if specified, is the name of a suffix for alternate invoices.
1467 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1473 my $conf = $self->conf;
1474 my $opt = shift || {};
1475 if ($opt and !ref($opt)) {
1476 # nobody does this anyway
1477 die "FS::cust_bill::lpr_data called with positional parameters";
1480 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1481 [ $self->$method( $opt ) ];
1486 Prints this invoice.
1488 Options must be passed as a hashref.
1490 I<template>, if specified, is the name of a suffix for alternate invoices.
1492 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1498 return if $self->hide;
1499 my $conf = $self->conf;
1500 my $opt = shift || {};
1501 if ($opt and !ref($opt)) {
1502 die "FS::cust_bill::print called with positional parameters";
1505 my $lpr = delete $opt->{lpr};
1506 if($conf->exists('invoice_print_pdf')) {
1507 # Add the invoice to the current batch.
1508 $self->batch_invoice($opt);
1512 $self->lpr_data($opt),
1513 'agentnum' => $self->cust_main->agentnum,
1519 =item fax_invoice HASHREF
1523 Options must be passed as a hashref.
1525 I<template>, if specified, is the name of a suffix for alternate invoices.
1527 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1533 return if $self->hide;
1534 my $conf = $self->conf;
1535 my $opt = shift || {};
1536 if ($opt and !ref($opt)) {
1537 die "FS::cust_bill::fax_invoice called with positional parameters";
1540 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1541 unless $conf->exists('invoice_latex');
1543 my $dialstring = $self->cust_main->getfield('fax');
1546 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1547 'dialstring' => $dialstring,
1549 die $error if $error;
1553 =item batch_invoice [ HASHREF ]
1555 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1556 isn't an open batch, one will be created.
1561 my ($self, $opt) = @_;
1562 my $bill_batch = $self->get_open_bill_batch;
1563 my $cust_bill_batch = FS::cust_bill_batch->new({
1564 batchnum => $bill_batch->batchnum,
1565 invnum => $self->invnum,
1567 return $cust_bill_batch->insert($opt);
1570 =item get_open_batch
1572 Returns the currently open batch as an FS::bill_batch object, creating a new
1573 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1578 sub get_open_bill_batch {
1580 my $conf = $self->conf;
1581 my $hashref = { status => 'O' };
1582 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1583 ? $self->cust_main->agentnum
1585 my $batch = qsearchs('bill_batch', $hashref);
1586 return $batch if $batch;
1587 $batch = FS::bill_batch->new($hashref);
1588 my $error = $batch->insert;
1589 die $error if $error;
1593 =item ftp_invoice [ TEMPLATENAME ]
1595 Sends this invoice data via FTP.
1597 TEMPLATENAME is unused?
1603 my $conf = $self->conf;
1604 my $template = scalar(@_) ? shift : '';
1607 'protocol' => 'ftp',
1608 'server' => $conf->config('cust_bill-ftpserver'),
1609 'username' => $conf->config('cust_bill-ftpusername'),
1610 'password' => $conf->config('cust_bill-ftppassword'),
1611 'dir' => $conf->config('cust_bill-ftpdir'),
1612 'format' => $conf->config('cust_bill-ftpformat'),
1616 =item spool_invoice [ TEMPLATENAME ]
1618 Spools this invoice data (see L<FS::spool_csv>)
1620 TEMPLATENAME is unused?
1626 my $conf = $self->conf;
1627 my $template = scalar(@_) ? shift : '';
1630 'format' => $conf->config('cust_bill-spoolformat'),
1631 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1635 =item send_csv OPTION => VALUE, ...
1637 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1641 protocol - currently only "ftp"
1647 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1648 and YYMMDDHHMMSS is a timestamp.
1650 See L</print_csv> for a description of the output format.
1655 my($self, %opt) = @_;
1659 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1660 mkdir $spooldir, 0700 unless -d $spooldir;
1662 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1663 my $file = "$spooldir/$tracctnum.csv";
1665 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1667 open(CSV, ">$file") or die "can't open $file: $!";
1675 if ( $opt{protocol} eq 'ftp' ) {
1676 eval "use Net::FTP;";
1678 $net = Net::FTP->new($opt{server}) or die @$;
1680 die "unknown protocol: $opt{protocol}";
1683 $net->login( $opt{username}, $opt{password} )
1684 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1686 $net->binary or die "can't set binary mode";
1688 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1690 $net->put($file) or die "can't put $file: $!";
1700 Spools CSV invoice data.
1706 =item format - any of FS::Misc::::Invoicing::spool_formats
1708 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1709 customer has the corresponding invoice destinations set (see
1710 L<FS::cust_main_invoice>).
1712 =item agent_spools - if set to a true value, will spool to per-agent files
1713 rather than a single global file
1715 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1716 append to that spool. L<FS::Cron::upload> will then send the spool file to
1719 =item balanceover - if set, only spools the invoice if the total amount owed on
1720 this invoice and all older invoices is greater than the specified amount.
1722 =item time - the "current time". Controls the printing of past due messages
1730 my($self, %opt) = @_;
1732 my $time = $opt{'time'} || time;
1733 my $cust_main = $self->cust_main;
1735 if ( $opt{'dest'} ) {
1736 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1737 $cust_main->invoicing_list;
1738 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1739 || ! keys %invoicing_list;
1742 if ( $opt{'balanceover'} ) {
1744 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1747 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1748 mkdir $spooldir, 0700 unless -d $spooldir;
1750 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1753 if ( $opt{'agent_spools'} ) {
1754 $file = 'agentnum'.$cust_main->agentnum;
1759 if ( $opt{'upload_targetnum'} ) {
1760 $spooldir .= '/target'.$opt{'upload_targetnum'};
1761 mkdir $spooldir, 0700 unless -d $spooldir;
1762 } # otherwise it just goes into export.xxx/cust_bill
1764 if ( lc($opt{'format'}) eq 'billco' ) {
1768 $file = "$spooldir/$file.csv";
1770 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1772 open(CSV, ">>$file") or die "can't open $file: $!";
1773 flock(CSV, LOCK_EX);
1778 if ( lc($opt{'format'}) eq 'billco' ) {
1780 flock(CSV, LOCK_UN);
1783 $file =~ s/-header.csv$/-detail.csv/;
1785 open(CSV,">>$file") or die "can't open $file: $!";
1786 flock(CSV, LOCK_EX);
1790 print CSV $detail if defined($detail);
1792 flock(CSV, LOCK_UN);
1799 =item print_csv OPTION => VALUE, ...
1801 Returns CSV data for this invoice.
1805 format - 'default', 'billco', 'oneline', 'bridgestone'
1807 Returns a list consisting of two scalars. The first is a single line of CSV
1808 header information for this invoice. The second is one or more lines of CSV
1809 detail information for this invoice.
1811 If I<format> is not specified or "default", the fields of the CSV file are as
1814 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1815 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1819 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1821 B<record_type> is C<cust_bill> for the initial header line only. The
1822 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1823 fields are filled in.
1825 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1826 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1829 =item invnum - invoice number
1831 =item custnum - customer number
1833 =item _date - invoice date
1835 =item charged - total invoice amount
1837 =item first - customer first name
1839 =item last - customer first name
1841 =item company - company name
1843 =item address1 - address line 1
1845 =item address2 - address line 1
1855 =item pkg - line item description
1857 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1859 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1861 =item sdate - start date for recurring fee
1863 =item edate - end date for recurring fee
1867 If I<format> is "billco", the fields of the header CSV file are as follows:
1869 +-------------------------------------------------------------------+
1870 | FORMAT HEADER FILE |
1871 |-------------------------------------------------------------------|
1872 | Field | Description | Name | Type | Width |
1873 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1874 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1875 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1876 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1877 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1878 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1879 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1880 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1881 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1882 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1883 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1884 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1885 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1886 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1887 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1888 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1889 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1890 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1891 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1892 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1893 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1894 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1895 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1896 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1897 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1898 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1899 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1900 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1901 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1902 +-------+-------------------------------+------------+------+-------+
1904 If I<format> is "billco", the fields of the detail CSV file are as follows:
1906 FORMAT FOR DETAIL FILE
1908 Field | Description | Name | Type | Width
1909 1 | N/A-Leave Empty | RC | CHAR | 2
1910 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1911 3 | Account Number | TRACCTNUM | CHAR | 15
1912 4 | Invoice Number | TRINVOICE | CHAR | 15
1913 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1914 6 | Transaction Detail | DETAILS | CHAR | 100
1915 7 | Amount | AMT | NUM* | 9
1916 8 | Line Format Control** | LNCTRL | CHAR | 2
1917 9 | Grouping Code | GROUP | CHAR | 2
1918 10 | User Defined | ACCT CODE | CHAR | 15
1920 If format is 'oneline', there is no detail file. Each invoice has a
1921 header line only, with the fields:
1923 Agent number, agent name, customer number, first name, last name, address
1924 line 1, address line 2, city, state, zip, invoice date, invoice number,
1925 amount charged, amount due, previous balance, due date.
1927 and then, for each line item, three columns containing the package number,
1928 description, and amount.
1930 If format is 'bridgestone', there is no detail file. Each invoice has a
1931 header line with the following fields in a fixed-width format:
1933 Customer number (in display format), date, name (first last), company,
1934 address 1, address 2, city, state, zip.
1936 This is a mailing list format, and has no per-invoice fields. To avoid
1937 sending redundant notices, the spooling event should have a "once" or
1938 "once_percust_every" condition.
1943 my($self, %opt) = @_;
1945 eval "use Text::CSV_XS";
1948 my $cust_main = $self->cust_main;
1950 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1951 my $format = lc($opt{'format'});
1953 my $time = $opt{'time'} || time;
1955 my $tracctnum = ''; #leaking out from billco-specific sections :/
1956 if ( $format eq 'billco' ) {
1959 $self->conf->config('billco-account_num', $cust_main->agentnum);
1961 $tracctnum = $account_num eq 'display_custnum'
1962 ? $cust_main->display_custnum
1963 : $opt{'tracctnum'};
1966 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1968 my $duedate = $self->due_date2str('%m/%d/%Y'); #date_format?
1970 my( $previous_balance, @unused ) = $self->previous; #previous balance
1972 my $pmt_cr_applied = 0;
1973 $pmt_cr_applied += $_->{'amount'}
1974 foreach ( $self->_items_payments, $self->_items_credits ) ;
1976 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1979 '', # 1 | N/A-Leave Empty CHAR 2
1980 '', # 2 | N/A-Leave Empty CHAR 15
1981 $tracctnum, # 3 | Transaction Account No CHAR 15
1982 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1983 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1984 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1985 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1986 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1987 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1988 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1989 '', # 10 | Ancillary Billing Information CHAR 30
1990 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1991 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1994 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1997 $duedate, # 14 | Bill Due Date CHAR 10
1999 $previous_balance, # 15 | Previous Balance NUM* 9
2000 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2001 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2002 $totaldue, # 18 | Total Amt Due NUM* 9
2003 $totaldue, # 19 | Total Amt Due NUM* 9
2004 '', # 20 | 30 Day Aging NUM* 9
2005 '', # 21 | 60 Day Aging NUM* 9
2006 '', # 22 | 90 Day Aging NUM* 9
2007 'N', # 23 | Y/N CHAR 1
2008 '', # 24 | Remittance automation CHAR 100
2009 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2010 $self->custnum, # 26 | Customer Reference Number CHAR 15
2011 '0', # 27 | Federal Tax*** NUM* 9
2012 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2013 '0', # 29 | Other Taxes & Fees*** NUM* 9
2016 } elsif ( $format eq 'oneline' ) { #name
2018 my ($previous_balance) = $self->previous;
2019 $previous_balance = sprintf('%.2f', $previous_balance);
2020 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2026 $self->_items_pkg, #_items_nontax? no sections or anything
2031 $cust_main->agentnum,
2032 $cust_main->agent->agent,
2036 $cust_main->company,
2037 $cust_main->address1,
2038 $cust_main->address2,
2044 time2str("%x", $self->_date),
2049 $self->due_date2str("%x"),
2054 } elsif ( $format eq 'bridgestone' ) {
2056 # bypass the CSV stuff and just return this
2057 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2058 my $zip = $cust_main->zip;
2060 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2064 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2066 $cust_main->display_custnum,
2068 uc(substr($cust_main->contact_firstlast,0,30)),
2069 uc(substr($cust_main->company ,0,30)),
2070 uc(substr($cust_main->address1 ,0,30)),
2071 uc(substr($cust_main->address2 ,0,30)),
2072 uc(substr($cust_main->city ,0,20)),
2073 uc($cust_main->state),
2079 } elsif ( $format eq 'ics' ) {
2081 my $bill = $cust_main->bill_location;
2082 my $zip = $bill->zip;
2086 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2091 # minor false laziness with print_generic
2092 my ($previous_balance) = $self->previous;
2093 my $balance_due = $self->owed + $previous_balance;
2094 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2095 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2098 if ( $self->due_date and $time >= $self->due_date ) {
2099 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2103 my $header = sprintf(
2104 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2105 $cust_main->display_custnum, #BID
2106 uc($cust_main->first), #FNAME
2107 uc($cust_main->last), #LNAME
2108 '00', #BATCH, should this ever be anything else?
2109 uc($cust_main->company), #COMP
2110 uc($bill->address1), #STREET1
2111 uc($bill->address2), #STREET2
2112 uc($bill->city), #CITY
2113 uc($bill->state), #STATE
2116 time2str('%Y%m%d', $self->_date), #BILL_DATE
2117 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2118 ( map {sprintf('%0.2f', $_)}
2119 $balance_due, #AMNT_DUE
2120 $previous_balance, #PREV_BAL
2121 $payment_total, #PYMT_RCVD
2122 $credit_total, #CREDITS
2123 $previous_balance, #BEG_BAL--is this correct?
2124 $self->charged, #NEW_CHRG
2127 $past_due, #PAST_MSG
2131 my %svc_class = ('' => ''); # maybe cache this more persistently?
2133 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2135 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2136 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2140 my @dates = ( $self->_date, undef );
2141 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2142 $dates[1] = $prev->sdate; #questionable
2145 # generate an 01 detail for each service
2146 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2147 foreach my $cust_svc ( @svcs ) {
2148 $show_pkgnum = ''; # hide it if we're showing svcnums
2150 my $svcpart = $cust_svc->svcpart;
2151 if (!exists($svc_class{$svcpart})) {
2152 my $classnum = $cust_svc->part_svc->classnum;
2153 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2155 $svc_class{$svcpart} = $part_svc_class ?
2156 $part_svc_class->classname :
2160 my @h_label = $cust_svc->label(@dates, 'I');
2161 push @details, sprintf('01%-9s%-20s%-47s',
2163 $svc_class{$svcpart},
2166 } #foreach $cust_svc
2169 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2170 if ($cust_bill_pkg->recur > 0) {
2171 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2172 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2174 push @details, sprintf('02%-6s%-60s%-10s',
2177 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2179 } #foreach $cust_bill_pkg
2181 # Tag this row so that we know whether this is one page (1), two pages
2182 # (2), # or "big" (B). The tag will be stripped off before uploading.
2183 if ( scalar(@details) < 12 ) {
2185 } elsif ( scalar(@details) < 58 ) {
2191 return join('', $header, @details, "\n");
2199 time2str("%x", $self->_date),
2200 sprintf("%.2f", $self->charged),
2201 ( map { $cust_main->getfield($_) }
2202 qw( first last company address1 address2 city state zip country ) ),
2204 ) or die "can't create csv";
2207 my $header = $csv->string. "\n";
2210 if ( lc($opt{'format'}) eq 'billco' ) {
2213 foreach my $item ( $self->_items_pkg ) {
2216 '', # 1 | N/A-Leave Empty CHAR 2
2217 '', # 2 | N/A-Leave Empty CHAR 15
2218 $tracctnum, # 3 | Account Number CHAR 15
2219 $self->invnum, # 4 | Invoice Number CHAR 15
2220 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2221 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2222 $item->{'amount'}, # 7 | Amount NUM* 9
2223 '', # 8 | Line Format Control** CHAR 2
2224 '', # 9 | Grouping Code CHAR 2
2225 '', # 10 | User Defined CHAR 15
2228 $detail .= $csv->string. "\n";
2232 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2238 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2240 my($pkg, $setup, $recur, $sdate, $edate);
2241 if ( $cust_bill_pkg->pkgnum ) {
2243 ($pkg, $setup, $recur, $sdate, $edate) = (
2244 $cust_bill_pkg->part_pkg->pkg,
2245 ( $cust_bill_pkg->setup != 0
2246 ? sprintf("%.2f", $cust_bill_pkg->setup )
2248 ( $cust_bill_pkg->recur != 0
2249 ? sprintf("%.2f", $cust_bill_pkg->recur )
2251 ( $cust_bill_pkg->sdate
2252 ? time2str("%x", $cust_bill_pkg->sdate)
2254 ($cust_bill_pkg->edate
2255 ?time2str("%x", $cust_bill_pkg->edate)
2259 } else { #pkgnum tax
2260 next unless $cust_bill_pkg->setup != 0;
2261 $pkg = $cust_bill_pkg->desc;
2262 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2263 ( $sdate, $edate ) = ( '', '' );
2269 ( map { '' } (1..11) ),
2270 ($pkg, $setup, $recur, $sdate, $edate)
2271 ) or die "can't create csv";
2273 $detail .= $csv->string. "\n";
2279 ( $header, $detail );
2285 Pays this invoice with a compliemntary payment. If there is an error,
2286 returns the error, otherwise returns false.
2292 my $cust_pay = new FS::cust_pay ( {
2293 'invnum' => $self->invnum,
2294 'paid' => $self->owed,
2297 'payinfo' => $self->cust_main->payinfo,
2305 Attempts to pay this invoice with a credit card payment via a
2306 Business::OnlinePayment realtime gateway. See
2307 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2308 for supported processors.
2314 $self->realtime_bop( 'CC', @_ );
2319 Attempts to pay this invoice with an electronic check (ACH) payment via a
2320 Business::OnlinePayment realtime gateway. See
2321 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2322 for supported processors.
2328 $self->realtime_bop( 'ECHECK', @_ );
2333 Attempts to pay this invoice with phone bill (LEC) payment via a
2334 Business::OnlinePayment realtime gateway. See
2335 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2336 for supported processors.
2342 $self->realtime_bop( 'LEC', @_ );
2346 my( $self, $method ) = (shift,shift);
2347 my $conf = $self->conf;
2350 my $cust_main = $self->cust_main;
2351 my $balance = $cust_main->balance;
2352 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2353 $amount = sprintf("%.2f", $amount);
2354 return "not run (balance $balance)" unless $amount > 0;
2356 my $description = 'Internet Services';
2357 if ( $conf->exists('business-onlinepayment-description') ) {
2358 my $dtempl = $conf->config('business-onlinepayment-description');
2360 my $agent_obj = $cust_main->agent
2361 or die "can't retreive agent for $cust_main (agentnum ".
2362 $cust_main->agentnum. ")";
2363 my $agent = $agent_obj->agent;
2364 my $pkgs = join(', ',
2365 map { $_->part_pkg->pkg }
2366 grep { $_->pkgnum } $self->cust_bill_pkg
2368 $description = eval qq("$dtempl");
2371 $cust_main->realtime_bop($method, $amount,
2372 'description' => $description,
2373 'invnum' => $self->invnum,
2374 #this didn't do what we want, it just calls apply_payments_and_credits
2376 'apply_to_invoice' => 1,
2379 #this changes application behavior: auto payments
2380 #triggered against a specific invoice are now applied
2381 #to that invoice instead of oldest open.
2387 =item batch_card OPTION => VALUE...
2389 Adds a payment for this invoice to the pending credit card batch (see
2390 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2391 runs the payment using a realtime gateway.
2396 my ($self, %options) = @_;
2397 my $cust_main = $self->cust_main;
2399 $options{invnum} = $self->invnum;
2401 $cust_main->batch_card(%options);
2404 sub _agent_template {
2406 $self->cust_main->agent_template;
2409 sub _agent_invoice_from {
2411 $self->cust_main->agent_invoice_from;
2414 =item invoice_barcode DIR_OR_FALSE
2416 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2417 it is taken as the temp directory where the PNG file will be generated and the
2418 PNG file name is returned. Otherwise, the PNG image itself is returned.
2422 sub invoice_barcode {
2423 my ($self, $dir) = (shift,shift);
2425 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2426 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2427 my $gd = $gdbar->plot(Height => 30);
2430 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2434 ) or die "can't open temp file: $!\n";
2435 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2436 my $png_file = $bh->filename;
2443 =item invnum_date_pretty
2445 Returns a string with the invoice number and date, for example:
2446 "Invoice #54 (3/20/2008)"
2450 sub invnum_date_pretty {
2452 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2455 #sub _items_extra_usage_sections {
2457 # my $escape = shift;
2459 # my %sections = ();
2461 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2462 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2464 # next unless $cust_bill_pkg->pkgnum > 0;
2466 # foreach my $section ( keys %usage_class ) {
2468 # my $usage = $cust_bill_pkg->usage($section);
2470 # next unless $usage && $usage > 0;
2472 # $sections{$section} ||= 0;
2473 # $sections{$section} += $usage;
2479 # map { { 'description' => &{$escape}($_),
2480 # 'subtotal' => $sections{$_},
2481 # 'summarized' => '',
2482 # 'tax_section' => '',
2485 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2489 sub _items_extra_usage_sections {
2491 my $conf = $self->conf;
2499 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2501 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2502 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2503 next unless $cust_bill_pkg->pkgnum > 0;
2505 foreach my $classnum ( keys %usage_class ) {
2506 my $section = $usage_class{$classnum}->classname;
2507 $classnums{$section} = $classnum;
2509 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2510 my $amount = $detail->amount;
2511 next unless $amount && $amount > 0;
2513 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2514 $sections{$section}{amount} += $amount; #subtotal
2515 $sections{$section}{calls}++;
2516 $sections{$section}{duration} += $detail->duration;
2518 my $desc = $detail->regionname;
2519 my $description = $desc;
2520 $description = substr($desc, 0, $maxlength). '...'
2521 if $format eq 'latex' && length($desc) > $maxlength;
2523 $lines{$section}{$desc} ||= {
2524 description => &{$escape}($description),
2525 #pkgpart => $part_pkg->pkgpart,
2526 pkgnum => $cust_bill_pkg->pkgnum,
2531 #unit_amount => $cust_bill_pkg->unitrecur,
2532 quantity => $cust_bill_pkg->quantity,
2533 product_code => 'N/A',
2534 ext_description => [],
2537 $lines{$section}{$desc}{amount} += $amount;
2538 $lines{$section}{$desc}{calls}++;
2539 $lines{$section}{$desc}{duration} += $detail->duration;
2545 my %sectionmap = ();
2546 foreach (keys %sections) {
2547 my $usage_class = $usage_class{$classnums{$_}};
2548 $sectionmap{$_} = { 'description' => &{$escape}($_),
2549 'amount' => $sections{$_}{amount}, #subtotal
2550 'calls' => $sections{$_}{calls},
2551 'duration' => $sections{$_}{duration},
2553 'tax_section' => '',
2554 'sort_weight' => $usage_class->weight,
2555 ( $usage_class->format
2556 ? ( map { $_ => $usage_class->$_($format) }
2557 qw( description_generator header_generator total_generator total_line_generator )
2564 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2568 foreach my $section ( keys %lines ) {
2569 foreach my $line ( keys %{$lines{$section}} ) {
2570 my $l = $lines{$section}{$line};
2571 $l->{section} = $sectionmap{$section};
2572 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2573 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2578 return(\@sections, \@lines);
2584 my $end = $self->_date;
2586 # start at date of previous invoice + 1 second or 0 if no previous invoice
2587 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2588 $start = 0 if !$start;
2591 my $cust_main = $self->cust_main;
2592 my @pkgs = $cust_main->all_pkgs;
2593 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2596 foreach my $pkg ( @pkgs ) {
2597 my @h_cust_svc = $pkg->h_cust_svc($end);
2598 foreach my $h_cust_svc ( @h_cust_svc ) {
2599 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2600 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2602 my $inserted = $h_cust_svc->date_inserted;
2603 my $deleted = $h_cust_svc->date_deleted;
2604 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2606 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2608 # DID either activated or ported in; cannot be both for same DID simultaneously
2609 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2610 && (!$phone_inserted->lnp_status
2611 || $phone_inserted->lnp_status eq ''
2612 || $phone_inserted->lnp_status eq 'native')) {
2615 else { # this one not so clean, should probably move to (h_)svc_phone
2616 my $phone_portedin = qsearchs( 'h_svc_phone',
2617 { 'svcnum' => $h_cust_svc->svcnum,
2618 'lnp_status' => 'portedin' },
2619 FS::h_svc_phone->sql_h_searchs($end),
2621 $num_portedin++ if $phone_portedin;
2624 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2625 if($deleted >= $start && $deleted <= $end && $phone_deleted
2626 && (!$phone_deleted->lnp_status
2627 || $phone_deleted->lnp_status ne 'portingout')) {
2630 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2631 && $phone_deleted->lnp_status
2632 && $phone_deleted->lnp_status eq 'portingout') {
2636 # increment usage minutes
2637 if ( $phone_inserted ) {
2638 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2639 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2642 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2645 # don't look at this service again
2646 push @seen, $h_cust_svc->svcnum;
2650 $minutes = sprintf("%d", $minutes);
2651 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2652 . "$num_deactivated Ported-Out: $num_portedout ",
2653 "Total Minutes: $minutes");
2656 sub _items_accountcode_cdr {
2661 my $section = { 'amount' => 0,
2664 'sort_weight' => '',
2666 'description' => 'Usage by Account Code',
2672 my %accountcodes = ();
2674 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2675 next unless $cust_bill_pkg->pkgnum > 0;
2677 my @header = $cust_bill_pkg->details_header;
2678 next unless scalar(@header);
2679 $section->{'header'} = join(',',@header);
2681 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2683 $section->{'header'} = $detail->formatted('format' => $format)
2684 if($detail->detail eq $section->{'header'});
2686 my $accountcode = $detail->accountcode;
2687 next unless $accountcode;
2689 my $amount = $detail->amount;
2690 next unless $amount && $amount > 0;
2692 $accountcodes{$accountcode} ||= {
2693 description => $accountcode,
2700 product_code => 'N/A',
2701 section => $section,
2702 ext_description => [ $section->{'header'} ],
2706 $section->{'amount'} += $amount;
2707 $accountcodes{$accountcode}{'amount'} += $amount;
2708 $accountcodes{$accountcode}{calls}++;
2709 $accountcodes{$accountcode}{duration} += $detail->duration;
2710 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2714 foreach my $l ( values %accountcodes ) {
2715 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2716 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2717 foreach my $sorted_detail ( @sorted_detail ) {
2718 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2720 delete $l->{detail_temp};
2724 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2726 return ($section,\@sorted_lines);
2729 sub _items_svc_phone_sections {
2731 my $conf = $self->conf;
2739 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2741 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2742 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2744 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2745 next unless $cust_bill_pkg->pkgnum > 0;
2747 my @header = $cust_bill_pkg->details_header;
2748 next unless scalar(@header);
2750 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2752 my $phonenum = $detail->phonenum;
2753 next unless $phonenum;
2755 my $amount = $detail->amount;
2756 next unless $amount && $amount > 0;
2758 $sections{$phonenum} ||= { 'amount' => 0,
2761 'sort_weight' => -1,
2762 'phonenum' => $phonenum,
2764 $sections{$phonenum}{amount} += $amount; #subtotal
2765 $sections{$phonenum}{calls}++;
2766 $sections{$phonenum}{duration} += $detail->duration;
2768 my $desc = $detail->regionname;
2769 my $description = $desc;
2770 $description = substr($desc, 0, $maxlength). '...'
2771 if $format eq 'latex' && length($desc) > $maxlength;
2773 $lines{$phonenum}{$desc} ||= {
2774 description => &{$escape}($description),
2775 #pkgpart => $part_pkg->pkgpart,
2783 product_code => 'N/A',
2784 ext_description => [],
2787 $lines{$phonenum}{$desc}{amount} += $amount;
2788 $lines{$phonenum}{$desc}{calls}++;
2789 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2791 my $line = $usage_class{$detail->classnum}->classname;
2792 $sections{"$phonenum $line"} ||=
2796 'sort_weight' => $usage_class{$detail->classnum}->weight,
2797 'phonenum' => $phonenum,
2798 'header' => [ @header ],
2800 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2801 $sections{"$phonenum $line"}{calls}++;
2802 $sections{"$phonenum $line"}{duration} += $detail->duration;
2804 $lines{"$phonenum $line"}{$desc} ||= {
2805 description => &{$escape}($description),
2806 #pkgpart => $part_pkg->pkgpart,
2814 product_code => 'N/A',
2815 ext_description => [],
2818 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2819 $lines{"$phonenum $line"}{$desc}{calls}++;
2820 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2821 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2822 $detail->formatted('format' => $format);
2827 my %sectionmap = ();
2828 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2829 foreach ( keys %sections ) {
2830 my @header = @{ $sections{$_}{header} || [] };
2832 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2833 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2834 my $usage_class = $summary ? $simple : $usage_simple;
2835 my $ending = $summary ? ' usage charges' : '';
2838 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2840 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2841 'amount' => $sections{$_}{amount}, #subtotal
2842 'calls' => $sections{$_}{calls},
2843 'duration' => $sections{$_}{duration},
2845 'tax_section' => '',
2846 'phonenum' => $sections{$_}{phonenum},
2847 'sort_weight' => $sections{$_}{sort_weight},
2848 'post_total' => $summary, #inspire pagebreak
2850 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2851 qw( description_generator
2854 total_line_generator
2861 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2862 $a->{sort_weight} <=> $b->{sort_weight}
2867 foreach my $section ( keys %lines ) {
2868 foreach my $line ( keys %{$lines{$section}} ) {
2869 my $l = $lines{$section}{$line};
2870 $l->{section} = $sectionmap{$section};
2871 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2872 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2877 if($conf->exists('phone_usage_class_summary')) {
2878 # this only works with Latex
2882 # after this, we'll have only two sections per DID:
2883 # Calls Summary and Calls Detail
2884 foreach my $section ( @sections ) {
2885 if($section->{'post_total'}) {
2886 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2887 $section->{'total_line_generator'} = sub { '' };
2888 $section->{'total_generator'} = sub { '' };
2889 $section->{'header_generator'} = sub { '' };
2890 $section->{'description_generator'} = '';
2891 push @newsections, $section;
2892 my %calls_detail = %$section;
2893 $calls_detail{'post_total'} = '';
2894 $calls_detail{'sort_weight'} = '';
2895 $calls_detail{'description_generator'} = sub { '' };
2896 $calls_detail{'header_generator'} = sub {
2897 return ' & Date/Time & Called Number & Duration & Price'
2898 if $format eq 'latex';
2901 $calls_detail{'description'} = 'Calls Detail: '
2902 . $section->{'phonenum'};
2903 push @newsections, \%calls_detail;
2907 # after this, each usage class is collapsed/summarized into a single
2908 # line under the Calls Summary section
2909 foreach my $newsection ( @newsections ) {
2910 if($newsection->{'post_total'}) { # this means Calls Summary
2911 foreach my $section ( @sections ) {
2912 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2913 && !$section->{'post_total'});
2914 my $newdesc = $section->{'description'};
2915 my $tn = $section->{'phonenum'};
2916 $newdesc =~ s/$tn//g;
2917 my $line = { ext_description => [],
2921 calls => $section->{'calls'},
2922 section => $newsection,
2923 duration => $section->{'duration'},
2924 description => $newdesc,
2925 amount => sprintf("%.2f",$section->{'amount'}),
2926 product_code => 'N/A',
2928 push @newlines, $line;
2933 # after this, Calls Details is populated with all CDRs
2934 foreach my $newsection ( @newsections ) {
2935 if(!$newsection->{'post_total'}) { # this means Calls Details
2936 foreach my $line ( @lines ) {
2937 next unless (scalar(@{$line->{'ext_description'}}) &&
2938 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2940 my @extdesc = @{$line->{'ext_description'}};
2942 foreach my $extdesc ( @extdesc ) {
2943 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2944 push @newextdesc, $extdesc;
2946 $line->{'ext_description'} = \@newextdesc;
2947 $line->{'section'} = $newsection;
2948 push @newlines, $line;
2953 return(\@newsections, \@newlines);
2956 return(\@sections, \@lines);
2960 sub _items_previous {
2962 my $conf = $self->conf;
2963 my $cust_main = $self->cust_main;
2964 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2966 foreach ( @pr_cust_bill ) {
2967 my $date = $conf->exists('invoice_show_prior_due_date')
2968 ? 'due '. $_->due_date2str($date_format)
2969 : time2str($date_format, $_->_date);
2971 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2972 #'pkgpart' => 'N/A',
2974 'amount' => sprintf("%.2f", $_->owed),
2980 # 'description' => 'Previous Balance',
2981 # #'pkgpart' => 'N/A',
2982 # 'pkgnum' => 'N/A',
2983 # 'amount' => sprintf("%10.2f", $pr_total ),
2984 # 'ext_description' => [ map {
2985 # "Invoice ". $_->invnum.
2986 # " (". time2str("%x",$_->_date). ") ".
2987 # sprintf("%10.2f", $_->owed)
2988 # } @pr_cust_bill ],
2993 sub _items_credits {
2994 my( $self, %opt ) = @_;
2995 my $trim_len = $opt{'trim_len'} || 60;
3000 if ( $self->conf->exists('previous_balance-payments_since') ) {
3002 $date = $self->previous_bill->_date if $self->previous_bill;
3003 @objects = qsearch('cust_credit', {
3004 'custnum' => $self->custnum,
3005 '_date' => {op => '>=', value => $date},
3007 # hard to do this in the qsearch...
3008 @objects = grep { $_->_date < $self->_date } @objects;
3010 @objects = $self->cust_credited;
3013 foreach my $obj ( @objects ) {
3014 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3016 my $reason = substr($cust_credit->reason, 0, $trim_len);
3017 $reason .= '...' if length($reason) < length($cust_credit->reason);
3018 $reason = " ($reason) " if $reason;
3021 #'description' => 'Credit ref\#'. $_->crednum.
3022 # " (". time2str("%x",$_->cust_credit->_date) .")".
3024 'description' => $self->mt('Credit applied').' '.
3025 time2str($date_format,$obj->_date). $reason,
3026 'amount' => sprintf("%.2f",$obj->amount),
3034 sub _items_payments {
3038 my $detailed = $self->conf->exists('invoice_payment_details');
3040 if ( $self->conf->exists('previous_balance-payments_since') ) {
3042 $date = $self->previous_bill->_date if $self->previous_bill;
3043 @objects = qsearch('cust_pay', {
3044 'custnum' => $self->custnum,
3045 '_date' => {op => '>=', value => $date},
3047 @objects = grep { $_->_date < $self->_date } @objects;
3049 @objects = $self->cust_bill_pay;
3052 foreach my $obj (@objects) {
3053 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3054 my $desc = $self->mt('Payment received').' '.
3055 time2str($date_format, $cust_pay->_date );
3056 $desc .= $self->mt(' via ') .
3057 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3061 'description' => $desc,
3062 'amount' => sprintf("%.2f", $obj->amount )
3070 =item call_details [ OPTION => VALUE ... ]
3072 Returns an array of CSV strings representing the call details for this invoice
3073 The only option available is the boolean prepend_billed_number
3078 my ($self, %opt) = @_;
3080 my $format_function = sub { shift };
3082 if ($opt{prepend_billed_number}) {
3083 $format_function = sub {
3087 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3092 my @details = map { $_->details( 'format_function' => $format_function,
3093 'escape_function' => sub{ return() },
3097 $self->cust_bill_pkg;
3098 my $header = $details[0];
3099 ( $header, grep { $_ ne $header } @details );
3109 =item process_reprint
3113 sub process_reprint {
3114 process_re_X('print', @_);
3117 =item process_reemail
3121 sub process_reemail {
3122 process_re_X('email', @_);
3130 process_re_X('fax', @_);
3138 process_re_X('ftp', @_);
3145 sub process_respool {
3146 process_re_X('spool', @_);
3149 use Storable qw(thaw);
3153 my( $method, $job ) = ( shift, shift );
3154 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3156 my $param = thaw(decode_base64(shift));
3157 warn Dumper($param) if $DEBUG;
3168 # spool_invoice ftp_invoice fax_invoice print_invoice
3169 my($method, $job, %param ) = @_;
3171 warn "re_X $method for job $job with param:\n".
3172 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3175 #some false laziness w/search/cust_bill.html
3177 my $orderby = 'ORDER BY cust_bill._date';
3179 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3181 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3183 my @cust_bill = qsearch( {
3184 #'select' => "cust_bill.*",
3185 'table' => 'cust_bill',
3186 'addl_from' => $addl_from,
3188 'extra_sql' => $extra_sql,
3189 'order_by' => $orderby,
3193 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3195 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3198 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3199 foreach my $cust_bill ( @cust_bill ) {
3200 $cust_bill->$method();
3202 if ( $job ) { #progressbar foo
3204 if ( time - $min_sec > $last ) {
3205 my $error = $job->update_statustext(
3206 int( 100 * $num / scalar(@cust_bill) )
3208 die $error if $error;
3219 =head1 CLASS METHODS
3225 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3230 my ($class, $start, $end) = @_;
3232 $class->paid_sql($start, $end). ' - '.
3233 $class->credited_sql($start, $end);
3238 Returns an SQL fragment to retreive the net amount (charged minus credited).
3243 my ($class, $start, $end) = @_;
3244 'charged - '. $class->credited_sql($start, $end);
3249 Returns an SQL fragment to retreive the amount paid against this invoice.
3254 my ($class, $start, $end) = @_;
3255 $start &&= "AND cust_bill_pay._date <= $start";
3256 $end &&= "AND cust_bill_pay._date > $end";
3257 $start = '' unless defined($start);
3258 $end = '' unless defined($end);
3259 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3260 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3265 Returns an SQL fragment to retreive the amount credited against this invoice.
3270 my ($class, $start, $end) = @_;
3271 $start &&= "AND cust_credit_bill._date <= $start";
3272 $end &&= "AND cust_credit_bill._date > $end";
3273 $start = '' unless defined($start);
3274 $end = '' unless defined($end);
3275 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3276 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3281 Returns an SQL fragment to retrieve the due date of an invoice.
3282 Currently only supported on PostgreSQL.
3287 my $conf = new FS::Conf;
3291 cust_bill.invoice_terms,
3292 cust_main.invoice_terms,
3293 \''.($conf->config('invoice_default_terms') || '').'\'
3294 ), E\'Net (\\\\d+)\'
3296 ) * 86400 + cust_bill._date'
3299 =item search_sql_where HASHREF
3301 Class method which returns an SQL WHERE fragment to search for parameters
3302 specified in HASHREF. Valid parameters are
3308 List reference of start date, end date, as UNIX timestamps.
3318 List reference of charged limits (exclusive).
3322 List reference of charged limits (exclusive).
3326 flag, return open invoices only
3330 flag, return net invoices only
3334 =item newest_percust
3338 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3342 sub search_sql_where {
3343 my($class, $param) = @_;
3345 warn "$me search_sql_where called with params: \n".
3346 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3352 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3353 push @search, "cust_main.agentnum = $1";
3357 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3358 push @search, "cust_main.refnum = $1";
3362 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3363 push @search, "cust_bill.custnum = $1";
3366 #customer classnum (false laziness w/ cust_main/Search.pm)
3367 if ( $param->{'cust_classnum'} ) {
3369 my @classnum = ref( $param->{'cust_classnum'} )
3370 ? @{ $param->{'cust_classnum'} }
3371 : ( $param->{'cust_classnum'} );
3373 @classnum = grep /^(\d*)$/, @classnum;
3376 push @search, '( '. join(' OR ', map {
3377 $_ ? "cust_main.classnum = $_"
3378 : "cust_main.classnum IS NULL"
3388 if ( $param->{_date} ) {
3389 my($beginning, $ending) = @{$param->{_date}};
3391 push @search, "cust_bill._date >= $beginning",
3392 "cust_bill._date < $ending";
3396 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3397 push @search, "cust_bill.invnum >= $1";
3399 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3400 push @search, "cust_bill.invnum <= $1";
3404 if ( $param->{charged} ) {
3405 my @charged = ref($param->{charged})
3406 ? @{ $param->{charged} }
3407 : ($param->{charged});
3409 push @search, map { s/^charged/cust_bill.charged/; $_; }
3413 my $owed_sql = FS::cust_bill->owed_sql;
3416 if ( $param->{owed} ) {
3417 my @owed = ref($param->{owed})
3418 ? @{ $param->{owed} }
3420 push @search, map { s/^owed/$owed_sql/; $_; }
3425 push @search, "0 != $owed_sql"
3426 if $param->{'open'};
3427 push @search, '0 != '. FS::cust_bill->net_sql
3431 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3432 if $param->{'days'};
3435 if ( $param->{'newest_percust'} ) {
3437 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3438 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3440 my @newest_where = map { my $x = $_;
3441 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3444 grep ! /^cust_main./, @search;
3445 my $newest_where = scalar(@newest_where)
3446 ? ' AND '. join(' AND ', @newest_where)
3450 push @search, "cust_bill._date = (
3451 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3452 WHERE newest_cust_bill.custnum = cust_bill.custnum
3458 #promised_date - also has an option to accept nulls
3459 if ( $param->{promised_date} ) {
3460 my($beginning, $ending, $null) = @{$param->{promised_date}};
3462 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3463 "cust_bill.promised_date < $ending )" .
3464 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3467 #agent virtualization
3468 my $curuser = $FS::CurrentUser::CurrentUser;
3469 if ( $curuser->username eq 'fs_queue'
3470 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3472 my $newuser = qsearchs('access_user', {
3473 'username' => $username,
3477 $curuser = $newuser;
3479 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3482 push @search, $curuser->agentnums_sql;
3484 join(' AND ', @search );
3496 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3497 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base