2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $DEBUG $me );
7 use Fcntl qw(:flock); #for spool_csv
9 use List::Util qw(min max sum);
13 use Storable qw( freeze thaw );
15 use FS::UID qw( datasrc );
16 use FS::Misc qw( send_email send_fax do_print );
17 use FS::Record qw( qsearch qsearchs dbh );
18 use FS::cust_statement;
19 use FS::cust_bill_pkg;
20 use FS::cust_bill_pkg_display;
21 use FS::cust_bill_pkg_detail;
25 use FS::cust_credit_bill;
27 use FS::cust_bill_event;
30 use FS::cust_bill_pay;
31 use FS::part_bill_event;
34 use FS::cust_bill_batch;
35 use FS::cust_bill_pay_pkg;
36 use FS::cust_credit_bill_pkg;
37 use FS::discount_plan;
38 use FS::cust_bill_void;
42 $me = '[FS::cust_bill]';
44 #ask FS::UID to run this stuff for us later
45 FS::UID->install_callback( sub {
46 my $conf = new FS::Conf; #global
51 FS::cust_bill - Object methods for cust_bill records
57 $record = new FS::cust_bill \%hash;
58 $record = new FS::cust_bill { 'column' => 'value' };
60 $error = $record->insert;
62 $error = $new_record->replace($old_record);
64 $error = $record->delete;
66 $error = $record->check;
68 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
70 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
72 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
74 @cust_pay_objects = $cust_bill->cust_pay;
76 $tax_amount = $record->tax;
78 @lines = $cust_bill->print_text;
79 @lines = $cust_bill->print_text('time' => $time);
83 An FS::cust_bill object represents an invoice; a declaration that a customer
84 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
85 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
86 following fields are currently supported:
92 =item invnum - primary key (assigned automatically for new invoices)
94 =item custnum - customer (see L<FS::cust_main>)
96 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
97 L<Time::Local> and L<Date::Parse> for conversion functions.
99 =item charged - amount of this invoice
101 =item invoice_terms - optional terms override for this specific invoice
105 Customer info at invoice generation time
109 =item billing_balance - the customer's balance at the time the invoice was
110 generated (not including charges on this invoice)
112 =item previous_balance - the billing_balance of this customer's previous
113 invoice plus the charges on that invoice
121 =item printed - deprecated
129 =item closed - books closed flag, empty or `Y'
131 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
133 =item agent_invid - legacy invoice number
135 =item promised_date - customer promised payment date, for collection
145 Creates a new invoice. To add the invoice to the database, see L<"insert">.
146 Invoices are normally created by calling the bill method of a customer object
147 (see L<FS::cust_main>).
151 sub table { 'cust_bill'; }
153 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
154 # (except email_subject and invnum_date_pretty)
157 $self->conf->config('notice_name') || 'Invoice'
160 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
161 sub cust_unlinked_msg {
163 "WARNING: can't find cust_main.custnum ". $self->custnum.
164 ' (cust_bill.invnum '. $self->invnum. ')';
169 Adds this invoice to the database ("Posts" the invoice). If there is an error,
170 returns the error, otherwise returns false.
176 warn "$me insert called\n" if $DEBUG;
178 local $SIG{HUP} = 'IGNORE';
179 local $SIG{INT} = 'IGNORE';
180 local $SIG{QUIT} = 'IGNORE';
181 local $SIG{TERM} = 'IGNORE';
182 local $SIG{TSTP} = 'IGNORE';
183 local $SIG{PIPE} = 'IGNORE';
185 my $oldAutoCommit = $FS::UID::AutoCommit;
186 local $FS::UID::AutoCommit = 0;
189 my $error = $self->SUPER::insert;
191 $dbh->rollback if $oldAutoCommit;
195 if ( $self->get('cust_bill_pkg') ) {
196 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
197 $cust_bill_pkg->invnum($self->invnum);
198 my $error = $cust_bill_pkg->insert;
200 $dbh->rollback if $oldAutoCommit;
201 return "can't create invoice line item: $error";
206 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
213 Voids this invoice: deletes the invoice and adds a record of the voided invoice
214 to the FS::cust_bill_void table (and related tables starting from
215 FS::cust_bill_pkg_void).
221 my $reason = scalar(@_) ? shift : '';
223 local $SIG{HUP} = 'IGNORE';
224 local $SIG{INT} = 'IGNORE';
225 local $SIG{QUIT} = 'IGNORE';
226 local $SIG{TERM} = 'IGNORE';
227 local $SIG{TSTP} = 'IGNORE';
228 local $SIG{PIPE} = 'IGNORE';
230 my $oldAutoCommit = $FS::UID::AutoCommit;
231 local $FS::UID::AutoCommit = 0;
234 my $cust_bill_void = new FS::cust_bill_void ( {
235 map { $_ => $self->get($_) } $self->fields
237 $cust_bill_void->reason($reason);
238 my $error = $cust_bill_void->insert;
240 $dbh->rollback if $oldAutoCommit;
244 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
245 my $error = $cust_bill_pkg->void($reason);
247 $dbh->rollback if $oldAutoCommit;
252 $error = $self->delete;
254 $dbh->rollback if $oldAutoCommit;
258 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
266 This method now works but you probably shouldn't use it. Instead, apply a
267 credit against the invoice, or use the new void method.
269 Using this method to delete invoices outright is really, really bad. There
270 would be no record you ever posted this invoice, and there are no check to
271 make sure charged = 0 or that there are no associated cust_bill_pkg records.
273 Really, don't use it.
279 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
281 local $SIG{HUP} = 'IGNORE';
282 local $SIG{INT} = 'IGNORE';
283 local $SIG{QUIT} = 'IGNORE';
284 local $SIG{TERM} = 'IGNORE';
285 local $SIG{TSTP} = 'IGNORE';
286 local $SIG{PIPE} = 'IGNORE';
288 my $oldAutoCommit = $FS::UID::AutoCommit;
289 local $FS::UID::AutoCommit = 0;
292 foreach my $table (qw(
303 foreach my $linked ( $self->$table() ) {
304 my $error = $linked->delete;
306 $dbh->rollback if $oldAutoCommit;
313 my $error = $self->SUPER::delete(@_);
315 $dbh->rollback if $oldAutoCommit;
319 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
325 =item replace [ OLD_RECORD ]
327 You can, but probably shouldn't modify invoices...
329 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
330 supplied, replaces this record. If there is an error, returns the error,
331 otherwise returns false.
335 #replace can be inherited from Record.pm
337 # replace_check is now the preferred way to #implement replace data checks
338 # (so $object->replace() works without an argument)
341 my( $new, $old ) = ( shift, shift );
342 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
343 #return "Can't change _date!" unless $old->_date eq $new->_date;
344 return "Can't change _date" unless $old->_date == $new->_date;
345 return "Can't change charged" unless $old->charged == $new->charged
346 || $old->charged == 0
347 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
353 =item add_cc_surcharge
359 sub add_cc_surcharge {
360 my ($self, $pkgnum, $amount) = (shift, shift, shift);
363 my $cust_bill_pkg = new FS::cust_bill_pkg({
364 'invnum' => $self->invnum,
368 $error = $cust_bill_pkg->insert;
369 return $error if $error;
371 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
372 $self->charged($self->charged+$amount);
373 $error = $self->replace;
374 return $error if $error;
376 $self->apply_payments_and_credits;
382 Checks all fields to make sure this is a valid invoice. If there is an error,
383 returns the error, otherwise returns false. Called by the insert and replace
392 $self->ut_numbern('invnum')
393 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
394 || $self->ut_numbern('_date')
395 || $self->ut_money('charged')
396 || $self->ut_numbern('printed')
397 || $self->ut_enum('closed', [ '', 'Y' ])
398 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
399 || $self->ut_numbern('agent_invid') #varchar?
401 return $error if $error;
403 $self->_date(time) unless $self->_date;
405 $self->printed(0) if $self->printed eq '';
412 Returns the displayed invoice number for this invoice: agent_invid if
413 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
419 my $conf = $self->conf;
420 if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
421 return $self->agent_invid;
423 return $self->invnum;
429 Returns the customer's last invoice before this one.
435 if ( !$self->get('previous_bill') ) {
436 $self->set('previous_bill', qsearchs({
437 'table' => 'cust_bill',
438 'hashref' => { 'custnum' => $self->custnum,
439 '_date' => { op=>'<', value=>$self->_date } },
440 'order_by' => 'ORDER BY _date DESC LIMIT 1',
443 $self->get('previous_bill');
448 Returns a list consisting of the total previous balance for this customer,
449 followed by the previous outstanding invoices (as FS::cust_bill objects also).
456 my @cust_bill = sort { $a->_date <=> $b->_date }
457 grep { $_->owed != 0 }
458 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
459 #'_date' => { op=>'<', value=>$self->_date },
460 'invnum' => { op=>'<', value=>$self->invnum },
463 foreach ( @cust_bill ) { $total += $_->owed; }
467 =item enable_previous
469 Whether to show the 'Previous Charges' section when printing this invoice.
470 The negation of the 'disable_previous_balance' config setting.
474 sub enable_previous {
476 my $agentnum = $self->cust_main->agentnum;
477 !$self->conf->exists('disable_previous_balance', $agentnum);
482 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
489 { 'table' => 'cust_bill_pkg',
490 'hashref' => { 'invnum' => $self->invnum },
491 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
492 # the AUTLOADED FK search. or should
493 # that default to ORDER by the pkey?
498 =item cust_bill_pkg_pkgnum PKGNUM
500 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
505 sub cust_bill_pkg_pkgnum {
506 my( $self, $pkgnum ) = @_;
508 { 'table' => 'cust_bill_pkg',
509 'hashref' => { 'invnum' => $self->invnum,
512 'order_by' => 'ORDER BY billpkgnum',
519 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
526 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
527 $self->cust_bill_pkg;
529 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
534 Returns true if any of the packages (or their definitions) corresponding to the
535 line items for this invoice have the no_auto flag set.
541 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
544 =item open_cust_bill_pkg
546 Returns the open line items for this invoice.
548 Note that cust_bill_pkg with both setup and recur fees are returned as two
549 separate line items, each with only one fee.
553 # modeled after cust_main::open_cust_bill
554 sub open_cust_bill_pkg {
557 # grep { $_->owed > 0 } $self->cust_bill_pkg
559 my %other = ( 'recur' => 'setup',
560 'setup' => 'recur', );
562 foreach my $field ( qw( recur setup )) {
563 push @open, map { $_->set( $other{$field}, 0 ); $_; }
564 grep { $_->owed($field) > 0 }
565 $self->cust_bill_pkg;
571 =item cust_bill_event
573 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
577 sub cust_bill_event {
579 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
582 =item num_cust_bill_event
584 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
588 sub num_cust_bill_event {
591 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
592 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
593 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
594 $sth->fetchrow_arrayref->[0];
599 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
603 #false laziness w/cust_pkg.pm
607 'table' => 'cust_event',
608 'addl_from' => 'JOIN part_event USING ( eventpart )',
609 'hashref' => { 'tablenum' => $self->invnum },
610 'extra_sql' => " AND eventtable = 'cust_bill' ",
616 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
620 #false laziness w/cust_pkg.pm
624 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
625 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
626 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
627 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
628 $sth->fetchrow_arrayref->[0];
633 Returns the customer (see L<FS::cust_main>) for this invoice.
635 =item cust_suspend_if_balance_over AMOUNT
637 Suspends the customer associated with this invoice if the total amount owed on
638 this invoice and all older invoices is greater than the specified amount.
640 Returns a list: an empty list on success or a list of errors.
644 sub cust_suspend_if_balance_over {
645 my( $self, $amount ) = ( shift, shift );
646 my $cust_main = $self->cust_main;
647 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
650 $cust_main->suspend(@_);
656 Depreciated. See the cust_credited method.
658 #Returns a list consisting of the total previous credited (see
659 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
660 #outstanding credits (FS::cust_credit objects).
666 croak "FS::cust_bill->cust_credit depreciated; see ".
667 "FS::cust_bill->cust_credit_bill";
670 #my @cust_credit = sort { $a->_date <=> $b->_date }
671 # grep { $_->credited != 0 && $_->_date < $self->_date }
672 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
674 #foreach (@cust_credit) { $total += $_->credited; }
675 #$total, @cust_credit;
680 Depreciated. See the cust_bill_pay method.
682 #Returns all payments (see L<FS::cust_pay>) for this invoice.
688 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
690 #sort { $a->_date <=> $b->_date }
691 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
697 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
703 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
704 sort { $a->_date <=> $b->_date }
705 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
710 =item cust_credit_bill
712 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
718 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
719 sort { $a->_date <=> $b->_date }
720 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
724 sub cust_credit_bill {
725 shift->cust_credited(@_);
728 #=item cust_bill_pay_pkgnum PKGNUM
730 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
731 #with matching pkgnum.
735 #sub cust_bill_pay_pkgnum {
736 # my( $self, $pkgnum ) = @_;
737 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
738 # sort { $a->_date <=> $b->_date }
739 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
740 # 'pkgnum' => $pkgnum,
745 =item cust_bill_pay_pkg PKGNUM
747 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
748 applied against the matching pkgnum.
752 sub cust_bill_pay_pkg {
753 my( $self, $pkgnum ) = @_;
756 'select' => 'cust_bill_pay_pkg.*',
757 'table' => 'cust_bill_pay_pkg',
758 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
759 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
760 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
761 " AND cust_bill_pkg.pkgnum = $pkgnum",
766 #=item cust_credited_pkgnum PKGNUM
768 #=item cust_credit_bill_pkgnum PKGNUM
770 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
771 #with matching pkgnum.
775 #sub cust_credited_pkgnum {
776 # my( $self, $pkgnum ) = @_;
777 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
778 # sort { $a->_date <=> $b->_date }
779 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
780 # 'pkgnum' => $pkgnum,
785 #sub cust_credit_bill_pkgnum {
786 # shift->cust_credited_pkgnum(@_);
789 =item cust_credit_bill_pkg PKGNUM
791 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
792 applied against the matching pkgnum.
796 sub cust_credit_bill_pkg {
797 my( $self, $pkgnum ) = @_;
800 'select' => 'cust_credit_bill_pkg.*',
801 'table' => 'cust_credit_bill_pkg',
802 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
803 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
804 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
805 " AND cust_bill_pkg.pkgnum = $pkgnum",
810 =item cust_bill_batch
812 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
816 sub cust_bill_batch {
818 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
823 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
824 hash keyed by term length.
830 FS::discount_plan->all($self);
835 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
842 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
844 foreach (@taxlines) { $total += $_->setup; }
850 Returns the amount owed (still outstanding) on this invoice, which is charged
851 minus all payment applications (see L<FS::cust_bill_pay>) and credit
852 applications (see L<FS::cust_credit_bill>).
858 my $balance = $self->charged;
859 $balance -= $_->amount foreach ( $self->cust_bill_pay );
860 $balance -= $_->amount foreach ( $self->cust_credited );
861 $balance = sprintf( "%.2f", $balance);
862 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
867 my( $self, $pkgnum ) = @_;
869 #my $balance = $self->charged;
871 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
873 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
874 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
876 $balance = sprintf( "%.2f", $balance);
877 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
883 Returns true if this invoice should be hidden. See the
884 selfservice-hide_invoices-taxclass configuraiton setting.
890 my $conf = $self->conf;
891 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
893 my @cust_bill_pkg = $self->cust_bill_pkg;
894 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
895 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
898 =item apply_payments_and_credits [ OPTION => VALUE ... ]
900 Applies unapplied payments and credits to this invoice.
902 A hash of optional arguments may be passed. Currently "manual" is supported.
903 If true, a payment receipt is sent instead of a statement when
904 'payment_receipt_email' configuration option is set.
906 If there is an error, returns the error, otherwise returns false.
910 sub apply_payments_and_credits {
911 my( $self, %options ) = @_;
912 my $conf = $self->conf;
914 local $SIG{HUP} = 'IGNORE';
915 local $SIG{INT} = 'IGNORE';
916 local $SIG{QUIT} = 'IGNORE';
917 local $SIG{TERM} = 'IGNORE';
918 local $SIG{TSTP} = 'IGNORE';
919 local $SIG{PIPE} = 'IGNORE';
921 my $oldAutoCommit = $FS::UID::AutoCommit;
922 local $FS::UID::AutoCommit = 0;
925 $self->select_for_update; #mutex
927 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
928 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
930 if ( $conf->exists('pkg-balances') ) {
931 # limit @payments & @credits to those w/ a pkgnum grepped from $self
932 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
933 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
934 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
937 while ( $self->owed > 0 and ( @payments || @credits ) ) {
940 if ( @payments && @credits ) {
942 #decide which goes first by weight of top (unapplied) line item
944 my @open_lineitems = $self->open_cust_bill_pkg;
947 max( map { $_->part_pkg->pay_weight || 0 }
952 my $max_credit_weight =
953 max( map { $_->part_pkg->credit_weight || 0 }
959 #if both are the same... payments first? it has to be something
960 if ( $max_pay_weight >= $max_credit_weight ) {
966 } elsif ( @payments ) {
968 } elsif ( @credits ) {
971 die "guru meditation #12 and 35";
975 if ( $app eq 'pay' ) {
977 my $payment = shift @payments;
978 $unapp_amount = $payment->unapplied;
979 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
980 $app->pkgnum( $payment->pkgnum )
981 if $conf->exists('pkg-balances') && $payment->pkgnum;
983 } elsif ( $app eq 'credit' ) {
985 my $credit = shift @credits;
986 $unapp_amount = $credit->credited;
987 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
988 $app->pkgnum( $credit->pkgnum )
989 if $conf->exists('pkg-balances') && $credit->pkgnum;
992 die "guru meditation #12 and 35";
996 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
997 warn "owed_pkgnum ". $app->pkgnum;
998 $owed = $self->owed_pkgnum($app->pkgnum);
1000 $owed = $self->owed;
1002 next unless $owed > 0;
1004 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1005 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1007 $app->invnum( $self->invnum );
1009 my $error = $app->insert(%options);
1011 $dbh->rollback if $oldAutoCommit;
1012 return "Error inserting ". $app->table. " record: $error";
1014 die $error if $error;
1018 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1023 =item generate_email OPTION => VALUE ...
1031 sender address, required
1035 alternate template name, optional
1039 text attachment arrayref, optional
1043 email subject, optional
1047 notice name instead of "Invoice", optional
1051 Returns an argument list to be passed to L<FS::Misc::send_email>.
1057 sub generate_email {
1061 my $conf = $self->conf;
1063 my $me = '[FS::cust_bill::generate_email]';
1066 'from' => $args{'from'},
1067 'subject' => ($args{'subject'} || $self->email_subject),
1070 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1072 my $cust_main = $self->cust_main;
1074 if (ref($args{'to'}) eq 'ARRAY') {
1075 $return{'to'} = $args{'to'};
1077 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1078 $cust_main->invoicing_list
1082 if ( $conf->exists('invoice_html') ) {
1084 warn "$me creating HTML/text multipart message"
1087 $return{'nobody'} = 1;
1089 my $alternative = build MIME::Entity
1090 'Type' => 'multipart/alternative',
1091 #'Encoding' => '7bit',
1092 'Disposition' => 'inline'
1096 if ( $conf->exists('invoice_email_pdf')
1097 and scalar($conf->config('invoice_email_pdf_note')) ) {
1099 warn "$me using 'invoice_email_pdf_note' in multipart message"
1101 $data = [ map { $_ . "\n" }
1102 $conf->config('invoice_email_pdf_note')
1107 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1109 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1110 $data = $args{'print_text'};
1112 $data = [ $self->print_text(\%args) ];
1117 $alternative->attach(
1118 'Type' => 'text/plain',
1119 'Encoding' => 'quoted-printable',
1120 #'Encoding' => '7bit',
1122 'Disposition' => 'inline',
1129 if ( $conf->exists('invoice_email_pdf')
1130 and scalar($conf->config('invoice_email_pdf_note')) ) {
1132 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1136 $args{'from'} =~ /\@([\w\.\-]+)/;
1137 my $from = $1 || 'example.com';
1138 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1141 my $agentnum = $cust_main->agentnum;
1142 if ( defined($args{'template'}) && length($args{'template'})
1143 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1146 $logo = 'logo_'. $args{'template'}. '.png';
1150 my $image_data = $conf->config_binary( $logo, $agentnum);
1152 $image = build MIME::Entity
1153 'Type' => 'image/png',
1154 'Encoding' => 'base64',
1155 'Data' => $image_data,
1156 'Filename' => 'logo.png',
1157 'Content-ID' => "<$content_id>",
1160 if ($conf->exists('invoice-barcode')) {
1161 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1162 $barcode = build MIME::Entity
1163 'Type' => 'image/png',
1164 'Encoding' => 'base64',
1165 'Data' => $self->invoice_barcode(0),
1166 'Filename' => 'barcode.png',
1167 'Content-ID' => "<$barcode_content_id>",
1169 $args{'barcode_cid'} = $barcode_content_id;
1172 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1175 $alternative->attach(
1176 'Type' => 'text/html',
1177 'Encoding' => 'quoted-printable',
1178 'Data' => [ '<html>',
1181 ' '. encode_entities($return{'subject'}),
1184 ' <body bgcolor="#e8e8e8">',
1189 'Disposition' => 'inline',
1190 #'Filename' => 'invoice.pdf',
1194 my @otherparts = ();
1195 if ( $cust_main->email_csv_cdr ) {
1197 push @otherparts, build MIME::Entity
1198 'Type' => 'text/csv',
1199 'Encoding' => '7bit',
1200 'Data' => [ map { "$_\n" }
1201 $self->call_details('prepend_billed_number' => 1)
1203 'Disposition' => 'attachment',
1204 'Filename' => 'usage-'. $self->invnum. '.csv',
1209 if ( $conf->exists('invoice_email_pdf') ) {
1214 # multipart/alternative
1220 my $related = build MIME::Entity 'Type' => 'multipart/related',
1221 'Encoding' => '7bit';
1223 #false laziness w/Misc::send_email
1224 $related->head->replace('Content-type',
1225 $related->mime_type.
1226 '; boundary="'. $related->head->multipart_boundary. '"'.
1227 '; type=multipart/alternative'
1230 $related->add_part($alternative);
1232 $related->add_part($image) if $image;
1234 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1236 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1240 #no other attachment:
1242 # multipart/alternative
1247 $return{'content-type'} = 'multipart/related';
1248 if ($conf->exists('invoice-barcode') && $barcode) {
1249 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1251 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1253 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1254 #$return{'disposition'} = 'inline';
1260 if ( $conf->exists('invoice_email_pdf') ) {
1261 warn "$me creating PDF attachment"
1264 #mime parts arguments a la MIME::Entity->build().
1265 $return{'mimeparts'} = [
1266 { $self->mimebuild_pdf(\%args) }
1270 if ( $conf->exists('invoice_email_pdf')
1271 and scalar($conf->config('invoice_email_pdf_note')) ) {
1273 warn "$me using 'invoice_email_pdf_note'"
1275 $return{'body'} = [ map { $_ . "\n" }
1276 $conf->config('invoice_email_pdf_note')
1281 warn "$me not using 'invoice_email_pdf_note'"
1283 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1284 $return{'body'} = $args{'print_text'};
1286 $return{'body'} = [ $self->print_text(\%args) ];
1299 Returns a list suitable for passing to MIME::Entity->build(), representing
1300 this invoice as PDF attachment.
1307 'Type' => 'application/pdf',
1308 'Encoding' => 'base64',
1309 'Data' => [ $self->print_pdf(@_) ],
1310 'Disposition' => 'attachment',
1311 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1317 Sends this invoice to the destinations configured for this customer: sends
1318 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1320 Options can be passed as a hashref. Positional parameters are no longer
1323 I<template>: a suffix for alternate invoices
1325 I<agentnum>: obsolete, now does nothing.
1327 I<invoice_from> overrides the default email invoice From: address.
1329 I<amount>: obsolete, does nothing
1331 I<notice_name> overrides "Invoice" as the name of the sent document
1332 (templates from 10/2009 or newer required).
1334 I<lpr> overrides the system 'lpr' option as the command to print a document
1335 from standard input.
1341 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1342 my $conf = $self->conf;
1344 my $cust_main = $self->cust_main;
1346 my @invoicing_list = $cust_main->invoicing_list;
1349 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1350 && ! $self->invoice_noemail;
1353 if grep { $_ eq 'POST' } @invoicing_list; #postal
1355 #this has never been used post-$ORIGINAL_ISP afaik
1356 $self->fax_invoice($opt)
1357 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1363 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1365 Sends this invoice to the customer's email destination(s).
1367 Options must be passed as a hashref. Positional parameters are no longer
1370 I<template>, if specified, is the name of a suffix for alternate invoices.
1372 I<invoice_from>, if specified, overrides the default email invoice From:
1375 I<notice_name> is the name of the sent document.
1379 sub queueable_email {
1382 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1383 or die "invalid invoice number: " . $opt{invnum};
1385 my %args = map {$_ => $opt{$_}}
1387 qw( invoice_from notice_name no_coupon template );
1389 my $error = $self->email( \%args );
1390 die $error if $error;
1396 return if $self->hide;
1397 my $conf = $self->conf;
1398 my $opt = shift || {};
1399 if ($opt and !ref($opt)) {
1400 die "FS::cust_bill::email called with positional parameters";
1403 my $template = $opt->{template};
1404 my $from = delete $opt->{invoice_from};
1406 # this is where we set the From: address
1407 $from ||= $self->_agent_invoice_from || #XXX should go away
1408 $conf->config('invoice_from', $self->cust_main->agentnum );
1410 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1411 $self->cust_main->invoicing_list;
1413 if ( ! @invoicing_list ) { #no recipients
1414 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1415 die 'No recipients for customer #'. $self->custnum;
1417 #default: better to notify this person than silence
1418 @invoicing_list = ($from);
1422 # this is where we set the Subject:
1423 my $subject = $self->email_subject($template);
1425 my $error = send_email(
1426 $self->generate_email(
1428 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1429 'subject' => $subject,
1430 %$opt, # template, etc.
1433 die "can't email invoice: $error\n" if $error;
1434 #die "$error\n" if $error;
1440 my $conf = $self->conf;
1442 #my $template = scalar(@_) ? shift : '';
1445 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1448 my $cust_main = $self->cust_main;
1449 my $name = $cust_main->name;
1450 my $name_short = $cust_main->name_short;
1451 my $invoice_number = $self->invnum;
1452 my $invoice_date = $self->_date_pretty;
1454 eval qq("$subject");
1457 =item lpr_data HASHREF
1459 Returns the postscript or plaintext for this invoice as an arrayref.
1461 Options must be passed as a hashref. Positional parameters are no longer
1464 I<template>, if specified, is the name of a suffix for alternate invoices.
1466 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1472 my $conf = $self->conf;
1473 my $opt = shift || {};
1474 if ($opt and !ref($opt)) {
1475 # nobody does this anyway
1476 die "FS::cust_bill::lpr_data called with positional parameters";
1479 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1480 [ $self->$method( $opt ) ];
1485 Prints this invoice.
1487 Options must be passed as a hashref.
1489 I<template>, if specified, is the name of a suffix for alternate invoices.
1491 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1497 return if $self->hide;
1498 my $conf = $self->conf;
1499 my $opt = shift || {};
1500 if ($opt and !ref($opt)) {
1501 die "FS::cust_bill::print called with positional parameters";
1504 my $lpr = delete $opt->{lpr};
1505 if($conf->exists('invoice_print_pdf')) {
1506 # Add the invoice to the current batch.
1507 $self->batch_invoice($opt);
1511 $self->lpr_data($opt),
1512 'agentnum' => $self->cust_main->agentnum,
1518 =item fax_invoice HASHREF
1522 Options must be passed as a hashref.
1524 I<template>, if specified, is the name of a suffix for alternate invoices.
1526 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1532 return if $self->hide;
1533 my $conf = $self->conf;
1534 my $opt = shift || {};
1535 if ($opt and !ref($opt)) {
1536 die "FS::cust_bill::fax_invoice called with positional parameters";
1539 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1540 unless $conf->exists('invoice_latex');
1542 my $dialstring = $self->cust_main->getfield('fax');
1545 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1546 'dialstring' => $dialstring,
1548 die $error if $error;
1552 =item batch_invoice [ HASHREF ]
1554 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1555 isn't an open batch, one will be created.
1560 my ($self, $opt) = @_;
1561 my $bill_batch = $self->get_open_bill_batch;
1562 my $cust_bill_batch = FS::cust_bill_batch->new({
1563 batchnum => $bill_batch->batchnum,
1564 invnum => $self->invnum,
1566 return $cust_bill_batch->insert($opt);
1569 =item get_open_batch
1571 Returns the currently open batch as an FS::bill_batch object, creating a new
1572 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1577 sub get_open_bill_batch {
1579 my $conf = $self->conf;
1580 my $hashref = { status => 'O' };
1581 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1582 ? $self->cust_main->agentnum
1584 my $batch = qsearchs('bill_batch', $hashref);
1585 return $batch if $batch;
1586 $batch = FS::bill_batch->new($hashref);
1587 my $error = $batch->insert;
1588 die $error if $error;
1592 =item ftp_invoice [ TEMPLATENAME ]
1594 Sends this invoice data via FTP.
1596 TEMPLATENAME is unused?
1602 my $conf = $self->conf;
1603 my $template = scalar(@_) ? shift : '';
1606 'protocol' => 'ftp',
1607 'server' => $conf->config('cust_bill-ftpserver'),
1608 'username' => $conf->config('cust_bill-ftpusername'),
1609 'password' => $conf->config('cust_bill-ftppassword'),
1610 'dir' => $conf->config('cust_bill-ftpdir'),
1611 'format' => $conf->config('cust_bill-ftpformat'),
1615 =item spool_invoice [ TEMPLATENAME ]
1617 Spools this invoice data (see L<FS::spool_csv>)
1619 TEMPLATENAME is unused?
1625 my $conf = $self->conf;
1626 my $template = scalar(@_) ? shift : '';
1629 'format' => $conf->config('cust_bill-spoolformat'),
1630 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1634 =item send_csv OPTION => VALUE, ...
1636 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1640 protocol - currently only "ftp"
1646 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1647 and YYMMDDHHMMSS is a timestamp.
1649 See L</print_csv> for a description of the output format.
1654 my($self, %opt) = @_;
1658 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1659 mkdir $spooldir, 0700 unless -d $spooldir;
1661 # don't localize dates here, they're a defined format
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'); # hardcoded, NOT 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(%opt), $self->_items_credits(%opt) ) ;
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('short')
2969 : $self->time2str_local('short', $_->_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') ) {
3001 if ( $opt{'template'} eq 'statement' ) {
3002 # then the current bill is a "statement" (i.e. an invoice sent as
3003 # a payment receipt)
3004 # and in that case we want to see payments on or after THIS invoice
3005 @objects = qsearch('cust_credit', {
3006 'custnum' => $self->custnum,
3007 '_date' => {op => '>=', value => $self->_date},
3011 $date = $self->previous_bill->_date if $self->previous_bill;
3012 @objects = qsearch('cust_credit', {
3013 'custnum' => $self->custnum,
3014 '_date' => {op => '>=', value => $date},
3018 @objects = $self->cust_credited;
3021 foreach my $obj ( @objects ) {
3022 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3024 my $reason = substr($cust_credit->reason, 0, $trim_len);
3025 $reason .= '...' if length($reason) < length($cust_credit->reason);
3026 $reason = " ($reason) " if $reason;
3029 #'description' => 'Credit ref\#'. $_->crednum.
3030 # " (". time2str("%x",$_->cust_credit->_date) .")".
3032 'description' => $self->mt('Credit applied').' '.
3033 $self->time2str_local('short', $obj->_date). $reason,
3034 'amount' => sprintf("%.2f",$obj->amount),
3042 sub _items_payments {
3047 my $detailed = $self->conf->exists('invoice_payment_details');
3049 if ( $self->conf->exists('previous_balance-payments_since') ) {
3050 # then show payments dated on/after the previous bill...
3051 if ( $opt{'template'} eq 'statement' ) {
3052 # then the current bill is a "statement" (i.e. an invoice sent as
3053 # a payment receipt)
3054 # and in that case we want to see payments on or after THIS invoice
3055 @objects = qsearch('cust_pay', {
3056 'custnum' => $self->custnum,
3057 '_date' => {op => '>=', value => $self->_date},
3060 # the normal case: payments on or after the previous invoice
3062 $date = $self->previous_bill->_date if $self->previous_bill;
3063 @objects = qsearch('cust_pay', {
3064 'custnum' => $self->custnum,
3065 '_date' => {op => '>=', value => $date},
3067 # and before the current bill...
3068 @objects = grep { $_->_date < $self->_date } @objects;
3071 @objects = $self->cust_bill_pay;
3074 foreach my $obj (@objects) {
3075 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3076 my $desc = $self->mt('Payment received').' '.
3077 $self->time2str_local('short', $cust_pay->_date );
3078 $desc .= $self->mt(' via ') .
3079 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3083 'description' => $desc,
3084 'amount' => sprintf("%.2f", $obj->amount )
3092 =item call_details [ OPTION => VALUE ... ]
3094 Returns an array of CSV strings representing the call details for this invoice
3095 The only option available is the boolean prepend_billed_number
3100 my ($self, %opt) = @_;
3102 my $format_function = sub { shift };
3104 if ($opt{prepend_billed_number}) {
3105 $format_function = sub {
3109 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3114 my @details = map { $_->details( 'format_function' => $format_function,
3115 'escape_function' => sub{ return() },
3119 $self->cust_bill_pkg;
3120 my $header = $details[0];
3121 ( $header, grep { $_ ne $header } @details );
3131 =item process_reprint
3135 sub process_reprint {
3136 process_re_X('print', @_);
3139 =item process_reemail
3143 sub process_reemail {
3144 process_re_X('email', @_);
3152 process_re_X('fax', @_);
3160 process_re_X('ftp', @_);
3167 sub process_respool {
3168 process_re_X('spool', @_);
3171 use Storable qw(thaw);
3175 my( $method, $job ) = ( shift, shift );
3176 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3178 my $param = thaw(decode_base64(shift));
3179 warn Dumper($param) if $DEBUG;
3190 # spool_invoice ftp_invoice fax_invoice print_invoice
3191 my($method, $job, %param ) = @_;
3193 warn "re_X $method for job $job with param:\n".
3194 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3197 #some false laziness w/search/cust_bill.html
3199 my $orderby = 'ORDER BY cust_bill._date';
3201 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3203 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3205 my @cust_bill = qsearch( {
3206 #'select' => "cust_bill.*",
3207 'table' => 'cust_bill',
3208 'addl_from' => $addl_from,
3210 'extra_sql' => $extra_sql,
3211 'order_by' => $orderby,
3215 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3217 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3220 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3221 foreach my $cust_bill ( @cust_bill ) {
3222 $cust_bill->$method();
3224 if ( $job ) { #progressbar foo
3226 if ( time - $min_sec > $last ) {
3227 my $error = $job->update_statustext(
3228 int( 100 * $num / scalar(@cust_bill) )
3230 die $error if $error;
3241 =head1 CLASS METHODS
3247 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3252 my ($class, $start, $end) = @_;
3254 $class->paid_sql($start, $end). ' - '.
3255 $class->credited_sql($start, $end);
3260 Returns an SQL fragment to retreive the net amount (charged minus credited).
3265 my ($class, $start, $end) = @_;
3266 'charged - '. $class->credited_sql($start, $end);
3271 Returns an SQL fragment to retreive the amount paid against this invoice.
3276 my ($class, $start, $end) = @_;
3277 $start &&= "AND cust_bill_pay._date <= $start";
3278 $end &&= "AND cust_bill_pay._date > $end";
3279 $start = '' unless defined($start);
3280 $end = '' unless defined($end);
3281 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3282 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3287 Returns an SQL fragment to retreive the amount credited against this invoice.
3292 my ($class, $start, $end) = @_;
3293 $start &&= "AND cust_credit_bill._date <= $start";
3294 $end &&= "AND cust_credit_bill._date > $end";
3295 $start = '' unless defined($start);
3296 $end = '' unless defined($end);
3297 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3298 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3303 Returns an SQL fragment to retrieve the due date of an invoice.
3304 Currently only supported on PostgreSQL.
3309 my $conf = new FS::Conf;
3313 cust_bill.invoice_terms,
3314 cust_main.invoice_terms,
3315 \''.($conf->config('invoice_default_terms') || '').'\'
3316 ), E\'Net (\\\\d+)\'
3318 ) * 86400 + cust_bill._date'
3321 =item search_sql_where HASHREF
3323 Class method which returns an SQL WHERE fragment to search for parameters
3324 specified in HASHREF. Valid parameters are
3330 List reference of start date, end date, as UNIX timestamps.
3340 List reference of charged limits (exclusive).
3344 List reference of charged limits (exclusive).
3348 flag, return open invoices only
3352 flag, return net invoices only
3356 =item newest_percust
3360 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3364 sub search_sql_where {
3365 my($class, $param) = @_;
3367 warn "$me search_sql_where called with params: \n".
3368 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3374 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3375 push @search, "cust_main.agentnum = $1";
3379 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3380 push @search, "cust_main.refnum = $1";
3384 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3385 push @search, "cust_bill.custnum = $1";
3388 #customer classnum (false laziness w/ cust_main/Search.pm)
3389 if ( $param->{'cust_classnum'} ) {
3391 my @classnum = ref( $param->{'cust_classnum'} )
3392 ? @{ $param->{'cust_classnum'} }
3393 : ( $param->{'cust_classnum'} );
3395 @classnum = grep /^(\d*)$/, @classnum;
3398 push @search, '( '. join(' OR ', map {
3399 $_ ? "cust_main.classnum = $_"
3400 : "cust_main.classnum IS NULL"
3410 if ( $param->{_date} ) {
3411 my($beginning, $ending) = @{$param->{_date}};
3413 push @search, "cust_bill._date >= $beginning",
3414 "cust_bill._date < $ending";
3418 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3419 push @search, "cust_bill.invnum >= $1";
3421 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3422 push @search, "cust_bill.invnum <= $1";
3426 if ( $param->{charged} ) {
3427 my @charged = ref($param->{charged})
3428 ? @{ $param->{charged} }
3429 : ($param->{charged});
3431 push @search, map { s/^charged/cust_bill.charged/; $_; }
3435 my $owed_sql = FS::cust_bill->owed_sql;
3438 if ( $param->{owed} ) {
3439 my @owed = ref($param->{owed})
3440 ? @{ $param->{owed} }
3442 push @search, map { s/^owed/$owed_sql/; $_; }
3447 push @search, "0 != $owed_sql"
3448 if $param->{'open'};
3449 push @search, '0 != '. FS::cust_bill->net_sql
3453 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3454 if $param->{'days'};
3457 if ( $param->{'newest_percust'} ) {
3459 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3460 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3462 my @newest_where = map { my $x = $_;
3463 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3466 grep ! /^cust_main./, @search;
3467 my $newest_where = scalar(@newest_where)
3468 ? ' AND '. join(' AND ', @newest_where)
3472 push @search, "cust_bill._date = (
3473 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3474 WHERE newest_cust_bill.custnum = cust_bill.custnum
3480 #promised_date - also has an option to accept nulls
3481 if ( $param->{promised_date} ) {
3482 my($beginning, $ending, $null) = @{$param->{promised_date}};
3484 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3485 "cust_bill.promised_date < $ending )" .
3486 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3489 #agent virtualization
3490 my $curuser = $FS::CurrentUser::CurrentUser;
3491 if ( $curuser->username eq 'fs_queue'
3492 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3494 my $newuser = qsearchs('access_user', {
3495 'username' => $username,
3499 $curuser = $newuser;
3501 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3504 push @search, $curuser->agentnums_sql;
3506 join(' AND ', @search );
3518 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3519 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base