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),
1068 'custnum' => $self->custnum,
1069 'msgtype' => 'invoice',
1072 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1074 my $cust_main = $self->cust_main;
1076 if (ref($args{'to'}) eq 'ARRAY') {
1077 $return{'to'} = $args{'to'};
1079 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1080 $cust_main->invoicing_list
1084 if ( $conf->exists('invoice_html') ) {
1086 warn "$me creating HTML/text multipart message"
1089 $return{'nobody'} = 1;
1091 my $alternative = build MIME::Entity
1092 'Type' => 'multipart/alternative',
1093 #'Encoding' => '7bit',
1094 'Disposition' => 'inline'
1098 if ( $conf->exists('invoice_email_pdf')
1099 and scalar($conf->config('invoice_email_pdf_note')) ) {
1101 warn "$me using 'invoice_email_pdf_note' in multipart message"
1103 $data = [ map { $_ . "\n" }
1104 $conf->config('invoice_email_pdf_note')
1109 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1111 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1112 $data = $args{'print_text'};
1114 $data = [ $self->print_text(\%args) ];
1119 $alternative->attach(
1120 'Type' => 'text/plain',
1121 'Encoding' => 'quoted-printable',
1122 #'Encoding' => '7bit',
1124 'Disposition' => 'inline',
1131 if ( $conf->exists('invoice_email_pdf')
1132 and scalar($conf->config('invoice_email_pdf_note')) ) {
1134 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1138 $args{'from'} =~ /\@([\w\.\-]+)/;
1139 my $from = $1 || 'example.com';
1140 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1143 my $agentnum = $cust_main->agentnum;
1144 if ( defined($args{'template'}) && length($args{'template'})
1145 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1148 $logo = 'logo_'. $args{'template'}. '.png';
1152 my $image_data = $conf->config_binary( $logo, $agentnum);
1154 $image = build MIME::Entity
1155 'Type' => 'image/png',
1156 'Encoding' => 'base64',
1157 'Data' => $image_data,
1158 'Filename' => 'logo.png',
1159 'Content-ID' => "<$content_id>",
1162 if ($conf->exists('invoice-barcode')) {
1163 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1164 $barcode = build MIME::Entity
1165 'Type' => 'image/png',
1166 'Encoding' => 'base64',
1167 'Data' => $self->invoice_barcode(0),
1168 'Filename' => 'barcode.png',
1169 'Content-ID' => "<$barcode_content_id>",
1171 $args{'barcode_cid'} = $barcode_content_id;
1174 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1177 $alternative->attach(
1178 'Type' => 'text/html',
1179 'Encoding' => 'quoted-printable',
1180 'Data' => [ '<html>',
1183 ' '. encode_entities($return{'subject'}),
1186 ' <body bgcolor="#e8e8e8">',
1191 'Disposition' => 'inline',
1192 #'Filename' => 'invoice.pdf',
1196 my @otherparts = ();
1197 if ( $cust_main->email_csv_cdr ) {
1199 push @otherparts, build MIME::Entity
1200 'Type' => 'text/csv',
1201 'Encoding' => '7bit',
1202 'Data' => [ map { "$_\n" }
1203 $self->call_details('prepend_billed_number' => 1)
1205 'Disposition' => 'attachment',
1206 'Filename' => 'usage-'. $self->invnum. '.csv',
1211 if ( $conf->exists('invoice_email_pdf') ) {
1216 # multipart/alternative
1222 my $related = build MIME::Entity 'Type' => 'multipart/related',
1223 'Encoding' => '7bit';
1225 #false laziness w/Misc::send_email
1226 $related->head->replace('Content-type',
1227 $related->mime_type.
1228 '; boundary="'. $related->head->multipart_boundary. '"'.
1229 '; type=multipart/alternative'
1232 $related->add_part($alternative);
1234 $related->add_part($image) if $image;
1236 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1238 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1242 #no other attachment:
1244 # multipart/alternative
1249 $return{'content-type'} = 'multipart/related';
1250 if ($conf->exists('invoice-barcode') && $barcode) {
1251 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1253 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1255 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1256 #$return{'disposition'} = 'inline';
1262 if ( $conf->exists('invoice_email_pdf') ) {
1263 warn "$me creating PDF attachment"
1266 #mime parts arguments a la MIME::Entity->build().
1267 $return{'mimeparts'} = [
1268 { $self->mimebuild_pdf(\%args) }
1272 if ( $conf->exists('invoice_email_pdf')
1273 and scalar($conf->config('invoice_email_pdf_note')) ) {
1275 warn "$me using 'invoice_email_pdf_note'"
1277 $return{'body'} = [ map { $_ . "\n" }
1278 $conf->config('invoice_email_pdf_note')
1283 warn "$me not using 'invoice_email_pdf_note'"
1285 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1286 $return{'body'} = $args{'print_text'};
1288 $return{'body'} = [ $self->print_text(\%args) ];
1301 Returns a list suitable for passing to MIME::Entity->build(), representing
1302 this invoice as PDF attachment.
1309 'Type' => 'application/pdf',
1310 'Encoding' => 'base64',
1311 'Data' => [ $self->print_pdf(@_) ],
1312 'Disposition' => 'attachment',
1313 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1319 Sends this invoice to the destinations configured for this customer: sends
1320 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1322 Options can be passed as a hashref. Positional parameters are no longer
1325 I<template>: a suffix for alternate invoices
1327 I<agentnum>: obsolete, now does nothing.
1329 I<invoice_from> overrides the default email invoice From: address.
1331 I<amount>: obsolete, does nothing
1333 I<notice_name> overrides "Invoice" as the name of the sent document
1334 (templates from 10/2009 or newer required).
1336 I<lpr> overrides the system 'lpr' option as the command to print a document
1337 from standard input.
1343 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1344 my $conf = $self->conf;
1346 my $cust_main = $self->cust_main;
1348 my @invoicing_list = $cust_main->invoicing_list;
1351 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1352 && ! $self->invoice_noemail;
1355 if grep { $_ eq 'POST' } @invoicing_list; #postal
1357 #this has never been used post-$ORIGINAL_ISP afaik
1358 $self->fax_invoice($opt)
1359 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1365 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1367 Sends this invoice to the customer's email destination(s).
1369 Options must be passed as a hashref. Positional parameters are no longer
1372 I<template>, if specified, is the name of a suffix for alternate invoices.
1374 I<invoice_from>, if specified, overrides the default email invoice From:
1377 I<notice_name> is the name of the sent document.
1381 sub queueable_email {
1384 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1385 or die "invalid invoice number: " . $opt{invnum};
1387 my %args = map {$_ => $opt{$_}}
1389 qw( invoice_from notice_name no_coupon template );
1391 my $error = $self->email( \%args );
1392 die $error if $error;
1398 return if $self->hide;
1399 my $conf = $self->conf;
1400 my $opt = shift || {};
1401 if ($opt and !ref($opt)) {
1402 die "FS::cust_bill::email called with positional parameters";
1405 my $template = $opt->{template};
1406 my $from = delete $opt->{invoice_from};
1408 # this is where we set the From: address
1409 $from ||= $self->_agent_invoice_from || #XXX should go away
1410 $conf->config('invoice_from', $self->cust_main->agentnum );
1412 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1413 $self->cust_main->invoicing_list;
1415 if ( ! @invoicing_list ) { #no recipients
1416 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1417 die 'No recipients for customer #'. $self->custnum;
1419 #default: better to notify this person than silence
1420 @invoicing_list = ($from);
1424 # this is where we set the Subject:
1425 my $subject = $self->email_subject($template);
1427 my $error = send_email(
1428 $self->generate_email(
1430 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1431 'subject' => $subject,
1432 %$opt, # template, etc.
1435 die "can't email invoice: $error\n" if $error;
1436 #die "$error\n" if $error;
1442 my $conf = $self->conf;
1444 #my $template = scalar(@_) ? shift : '';
1447 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1450 my $cust_main = $self->cust_main;
1451 my $name = $cust_main->name;
1452 my $name_short = $cust_main->name_short;
1453 my $invoice_number = $self->invnum;
1454 my $invoice_date = $self->_date_pretty;
1456 eval qq("$subject");
1459 =item lpr_data HASHREF
1461 Returns the postscript or plaintext for this invoice as an arrayref.
1463 Options must be passed as a hashref. Positional parameters are no longer
1466 I<template>, if specified, is the name of a suffix for alternate invoices.
1468 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1474 my $conf = $self->conf;
1475 my $opt = shift || {};
1476 if ($opt and !ref($opt)) {
1477 # nobody does this anyway
1478 die "FS::cust_bill::lpr_data called with positional parameters";
1481 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1482 [ $self->$method( $opt ) ];
1487 Prints this invoice.
1489 Options must be passed as a hashref.
1491 I<template>, if specified, is the name of a suffix for alternate invoices.
1493 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1499 return if $self->hide;
1500 my $conf = $self->conf;
1501 my $opt = shift || {};
1502 if ($opt and !ref($opt)) {
1503 die "FS::cust_bill::print called with positional parameters";
1506 my $lpr = delete $opt->{lpr};
1507 if($conf->exists('invoice_print_pdf')) {
1508 # Add the invoice to the current batch.
1509 $self->batch_invoice($opt);
1513 $self->lpr_data($opt),
1514 'agentnum' => $self->cust_main->agentnum,
1520 =item fax_invoice HASHREF
1524 Options must be passed as a hashref.
1526 I<template>, if specified, is the name of a suffix for alternate invoices.
1528 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1534 return if $self->hide;
1535 my $conf = $self->conf;
1536 my $opt = shift || {};
1537 if ($opt and !ref($opt)) {
1538 die "FS::cust_bill::fax_invoice called with positional parameters";
1541 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1542 unless $conf->exists('invoice_latex');
1544 my $dialstring = $self->cust_main->getfield('fax');
1547 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1548 'dialstring' => $dialstring,
1550 die $error if $error;
1554 =item batch_invoice [ HASHREF ]
1556 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1557 isn't an open batch, one will be created.
1562 my ($self, $opt) = @_;
1563 my $bill_batch = $self->get_open_bill_batch;
1564 my $cust_bill_batch = FS::cust_bill_batch->new({
1565 batchnum => $bill_batch->batchnum,
1566 invnum => $self->invnum,
1568 return $cust_bill_batch->insert($opt);
1571 =item get_open_batch
1573 Returns the currently open batch as an FS::bill_batch object, creating a new
1574 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1579 sub get_open_bill_batch {
1581 my $conf = $self->conf;
1582 my $hashref = { status => 'O' };
1583 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1584 ? $self->cust_main->agentnum
1586 my $batch = qsearchs('bill_batch', $hashref);
1587 return $batch if $batch;
1588 $batch = FS::bill_batch->new($hashref);
1589 my $error = $batch->insert;
1590 die $error if $error;
1594 =item ftp_invoice [ TEMPLATENAME ]
1596 Sends this invoice data via FTP.
1598 TEMPLATENAME is unused?
1604 my $conf = $self->conf;
1605 my $template = scalar(@_) ? shift : '';
1608 'protocol' => 'ftp',
1609 'server' => $conf->config('cust_bill-ftpserver'),
1610 'username' => $conf->config('cust_bill-ftpusername'),
1611 'password' => $conf->config('cust_bill-ftppassword'),
1612 'dir' => $conf->config('cust_bill-ftpdir'),
1613 'format' => $conf->config('cust_bill-ftpformat'),
1617 =item spool_invoice [ TEMPLATENAME ]
1619 Spools this invoice data (see L<FS::spool_csv>)
1621 TEMPLATENAME is unused?
1627 my $conf = $self->conf;
1628 my $template = scalar(@_) ? shift : '';
1631 'format' => $conf->config('cust_bill-spoolformat'),
1632 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1636 =item send_csv OPTION => VALUE, ...
1638 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1642 protocol - currently only "ftp"
1648 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1649 and YYMMDDHHMMSS is a timestamp.
1651 See L</print_csv> for a description of the output format.
1656 my($self, %opt) = @_;
1660 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1661 mkdir $spooldir, 0700 unless -d $spooldir;
1663 # don't localize dates here, they're a defined format
1664 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1665 my $file = "$spooldir/$tracctnum.csv";
1667 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1669 open(CSV, ">$file") or die "can't open $file: $!";
1677 if ( $opt{protocol} eq 'ftp' ) {
1678 eval "use Net::FTP;";
1680 $net = Net::FTP->new($opt{server}) or die @$;
1682 die "unknown protocol: $opt{protocol}";
1685 $net->login( $opt{username}, $opt{password} )
1686 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1688 $net->binary or die "can't set binary mode";
1690 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1692 $net->put($file) or die "can't put $file: $!";
1702 Spools CSV invoice data.
1708 =item format - any of FS::Misc::::Invoicing::spool_formats
1710 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1711 customer has the corresponding invoice destinations set (see
1712 L<FS::cust_main_invoice>).
1714 =item agent_spools - if set to a true value, will spool to per-agent files
1715 rather than a single global file
1717 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1718 append to that spool. L<FS::Cron::upload> will then send the spool file to
1721 =item balanceover - if set, only spools the invoice if the total amount owed on
1722 this invoice and all older invoices is greater than the specified amount.
1724 =item time - the "current time". Controls the printing of past due messages
1732 my($self, %opt) = @_;
1734 my $time = $opt{'time'} || time;
1735 my $cust_main = $self->cust_main;
1737 if ( $opt{'dest'} ) {
1738 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1739 $cust_main->invoicing_list;
1740 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1741 || ! keys %invoicing_list;
1744 if ( $opt{'balanceover'} ) {
1746 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1749 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1750 mkdir $spooldir, 0700 unless -d $spooldir;
1752 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1755 if ( $opt{'agent_spools'} ) {
1756 $file = 'agentnum'.$cust_main->agentnum;
1761 if ( $opt{'upload_targetnum'} ) {
1762 $spooldir .= '/target'.$opt{'upload_targetnum'};
1763 mkdir $spooldir, 0700 unless -d $spooldir;
1764 } # otherwise it just goes into export.xxx/cust_bill
1766 if ( lc($opt{'format'}) eq 'billco' ) {
1770 $file = "$spooldir/$file.csv";
1772 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1774 open(CSV, ">>$file") or die "can't open $file: $!";
1775 flock(CSV, LOCK_EX);
1780 if ( lc($opt{'format'}) eq 'billco' ) {
1782 flock(CSV, LOCK_UN);
1785 $file =~ s/-header.csv$/-detail.csv/;
1787 open(CSV,">>$file") or die "can't open $file: $!";
1788 flock(CSV, LOCK_EX);
1792 print CSV $detail if defined($detail);
1794 flock(CSV, LOCK_UN);
1801 =item print_csv OPTION => VALUE, ...
1803 Returns CSV data for this invoice.
1807 format - 'default', 'billco', 'oneline', 'bridgestone'
1809 Returns a list consisting of two scalars. The first is a single line of CSV
1810 header information for this invoice. The second is one or more lines of CSV
1811 detail information for this invoice.
1813 If I<format> is not specified or "default", the fields of the CSV file are as
1816 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1817 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1821 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1823 B<record_type> is C<cust_bill> for the initial header line only. The
1824 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1825 fields are filled in.
1827 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1828 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1831 =item invnum - invoice number
1833 =item custnum - customer number
1835 =item _date - invoice date
1837 =item charged - total invoice amount
1839 =item first - customer first name
1841 =item last - customer first name
1843 =item company - company name
1845 =item address1 - address line 1
1847 =item address2 - address line 1
1857 =item pkg - line item description
1859 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1861 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1863 =item sdate - start date for recurring fee
1865 =item edate - end date for recurring fee
1869 If I<format> is "billco", the fields of the header CSV file are as follows:
1871 +-------------------------------------------------------------------+
1872 | FORMAT HEADER FILE |
1873 |-------------------------------------------------------------------|
1874 | Field | Description | Name | Type | Width |
1875 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1876 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1877 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1878 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1879 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1880 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1881 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1882 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1883 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1884 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1885 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1886 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1887 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1888 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1889 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1890 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1891 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1892 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1893 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1894 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1895 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1896 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1897 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1898 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1899 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1900 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1901 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1902 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1903 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1904 +-------+-------------------------------+------------+------+-------+
1906 If I<format> is "billco", the fields of the detail CSV file are as follows:
1908 FORMAT FOR DETAIL FILE
1910 Field | Description | Name | Type | Width
1911 1 | N/A-Leave Empty | RC | CHAR | 2
1912 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1913 3 | Account Number | TRACCTNUM | CHAR | 15
1914 4 | Invoice Number | TRINVOICE | CHAR | 15
1915 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1916 6 | Transaction Detail | DETAILS | CHAR | 100
1917 7 | Amount | AMT | NUM* | 9
1918 8 | Line Format Control** | LNCTRL | CHAR | 2
1919 9 | Grouping Code | GROUP | CHAR | 2
1920 10 | User Defined | ACCT CODE | CHAR | 15
1922 If format is 'oneline', there is no detail file. Each invoice has a
1923 header line only, with the fields:
1925 Agent number, agent name, customer number, first name, last name, address
1926 line 1, address line 2, city, state, zip, invoice date, invoice number,
1927 amount charged, amount due, previous balance, due date.
1929 and then, for each line item, three columns containing the package number,
1930 description, and amount.
1932 If format is 'bridgestone', there is no detail file. Each invoice has a
1933 header line with the following fields in a fixed-width format:
1935 Customer number (in display format), date, name (first last), company,
1936 address 1, address 2, city, state, zip.
1938 This is a mailing list format, and has no per-invoice fields. To avoid
1939 sending redundant notices, the spooling event should have a "once" or
1940 "once_percust_every" condition.
1945 my($self, %opt) = @_;
1947 eval "use Text::CSV_XS";
1950 my $cust_main = $self->cust_main;
1952 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1953 my $format = lc($opt{'format'});
1955 my $time = $opt{'time'} || time;
1957 my $tracctnum = ''; #leaking out from billco-specific sections :/
1958 if ( $format eq 'billco' ) {
1961 $self->conf->config('billco-account_num', $cust_main->agentnum);
1963 $tracctnum = $account_num eq 'display_custnum'
1964 ? $cust_main->display_custnum
1965 : $opt{'tracctnum'};
1968 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1970 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1972 my( $previous_balance, @unused ) = $self->previous; #previous balance
1974 my $pmt_cr_applied = 0;
1975 $pmt_cr_applied += $_->{'amount'}
1976 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1978 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1981 '', # 1 | N/A-Leave Empty CHAR 2
1982 '', # 2 | N/A-Leave Empty CHAR 15
1983 $tracctnum, # 3 | Transaction Account No CHAR 15
1984 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1985 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1986 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1987 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1988 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1989 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1990 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1991 '', # 10 | Ancillary Billing Information CHAR 30
1992 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1993 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1996 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1999 $duedate, # 14 | Bill Due Date CHAR 10
2001 $previous_balance, # 15 | Previous Balance NUM* 9
2002 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2003 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2004 $totaldue, # 18 | Total Amt Due NUM* 9
2005 $totaldue, # 19 | Total Amt Due NUM* 9
2006 '', # 20 | 30 Day Aging NUM* 9
2007 '', # 21 | 60 Day Aging NUM* 9
2008 '', # 22 | 90 Day Aging NUM* 9
2009 'N', # 23 | Y/N CHAR 1
2010 '', # 24 | Remittance automation CHAR 100
2011 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2012 $self->custnum, # 26 | Customer Reference Number CHAR 15
2013 '0', # 27 | Federal Tax*** NUM* 9
2014 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2015 '0', # 29 | Other Taxes & Fees*** NUM* 9
2018 } elsif ( $format eq 'oneline' ) { #name
2020 my ($previous_balance) = $self->previous;
2021 $previous_balance = sprintf('%.2f', $previous_balance);
2022 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2028 $self->_items_pkg, #_items_nontax? no sections or anything
2033 $cust_main->agentnum,
2034 $cust_main->agent->agent,
2038 $cust_main->company,
2039 $cust_main->address1,
2040 $cust_main->address2,
2046 time2str("%x", $self->_date),
2051 $self->due_date2str("%x"),
2056 } elsif ( $format eq 'bridgestone' ) {
2058 # bypass the CSV stuff and just return this
2059 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2060 my $zip = $cust_main->zip;
2062 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2066 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2068 $cust_main->display_custnum,
2070 uc(substr($cust_main->contact_firstlast,0,30)),
2071 uc(substr($cust_main->company ,0,30)),
2072 uc(substr($cust_main->address1 ,0,30)),
2073 uc(substr($cust_main->address2 ,0,30)),
2074 uc(substr($cust_main->city ,0,20)),
2075 uc($cust_main->state),
2081 } elsif ( $format eq 'ics' ) {
2083 my $bill = $cust_main->bill_location;
2084 my $zip = $bill->zip;
2088 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2093 # minor false laziness with print_generic
2094 my ($previous_balance) = $self->previous;
2095 my $balance_due = $self->owed + $previous_balance;
2096 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2097 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2100 if ( $self->due_date and $time >= $self->due_date ) {
2101 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2105 my $header = sprintf(
2106 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2107 $cust_main->display_custnum, #BID
2108 uc($cust_main->first), #FNAME
2109 uc($cust_main->last), #LNAME
2110 '00', #BATCH, should this ever be anything else?
2111 uc($cust_main->company), #COMP
2112 uc($bill->address1), #STREET1
2113 uc($bill->address2), #STREET2
2114 uc($bill->city), #CITY
2115 uc($bill->state), #STATE
2118 time2str('%Y%m%d', $self->_date), #BILL_DATE
2119 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2120 ( map {sprintf('%0.2f', $_)}
2121 $balance_due, #AMNT_DUE
2122 $previous_balance, #PREV_BAL
2123 $payment_total, #PYMT_RCVD
2124 $credit_total, #CREDITS
2125 $previous_balance, #BEG_BAL--is this correct?
2126 $self->charged, #NEW_CHRG
2129 $past_due, #PAST_MSG
2133 my %svc_class = ('' => ''); # maybe cache this more persistently?
2135 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2137 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2138 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2142 my @dates = ( $self->_date, undef );
2143 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2144 $dates[1] = $prev->sdate; #questionable
2147 # generate an 01 detail for each service
2148 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2149 foreach my $cust_svc ( @svcs ) {
2150 $show_pkgnum = ''; # hide it if we're showing svcnums
2152 my $svcpart = $cust_svc->svcpart;
2153 if (!exists($svc_class{$svcpart})) {
2154 my $classnum = $cust_svc->part_svc->classnum;
2155 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2157 $svc_class{$svcpart} = $part_svc_class ?
2158 $part_svc_class->classname :
2162 my @h_label = $cust_svc->label(@dates, 'I');
2163 push @details, sprintf('01%-9s%-20s%-47s',
2165 $svc_class{$svcpart},
2168 } #foreach $cust_svc
2171 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2172 if ($cust_bill_pkg->recur > 0) {
2173 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2174 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2176 push @details, sprintf('02%-6s%-60s%-10s',
2179 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2181 } #foreach $cust_bill_pkg
2183 # Tag this row so that we know whether this is one page (1), two pages
2184 # (2), # or "big" (B). The tag will be stripped off before uploading.
2185 if ( scalar(@details) < 12 ) {
2187 } elsif ( scalar(@details) < 58 ) {
2193 return join('', $header, @details, "\n");
2201 time2str("%x", $self->_date),
2202 sprintf("%.2f", $self->charged),
2203 ( map { $cust_main->getfield($_) }
2204 qw( first last company address1 address2 city state zip country ) ),
2206 ) or die "can't create csv";
2209 my $header = $csv->string. "\n";
2212 if ( lc($opt{'format'}) eq 'billco' ) {
2215 foreach my $item ( $self->_items_pkg ) {
2218 '', # 1 | N/A-Leave Empty CHAR 2
2219 '', # 2 | N/A-Leave Empty CHAR 15
2220 $tracctnum, # 3 | Account Number CHAR 15
2221 $self->invnum, # 4 | Invoice Number CHAR 15
2222 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2223 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2224 $item->{'amount'}, # 7 | Amount NUM* 9
2225 '', # 8 | Line Format Control** CHAR 2
2226 '', # 9 | Grouping Code CHAR 2
2227 '', # 10 | User Defined CHAR 15
2230 $detail .= $csv->string. "\n";
2234 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2240 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2242 my($pkg, $setup, $recur, $sdate, $edate);
2243 if ( $cust_bill_pkg->pkgnum ) {
2245 ($pkg, $setup, $recur, $sdate, $edate) = (
2246 $cust_bill_pkg->part_pkg->pkg,
2247 ( $cust_bill_pkg->setup != 0
2248 ? sprintf("%.2f", $cust_bill_pkg->setup )
2250 ( $cust_bill_pkg->recur != 0
2251 ? sprintf("%.2f", $cust_bill_pkg->recur )
2253 ( $cust_bill_pkg->sdate
2254 ? time2str("%x", $cust_bill_pkg->sdate)
2256 ($cust_bill_pkg->edate
2257 ? time2str("%x", $cust_bill_pkg->edate)
2261 } else { #pkgnum tax
2262 next unless $cust_bill_pkg->setup != 0;
2263 $pkg = $cust_bill_pkg->desc;
2264 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2265 ( $sdate, $edate ) = ( '', '' );
2271 ( map { '' } (1..11) ),
2272 ($pkg, $setup, $recur, $sdate, $edate)
2273 ) or die "can't create csv";
2275 $detail .= $csv->string. "\n";
2281 ( $header, $detail );
2287 Pays this invoice with a compliemntary payment. If there is an error,
2288 returns the error, otherwise returns false.
2294 my $cust_pay = new FS::cust_pay ( {
2295 'invnum' => $self->invnum,
2296 'paid' => $self->owed,
2299 'payinfo' => $self->cust_main->payinfo,
2307 Attempts to pay this invoice with a credit card payment via a
2308 Business::OnlinePayment realtime gateway. See
2309 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2310 for supported processors.
2316 $self->realtime_bop( 'CC', @_ );
2321 Attempts to pay this invoice with an electronic check (ACH) payment via a
2322 Business::OnlinePayment realtime gateway. See
2323 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2324 for supported processors.
2330 $self->realtime_bop( 'ECHECK', @_ );
2335 Attempts to pay this invoice with phone bill (LEC) payment via a
2336 Business::OnlinePayment realtime gateway. See
2337 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2338 for supported processors.
2344 $self->realtime_bop( 'LEC', @_ );
2348 my( $self, $method ) = (shift,shift);
2349 my $conf = $self->conf;
2352 my $cust_main = $self->cust_main;
2353 my $balance = $cust_main->balance;
2354 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2355 $amount = sprintf("%.2f", $amount);
2356 return "not run (balance $balance)" unless $amount > 0;
2358 my $description = 'Internet Services';
2359 if ( $conf->exists('business-onlinepayment-description') ) {
2360 my $dtempl = $conf->config('business-onlinepayment-description');
2362 my $agent_obj = $cust_main->agent
2363 or die "can't retreive agent for $cust_main (agentnum ".
2364 $cust_main->agentnum. ")";
2365 my $agent = $agent_obj->agent;
2366 my $pkgs = join(', ',
2367 map { $_->part_pkg->pkg }
2368 grep { $_->pkgnum } $self->cust_bill_pkg
2370 $description = eval qq("$dtempl");
2373 $cust_main->realtime_bop($method, $amount,
2374 'description' => $description,
2375 'invnum' => $self->invnum,
2376 #this didn't do what we want, it just calls apply_payments_and_credits
2378 'apply_to_invoice' => 1,
2381 #this changes application behavior: auto payments
2382 #triggered against a specific invoice are now applied
2383 #to that invoice instead of oldest open.
2389 =item batch_card OPTION => VALUE...
2391 Adds a payment for this invoice to the pending credit card batch (see
2392 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2393 runs the payment using a realtime gateway.
2398 my ($self, %options) = @_;
2399 my $cust_main = $self->cust_main;
2401 $options{invnum} = $self->invnum;
2403 $cust_main->batch_card(%options);
2406 sub _agent_template {
2408 $self->cust_main->agent_template;
2411 sub _agent_invoice_from {
2413 $self->cust_main->agent_invoice_from;
2416 =item invoice_barcode DIR_OR_FALSE
2418 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2419 it is taken as the temp directory where the PNG file will be generated and the
2420 PNG file name is returned. Otherwise, the PNG image itself is returned.
2424 sub invoice_barcode {
2425 my ($self, $dir) = (shift,shift);
2427 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2428 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2429 my $gd = $gdbar->plot(Height => 30);
2432 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2436 ) or die "can't open temp file: $!\n";
2437 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2438 my $png_file = $bh->filename;
2445 =item invnum_date_pretty
2447 Returns a string with the invoice number and date, for example:
2448 "Invoice #54 (3/20/2008)"
2452 sub invnum_date_pretty {
2454 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2457 #sub _items_extra_usage_sections {
2459 # my $escape = shift;
2461 # my %sections = ();
2463 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2464 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2466 # next unless $cust_bill_pkg->pkgnum > 0;
2468 # foreach my $section ( keys %usage_class ) {
2470 # my $usage = $cust_bill_pkg->usage($section);
2472 # next unless $usage && $usage > 0;
2474 # $sections{$section} ||= 0;
2475 # $sections{$section} += $usage;
2481 # map { { 'description' => &{$escape}($_),
2482 # 'subtotal' => $sections{$_},
2483 # 'summarized' => '',
2484 # 'tax_section' => '',
2487 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2491 sub _items_extra_usage_sections {
2493 my $conf = $self->conf;
2501 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2503 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2504 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2505 next unless $cust_bill_pkg->pkgnum > 0;
2507 foreach my $classnum ( keys %usage_class ) {
2508 my $section = $usage_class{$classnum}->classname;
2509 $classnums{$section} = $classnum;
2511 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2512 my $amount = $detail->amount;
2513 next unless $amount && $amount > 0;
2515 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2516 $sections{$section}{amount} += $amount; #subtotal
2517 $sections{$section}{calls}++;
2518 $sections{$section}{duration} += $detail->duration;
2520 my $desc = $detail->regionname;
2521 my $description = $desc;
2522 $description = substr($desc, 0, $maxlength). '...'
2523 if $format eq 'latex' && length($desc) > $maxlength;
2525 $lines{$section}{$desc} ||= {
2526 description => &{$escape}($description),
2527 #pkgpart => $part_pkg->pkgpart,
2528 pkgnum => $cust_bill_pkg->pkgnum,
2533 #unit_amount => $cust_bill_pkg->unitrecur,
2534 quantity => $cust_bill_pkg->quantity,
2535 product_code => 'N/A',
2536 ext_description => [],
2539 $lines{$section}{$desc}{amount} += $amount;
2540 $lines{$section}{$desc}{calls}++;
2541 $lines{$section}{$desc}{duration} += $detail->duration;
2547 my %sectionmap = ();
2548 foreach (keys %sections) {
2549 my $usage_class = $usage_class{$classnums{$_}};
2550 $sectionmap{$_} = { 'description' => &{$escape}($_),
2551 'amount' => $sections{$_}{amount}, #subtotal
2552 'calls' => $sections{$_}{calls},
2553 'duration' => $sections{$_}{duration},
2555 'tax_section' => '',
2556 'sort_weight' => $usage_class->weight,
2557 ( $usage_class->format
2558 ? ( map { $_ => $usage_class->$_($format) }
2559 qw( description_generator header_generator total_generator total_line_generator )
2566 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2570 foreach my $section ( keys %lines ) {
2571 foreach my $line ( keys %{$lines{$section}} ) {
2572 my $l = $lines{$section}{$line};
2573 $l->{section} = $sectionmap{$section};
2574 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2575 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2580 return(\@sections, \@lines);
2586 my $end = $self->_date;
2588 # start at date of previous invoice + 1 second or 0 if no previous invoice
2589 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2590 $start = 0 if !$start;
2593 my $cust_main = $self->cust_main;
2594 my @pkgs = $cust_main->all_pkgs;
2595 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2598 foreach my $pkg ( @pkgs ) {
2599 my @h_cust_svc = $pkg->h_cust_svc($end);
2600 foreach my $h_cust_svc ( @h_cust_svc ) {
2601 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2602 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2604 my $inserted = $h_cust_svc->date_inserted;
2605 my $deleted = $h_cust_svc->date_deleted;
2606 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2608 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2610 # DID either activated or ported in; cannot be both for same DID simultaneously
2611 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2612 && (!$phone_inserted->lnp_status
2613 || $phone_inserted->lnp_status eq ''
2614 || $phone_inserted->lnp_status eq 'native')) {
2617 else { # this one not so clean, should probably move to (h_)svc_phone
2618 my $phone_portedin = qsearchs( 'h_svc_phone',
2619 { 'svcnum' => $h_cust_svc->svcnum,
2620 'lnp_status' => 'portedin' },
2621 FS::h_svc_phone->sql_h_searchs($end),
2623 $num_portedin++ if $phone_portedin;
2626 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2627 if($deleted >= $start && $deleted <= $end && $phone_deleted
2628 && (!$phone_deleted->lnp_status
2629 || $phone_deleted->lnp_status ne 'portingout')) {
2632 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2633 && $phone_deleted->lnp_status
2634 && $phone_deleted->lnp_status eq 'portingout') {
2638 # increment usage minutes
2639 if ( $phone_inserted ) {
2640 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2641 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2644 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2647 # don't look at this service again
2648 push @seen, $h_cust_svc->svcnum;
2652 $minutes = sprintf("%d", $minutes);
2653 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2654 . "$num_deactivated Ported-Out: $num_portedout ",
2655 "Total Minutes: $minutes");
2658 sub _items_accountcode_cdr {
2663 my $section = { 'amount' => 0,
2666 'sort_weight' => '',
2668 'description' => 'Usage by Account Code',
2674 my %accountcodes = ();
2676 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2677 next unless $cust_bill_pkg->pkgnum > 0;
2679 my @header = $cust_bill_pkg->details_header;
2680 next unless scalar(@header);
2681 $section->{'header'} = join(',',@header);
2683 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2685 $section->{'header'} = $detail->formatted('format' => $format)
2686 if($detail->detail eq $section->{'header'});
2688 my $accountcode = $detail->accountcode;
2689 next unless $accountcode;
2691 my $amount = $detail->amount;
2692 next unless $amount && $amount > 0;
2694 $accountcodes{$accountcode} ||= {
2695 description => $accountcode,
2702 product_code => 'N/A',
2703 section => $section,
2704 ext_description => [ $section->{'header'} ],
2708 $section->{'amount'} += $amount;
2709 $accountcodes{$accountcode}{'amount'} += $amount;
2710 $accountcodes{$accountcode}{calls}++;
2711 $accountcodes{$accountcode}{duration} += $detail->duration;
2712 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2716 foreach my $l ( values %accountcodes ) {
2717 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2718 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2719 foreach my $sorted_detail ( @sorted_detail ) {
2720 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2722 delete $l->{detail_temp};
2726 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2728 return ($section,\@sorted_lines);
2731 sub _items_svc_phone_sections {
2733 my $conf = $self->conf;
2741 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2743 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2744 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2746 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2747 next unless $cust_bill_pkg->pkgnum > 0;
2749 my @header = $cust_bill_pkg->details_header;
2750 next unless scalar(@header);
2752 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2754 my $phonenum = $detail->phonenum;
2755 next unless $phonenum;
2757 my $amount = $detail->amount;
2758 next unless $amount && $amount > 0;
2760 $sections{$phonenum} ||= { 'amount' => 0,
2763 'sort_weight' => -1,
2764 'phonenum' => $phonenum,
2766 $sections{$phonenum}{amount} += $amount; #subtotal
2767 $sections{$phonenum}{calls}++;
2768 $sections{$phonenum}{duration} += $detail->duration;
2770 my $desc = $detail->regionname;
2771 my $description = $desc;
2772 $description = substr($desc, 0, $maxlength). '...'
2773 if $format eq 'latex' && length($desc) > $maxlength;
2775 $lines{$phonenum}{$desc} ||= {
2776 description => &{$escape}($description),
2777 #pkgpart => $part_pkg->pkgpart,
2785 product_code => 'N/A',
2786 ext_description => [],
2789 $lines{$phonenum}{$desc}{amount} += $amount;
2790 $lines{$phonenum}{$desc}{calls}++;
2791 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2793 my $line = $usage_class{$detail->classnum}->classname;
2794 $sections{"$phonenum $line"} ||=
2798 'sort_weight' => $usage_class{$detail->classnum}->weight,
2799 'phonenum' => $phonenum,
2800 'header' => [ @header ],
2802 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2803 $sections{"$phonenum $line"}{calls}++;
2804 $sections{"$phonenum $line"}{duration} += $detail->duration;
2806 $lines{"$phonenum $line"}{$desc} ||= {
2807 description => &{$escape}($description),
2808 #pkgpart => $part_pkg->pkgpart,
2816 product_code => 'N/A',
2817 ext_description => [],
2820 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2821 $lines{"$phonenum $line"}{$desc}{calls}++;
2822 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2823 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2824 $detail->formatted('format' => $format);
2829 my %sectionmap = ();
2830 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2831 foreach ( keys %sections ) {
2832 my @header = @{ $sections{$_}{header} || [] };
2834 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2835 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2836 my $usage_class = $summary ? $simple : $usage_simple;
2837 my $ending = $summary ? ' usage charges' : '';
2840 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2842 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2843 'amount' => $sections{$_}{amount}, #subtotal
2844 'calls' => $sections{$_}{calls},
2845 'duration' => $sections{$_}{duration},
2847 'tax_section' => '',
2848 'phonenum' => $sections{$_}{phonenum},
2849 'sort_weight' => $sections{$_}{sort_weight},
2850 'post_total' => $summary, #inspire pagebreak
2852 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2853 qw( description_generator
2856 total_line_generator
2863 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2864 $a->{sort_weight} <=> $b->{sort_weight}
2869 foreach my $section ( keys %lines ) {
2870 foreach my $line ( keys %{$lines{$section}} ) {
2871 my $l = $lines{$section}{$line};
2872 $l->{section} = $sectionmap{$section};
2873 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2874 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2879 if($conf->exists('phone_usage_class_summary')) {
2880 # this only works with Latex
2884 # after this, we'll have only two sections per DID:
2885 # Calls Summary and Calls Detail
2886 foreach my $section ( @sections ) {
2887 if($section->{'post_total'}) {
2888 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2889 $section->{'total_line_generator'} = sub { '' };
2890 $section->{'total_generator'} = sub { '' };
2891 $section->{'header_generator'} = sub { '' };
2892 $section->{'description_generator'} = '';
2893 push @newsections, $section;
2894 my %calls_detail = %$section;
2895 $calls_detail{'post_total'} = '';
2896 $calls_detail{'sort_weight'} = '';
2897 $calls_detail{'description_generator'} = sub { '' };
2898 $calls_detail{'header_generator'} = sub {
2899 return ' & Date/Time & Called Number & Duration & Price'
2900 if $format eq 'latex';
2903 $calls_detail{'description'} = 'Calls Detail: '
2904 . $section->{'phonenum'};
2905 push @newsections, \%calls_detail;
2909 # after this, each usage class is collapsed/summarized into a single
2910 # line under the Calls Summary section
2911 foreach my $newsection ( @newsections ) {
2912 if($newsection->{'post_total'}) { # this means Calls Summary
2913 foreach my $section ( @sections ) {
2914 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2915 && !$section->{'post_total'});
2916 my $newdesc = $section->{'description'};
2917 my $tn = $section->{'phonenum'};
2918 $newdesc =~ s/$tn//g;
2919 my $line = { ext_description => [],
2923 calls => $section->{'calls'},
2924 section => $newsection,
2925 duration => $section->{'duration'},
2926 description => $newdesc,
2927 amount => sprintf("%.2f",$section->{'amount'}),
2928 product_code => 'N/A',
2930 push @newlines, $line;
2935 # after this, Calls Details is populated with all CDRs
2936 foreach my $newsection ( @newsections ) {
2937 if(!$newsection->{'post_total'}) { # this means Calls Details
2938 foreach my $line ( @lines ) {
2939 next unless (scalar(@{$line->{'ext_description'}}) &&
2940 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2942 my @extdesc = @{$line->{'ext_description'}};
2944 foreach my $extdesc ( @extdesc ) {
2945 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2946 push @newextdesc, $extdesc;
2948 $line->{'ext_description'} = \@newextdesc;
2949 $line->{'section'} = $newsection;
2950 push @newlines, $line;
2955 return(\@newsections, \@newlines);
2958 return(\@sections, \@lines);
2962 sub _items_previous {
2964 my $conf = $self->conf;
2965 my $cust_main = $self->cust_main;
2966 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2968 foreach ( @pr_cust_bill ) {
2969 my $date = $conf->exists('invoice_show_prior_due_date')
2970 ? 'due '. $_->due_date2str('short')
2971 : $self->time2str_local('short', $_->_date);
2973 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2974 #'pkgpart' => 'N/A',
2976 'amount' => sprintf("%.2f", $_->owed),
2982 # 'description' => 'Previous Balance',
2983 # #'pkgpart' => 'N/A',
2984 # 'pkgnum' => 'N/A',
2985 # 'amount' => sprintf("%10.2f", $pr_total ),
2986 # 'ext_description' => [ map {
2987 # "Invoice ". $_->invnum.
2988 # " (". time2str("%x",$_->_date). ") ".
2989 # sprintf("%10.2f", $_->owed)
2990 # } @pr_cust_bill ],
2995 sub _items_credits {
2996 my( $self, %opt ) = @_;
2997 my $trim_len = $opt{'trim_len'} || 60;
3002 if ( $self->conf->exists('previous_balance-payments_since') ) {
3003 if ( $opt{'template'} eq 'statement' ) {
3004 # then the current bill is a "statement" (i.e. an invoice sent as
3005 # a payment receipt)
3006 # and in that case we want to see payments on or after THIS invoice
3007 @objects = qsearch('cust_credit', {
3008 'custnum' => $self->custnum,
3009 '_date' => {op => '>=', value => $self->_date},
3013 $date = $self->previous_bill->_date if $self->previous_bill;
3014 @objects = qsearch('cust_credit', {
3015 'custnum' => $self->custnum,
3016 '_date' => {op => '>=', value => $date},
3020 @objects = $self->cust_credited;
3023 foreach my $obj ( @objects ) {
3024 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3026 my $reason = substr($cust_credit->reason, 0, $trim_len);
3027 $reason .= '...' if length($reason) < length($cust_credit->reason);
3028 $reason = " ($reason) " if $reason;
3031 #'description' => 'Credit ref\#'. $_->crednum.
3032 # " (". time2str("%x",$_->cust_credit->_date) .")".
3034 'description' => $self->mt('Credit applied').' '.
3035 $self->time2str_local('short', $obj->_date). $reason,
3036 'amount' => sprintf("%.2f",$obj->amount),
3044 sub _items_payments {
3049 my $detailed = $self->conf->exists('invoice_payment_details');
3051 if ( $self->conf->exists('previous_balance-payments_since') ) {
3052 # then show payments dated on/after the previous bill...
3053 if ( $opt{'template'} eq 'statement' ) {
3054 # then the current bill is a "statement" (i.e. an invoice sent as
3055 # a payment receipt)
3056 # and in that case we want to see payments on or after THIS invoice
3057 @objects = qsearch('cust_pay', {
3058 'custnum' => $self->custnum,
3059 '_date' => {op => '>=', value => $self->_date},
3062 # the normal case: payments on or after the previous invoice
3064 $date = $self->previous_bill->_date if $self->previous_bill;
3065 @objects = qsearch('cust_pay', {
3066 'custnum' => $self->custnum,
3067 '_date' => {op => '>=', value => $date},
3069 # and before the current bill...
3070 @objects = grep { $_->_date < $self->_date } @objects;
3073 @objects = $self->cust_bill_pay;
3076 foreach my $obj (@objects) {
3077 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3078 my $desc = $self->mt('Payment received').' '.
3079 $self->time2str_local('short', $cust_pay->_date );
3080 $desc .= $self->mt(' via ') .
3081 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3085 'description' => $desc,
3086 'amount' => sprintf("%.2f", $obj->amount )
3094 =item call_details [ OPTION => VALUE ... ]
3096 Returns an array of CSV strings representing the call details for this invoice
3097 The only option available is the boolean prepend_billed_number
3102 my ($self, %opt) = @_;
3104 my $format_function = sub { shift };
3106 if ($opt{prepend_billed_number}) {
3107 $format_function = sub {
3111 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3116 my @details = map { $_->details( 'format_function' => $format_function,
3117 'escape_function' => sub{ return() },
3121 $self->cust_bill_pkg;
3122 my $header = $details[0];
3123 ( $header, grep { $_ ne $header } @details );
3133 =item process_reprint
3137 sub process_reprint {
3138 process_re_X('print', @_);
3141 =item process_reemail
3145 sub process_reemail {
3146 process_re_X('email', @_);
3154 process_re_X('fax', @_);
3162 process_re_X('ftp', @_);
3169 sub process_respool {
3170 process_re_X('spool', @_);
3173 use Storable qw(thaw);
3177 my( $method, $job ) = ( shift, shift );
3178 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3180 my $param = thaw(decode_base64(shift));
3181 warn Dumper($param) if $DEBUG;
3192 # spool_invoice ftp_invoice fax_invoice print_invoice
3193 my($method, $job, %param ) = @_;
3195 warn "re_X $method for job $job with param:\n".
3196 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3199 #some false laziness w/search/cust_bill.html
3201 my $orderby = 'ORDER BY cust_bill._date';
3203 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3205 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3207 my @cust_bill = qsearch( {
3208 #'select' => "cust_bill.*",
3209 'table' => 'cust_bill',
3210 'addl_from' => $addl_from,
3212 'extra_sql' => $extra_sql,
3213 'order_by' => $orderby,
3217 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3219 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3222 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3223 foreach my $cust_bill ( @cust_bill ) {
3224 $cust_bill->$method();
3226 if ( $job ) { #progressbar foo
3228 if ( time - $min_sec > $last ) {
3229 my $error = $job->update_statustext(
3230 int( 100 * $num / scalar(@cust_bill) )
3232 die $error if $error;
3243 =head1 CLASS METHODS
3249 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3254 my ($class, $start, $end) = @_;
3256 $class->paid_sql($start, $end). ' - '.
3257 $class->credited_sql($start, $end);
3262 Returns an SQL fragment to retreive the net amount (charged minus credited).
3267 my ($class, $start, $end) = @_;
3268 'charged - '. $class->credited_sql($start, $end);
3273 Returns an SQL fragment to retreive the amount paid against this invoice.
3278 my ($class, $start, $end) = @_;
3279 $start &&= "AND cust_bill_pay._date <= $start";
3280 $end &&= "AND cust_bill_pay._date > $end";
3281 $start = '' unless defined($start);
3282 $end = '' unless defined($end);
3283 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3284 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3289 Returns an SQL fragment to retreive the amount credited against this invoice.
3294 my ($class, $start, $end) = @_;
3295 $start &&= "AND cust_credit_bill._date <= $start";
3296 $end &&= "AND cust_credit_bill._date > $end";
3297 $start = '' unless defined($start);
3298 $end = '' unless defined($end);
3299 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3300 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3305 Returns an SQL fragment to retrieve the due date of an invoice.
3306 Currently only supported on PostgreSQL.
3311 my $conf = new FS::Conf;
3315 cust_bill.invoice_terms,
3316 cust_main.invoice_terms,
3317 \''.($conf->config('invoice_default_terms') || '').'\'
3318 ), E\'Net (\\\\d+)\'
3320 ) * 86400 + cust_bill._date'
3323 =item search_sql_where HASHREF
3325 Class method which returns an SQL WHERE fragment to search for parameters
3326 specified in HASHREF. Valid parameters are
3332 List reference of start date, end date, as UNIX timestamps.
3342 List reference of charged limits (exclusive).
3346 List reference of charged limits (exclusive).
3350 flag, return open invoices only
3354 flag, return net invoices only
3358 =item newest_percust
3362 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3366 sub search_sql_where {
3367 my($class, $param) = @_;
3369 warn "$me search_sql_where called with params: \n".
3370 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3376 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3377 push @search, "cust_main.agentnum = $1";
3381 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3382 push @search, "cust_main.refnum = $1";
3386 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3387 push @search, "cust_bill.custnum = $1";
3390 #customer classnum (false laziness w/ cust_main/Search.pm)
3391 if ( $param->{'cust_classnum'} ) {
3393 my @classnum = ref( $param->{'cust_classnum'} )
3394 ? @{ $param->{'cust_classnum'} }
3395 : ( $param->{'cust_classnum'} );
3397 @classnum = grep /^(\d*)$/, @classnum;
3400 push @search, '( '. join(' OR ', map {
3401 $_ ? "cust_main.classnum = $_"
3402 : "cust_main.classnum IS NULL"
3412 if ( $param->{_date} ) {
3413 my($beginning, $ending) = @{$param->{_date}};
3415 push @search, "cust_bill._date >= $beginning",
3416 "cust_bill._date < $ending";
3420 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3421 push @search, "cust_bill.invnum >= $1";
3423 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3424 push @search, "cust_bill.invnum <= $1";
3428 if ( $param->{charged} ) {
3429 my @charged = ref($param->{charged})
3430 ? @{ $param->{charged} }
3431 : ($param->{charged});
3433 push @search, map { s/^charged/cust_bill.charged/; $_; }
3437 my $owed_sql = FS::cust_bill->owed_sql;
3440 if ( $param->{owed} ) {
3441 my @owed = ref($param->{owed})
3442 ? @{ $param->{owed} }
3444 push @search, map { s/^owed/$owed_sql/; $_; }
3449 push @search, "0 != $owed_sql"
3450 if $param->{'open'};
3451 push @search, '0 != '. FS::cust_bill->net_sql
3455 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3456 if $param->{'days'};
3459 if ( $param->{'newest_percust'} ) {
3461 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3462 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3464 my @newest_where = map { my $x = $_;
3465 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3468 grep ! /^cust_main./, @search;
3469 my $newest_where = scalar(@newest_where)
3470 ? ' AND '. join(' AND ', @newest_where)
3474 push @search, "cust_bill._date = (
3475 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3476 WHERE newest_cust_bill.custnum = cust_bill.custnum
3482 #promised_date - also has an option to accept nulls
3483 if ( $param->{promised_date} ) {
3484 my($beginning, $ending, $null) = @{$param->{promised_date}};
3486 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3487 "cust_bill.promised_date < $ending )" .
3488 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3491 #agent virtualization
3492 my $curuser = $FS::CurrentUser::CurrentUser;
3493 if ( $curuser->username eq 'fs_queue'
3494 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3496 my $newuser = qsearchs('access_user', {
3497 'username' => $username,
3501 $curuser = $newuser;
3503 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3506 push @search, $curuser->agentnums_sql;
3508 join(' AND ', @search );
3520 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3521 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base