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 'Charset' => 'UTF-8',
1123 #'Encoding' => '7bit',
1125 'Disposition' => 'inline',
1132 if ( $conf->exists('invoice_email_pdf')
1133 and scalar($conf->config('invoice_email_pdf_note')) ) {
1135 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1139 $args{'from'} =~ /\@([\w\.\-]+)/;
1140 my $from = $1 || 'example.com';
1141 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1144 my $agentnum = $cust_main->agentnum;
1145 if ( defined($args{'template'}) && length($args{'template'})
1146 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1149 $logo = 'logo_'. $args{'template'}. '.png';
1153 my $image_data = $conf->config_binary( $logo, $agentnum);
1155 $image = build MIME::Entity
1156 'Type' => 'image/png',
1157 'Encoding' => 'base64',
1158 'Data' => $image_data,
1159 'Filename' => 'logo.png',
1160 'Content-ID' => "<$content_id>",
1163 if ($conf->exists('invoice-barcode')) {
1164 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1165 $barcode = build MIME::Entity
1166 'Type' => 'image/png',
1167 'Encoding' => 'base64',
1168 'Data' => $self->invoice_barcode(0),
1169 'Filename' => 'barcode.png',
1170 'Content-ID' => "<$barcode_content_id>",
1172 $args{'barcode_cid'} = $barcode_content_id;
1175 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1178 $alternative->attach(
1179 'Type' => 'text/html',
1180 'Encoding' => 'quoted-printable',
1181 'Data' => [ '<html>',
1184 ' '. encode_entities($return{'subject'}),
1187 ' <body bgcolor="#e8e8e8">',
1192 'Disposition' => 'inline',
1193 #'Filename' => 'invoice.pdf',
1197 my @otherparts = ();
1198 if ( $cust_main->email_csv_cdr ) {
1200 push @otherparts, build MIME::Entity
1201 'Type' => 'text/csv',
1202 'Encoding' => '7bit',
1203 'Data' => [ map { "$_\n" }
1204 $self->call_details('prepend_billed_number' => 1)
1206 'Disposition' => 'attachment',
1207 'Filename' => 'usage-'. $self->invnum. '.csv',
1212 if ( $conf->exists('invoice_email_pdf') ) {
1217 # multipart/alternative
1223 my $related = build MIME::Entity 'Type' => 'multipart/related',
1224 'Encoding' => '7bit';
1226 #false laziness w/Misc::send_email
1227 $related->head->replace('Content-type',
1228 $related->mime_type.
1229 '; boundary="'. $related->head->multipart_boundary. '"'.
1230 '; type=multipart/alternative'
1233 $related->add_part($alternative);
1235 $related->add_part($image) if $image;
1237 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1239 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1243 #no other attachment:
1245 # multipart/alternative
1250 $return{'content-type'} = 'multipart/related';
1251 if ($conf->exists('invoice-barcode') && $barcode) {
1252 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1254 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1256 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1257 #$return{'disposition'} = 'inline';
1263 if ( $conf->exists('invoice_email_pdf') ) {
1264 warn "$me creating PDF attachment"
1267 #mime parts arguments a la MIME::Entity->build().
1268 $return{'mimeparts'} = [
1269 { $self->mimebuild_pdf(\%args) }
1273 if ( $conf->exists('invoice_email_pdf')
1274 and scalar($conf->config('invoice_email_pdf_note')) ) {
1276 warn "$me using 'invoice_email_pdf_note'"
1278 $return{'body'} = [ map { $_ . "\n" }
1279 $conf->config('invoice_email_pdf_note')
1284 warn "$me not using 'invoice_email_pdf_note'"
1286 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1287 $return{'body'} = $args{'print_text'};
1289 $return{'body'} = [ $self->print_text(\%args) ];
1302 Returns a list suitable for passing to MIME::Entity->build(), representing
1303 this invoice as PDF attachment.
1310 'Type' => 'application/pdf',
1311 'Encoding' => 'base64',
1312 'Data' => [ $self->print_pdf(@_) ],
1313 'Disposition' => 'attachment',
1314 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1320 Sends this invoice to the destinations configured for this customer: sends
1321 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1323 Options can be passed as a hashref. Positional parameters are no longer
1326 I<template>: a suffix for alternate invoices
1328 I<agentnum>: obsolete, now does nothing.
1330 I<invoice_from> overrides the default email invoice From: address.
1332 I<amount>: obsolete, does nothing
1334 I<notice_name> overrides "Invoice" as the name of the sent document
1335 (templates from 10/2009 or newer required).
1337 I<lpr> overrides the system 'lpr' option as the command to print a document
1338 from standard input.
1344 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1345 my $conf = $self->conf;
1347 my $cust_main = $self->cust_main;
1349 my @invoicing_list = $cust_main->invoicing_list;
1352 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1353 && ! $self->invoice_noemail;
1356 if grep { $_ eq 'POST' } @invoicing_list; #postal
1358 #this has never been used post-$ORIGINAL_ISP afaik
1359 $self->fax_invoice($opt)
1360 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1366 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1368 Sends this invoice to the customer's email destination(s).
1370 Options must be passed as a hashref. Positional parameters are no longer
1373 I<template>, if specified, is the name of a suffix for alternate invoices.
1375 I<invoice_from>, if specified, overrides the default email invoice From:
1378 I<notice_name> is the name of the sent document.
1382 sub queueable_email {
1385 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1386 or die "invalid invoice number: " . $opt{invnum};
1388 my %args = map {$_ => $opt{$_}}
1390 qw( invoice_from notice_name no_coupon template );
1392 my $error = $self->email( \%args );
1393 die $error if $error;
1399 return if $self->hide;
1400 my $conf = $self->conf;
1401 my $opt = shift || {};
1402 if ($opt and !ref($opt)) {
1403 die "FS::cust_bill::email called with positional parameters";
1406 my $template = $opt->{template};
1407 my $from = delete $opt->{invoice_from};
1409 # this is where we set the From: address
1410 $from ||= $self->_agent_invoice_from || #XXX should go away
1411 $conf->config('invoice_from', $self->cust_main->agentnum );
1413 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1414 $self->cust_main->invoicing_list;
1416 if ( ! @invoicing_list ) { #no recipients
1417 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1418 die 'No recipients for customer #'. $self->custnum;
1420 #default: better to notify this person than silence
1421 @invoicing_list = ($from);
1425 # this is where we set the Subject:
1426 my $subject = $self->email_subject($template);
1428 my $error = send_email(
1429 $self->generate_email(
1431 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1432 'subject' => $subject,
1433 %$opt, # template, etc.
1436 die "can't email invoice: $error\n" if $error;
1437 #die "$error\n" if $error;
1443 my $conf = $self->conf;
1445 #my $template = scalar(@_) ? shift : '';
1448 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1451 my $cust_main = $self->cust_main;
1452 my $name = $cust_main->name;
1453 my $name_short = $cust_main->name_short;
1454 my $invoice_number = $self->invnum;
1455 my $invoice_date = $self->_date_pretty;
1457 eval qq("$subject");
1460 =item lpr_data HASHREF
1462 Returns the postscript or plaintext for this invoice as an arrayref.
1464 Options must be passed as a hashref. Positional parameters are no longer
1467 I<template>, if specified, is the name of a suffix for alternate invoices.
1469 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1475 my $conf = $self->conf;
1476 my $opt = shift || {};
1477 if ($opt and !ref($opt)) {
1478 # nobody does this anyway
1479 die "FS::cust_bill::lpr_data called with positional parameters";
1482 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1483 [ $self->$method( $opt ) ];
1488 Prints this invoice.
1490 Options must be passed as a hashref.
1492 I<template>, if specified, is the name of a suffix for alternate invoices.
1494 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1500 return if $self->hide;
1501 my $conf = $self->conf;
1502 my $opt = shift || {};
1503 if ($opt and !ref($opt)) {
1504 die "FS::cust_bill::print called with positional parameters";
1507 my $lpr = delete $opt->{lpr};
1508 if($conf->exists('invoice_print_pdf')) {
1509 # Add the invoice to the current batch.
1510 $self->batch_invoice($opt);
1514 $self->lpr_data($opt),
1515 'agentnum' => $self->cust_main->agentnum,
1521 =item fax_invoice HASHREF
1525 Options must be passed as a hashref.
1527 I<template>, if specified, is the name of a suffix for alternate invoices.
1529 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1535 return if $self->hide;
1536 my $conf = $self->conf;
1537 my $opt = shift || {};
1538 if ($opt and !ref($opt)) {
1539 die "FS::cust_bill::fax_invoice called with positional parameters";
1542 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1543 unless $conf->exists('invoice_latex');
1545 my $dialstring = $self->cust_main->getfield('fax');
1548 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1549 'dialstring' => $dialstring,
1551 die $error if $error;
1555 =item batch_invoice [ HASHREF ]
1557 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1558 isn't an open batch, one will be created.
1563 my ($self, $opt) = @_;
1564 my $bill_batch = $self->get_open_bill_batch;
1565 my $cust_bill_batch = FS::cust_bill_batch->new({
1566 batchnum => $bill_batch->batchnum,
1567 invnum => $self->invnum,
1569 return $cust_bill_batch->insert($opt);
1572 =item get_open_batch
1574 Returns the currently open batch as an FS::bill_batch object, creating a new
1575 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1580 sub get_open_bill_batch {
1582 my $conf = $self->conf;
1583 my $hashref = { status => 'O' };
1584 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1585 ? $self->cust_main->agentnum
1587 my $batch = qsearchs('bill_batch', $hashref);
1588 return $batch if $batch;
1589 $batch = FS::bill_batch->new($hashref);
1590 my $error = $batch->insert;
1591 die $error if $error;
1595 =item ftp_invoice [ TEMPLATENAME ]
1597 Sends this invoice data via FTP.
1599 TEMPLATENAME is unused?
1605 my $conf = $self->conf;
1606 my $template = scalar(@_) ? shift : '';
1609 'protocol' => 'ftp',
1610 'server' => $conf->config('cust_bill-ftpserver'),
1611 'username' => $conf->config('cust_bill-ftpusername'),
1612 'password' => $conf->config('cust_bill-ftppassword'),
1613 'dir' => $conf->config('cust_bill-ftpdir'),
1614 'format' => $conf->config('cust_bill-ftpformat'),
1618 =item spool_invoice [ TEMPLATENAME ]
1620 Spools this invoice data (see L<FS::spool_csv>)
1622 TEMPLATENAME is unused?
1628 my $conf = $self->conf;
1629 my $template = scalar(@_) ? shift : '';
1632 'format' => $conf->config('cust_bill-spoolformat'),
1633 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1637 =item send_csv OPTION => VALUE, ...
1639 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1643 protocol - currently only "ftp"
1649 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1650 and YYMMDDHHMMSS is a timestamp.
1652 See L</print_csv> for a description of the output format.
1657 my($self, %opt) = @_;
1661 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1662 mkdir $spooldir, 0700 unless -d $spooldir;
1664 # don't localize dates here, they're a defined format
1665 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1666 my $file = "$spooldir/$tracctnum.csv";
1668 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1670 open(CSV, ">$file") or die "can't open $file: $!";
1678 if ( $opt{protocol} eq 'ftp' ) {
1679 eval "use Net::FTP;";
1681 $net = Net::FTP->new($opt{server}) or die @$;
1683 die "unknown protocol: $opt{protocol}";
1686 $net->login( $opt{username}, $opt{password} )
1687 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1689 $net->binary or die "can't set binary mode";
1691 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1693 $net->put($file) or die "can't put $file: $!";
1703 Spools CSV invoice data.
1709 =item format - any of FS::Misc::::Invoicing::spool_formats
1711 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1712 customer has the corresponding invoice destinations set (see
1713 L<FS::cust_main_invoice>).
1715 =item agent_spools - if set to a true value, will spool to per-agent files
1716 rather than a single global file
1718 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1719 append to that spool. L<FS::Cron::upload> will then send the spool file to
1722 =item balanceover - if set, only spools the invoice if the total amount owed on
1723 this invoice and all older invoices is greater than the specified amount.
1725 =item time - the "current time". Controls the printing of past due messages
1733 my($self, %opt) = @_;
1735 my $time = $opt{'time'} || time;
1736 my $cust_main = $self->cust_main;
1738 if ( $opt{'dest'} ) {
1739 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1740 $cust_main->invoicing_list;
1741 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1742 || ! keys %invoicing_list;
1745 if ( $opt{'balanceover'} ) {
1747 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1750 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1751 mkdir $spooldir, 0700 unless -d $spooldir;
1753 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1756 if ( $opt{'agent_spools'} ) {
1757 $file = 'agentnum'.$cust_main->agentnum;
1762 if ( $opt{'upload_targetnum'} ) {
1763 $spooldir .= '/target'.$opt{'upload_targetnum'};
1764 mkdir $spooldir, 0700 unless -d $spooldir;
1765 } # otherwise it just goes into export.xxx/cust_bill
1767 if ( lc($opt{'format'}) eq 'billco' ) {
1771 $file = "$spooldir/$file.csv";
1773 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1775 open(CSV, ">>$file") or die "can't open $file: $!";
1776 flock(CSV, LOCK_EX);
1781 if ( lc($opt{'format'}) eq 'billco' ) {
1783 flock(CSV, LOCK_UN);
1786 $file =~ s/-header.csv$/-detail.csv/;
1788 open(CSV,">>$file") or die "can't open $file: $!";
1789 flock(CSV, LOCK_EX);
1793 print CSV $detail if defined($detail);
1795 flock(CSV, LOCK_UN);
1802 =item print_csv OPTION => VALUE, ...
1804 Returns CSV data for this invoice.
1808 format - 'default', 'billco', 'oneline', 'bridgestone'
1810 Returns a list consisting of two scalars. The first is a single line of CSV
1811 header information for this invoice. The second is one or more lines of CSV
1812 detail information for this invoice.
1814 If I<format> is not specified or "default", the fields of the CSV file are as
1817 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1818 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1822 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1824 B<record_type> is C<cust_bill> for the initial header line only. The
1825 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1826 fields are filled in.
1828 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1829 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1832 =item invnum - invoice number
1834 =item custnum - customer number
1836 =item _date - invoice date
1838 =item charged - total invoice amount
1840 =item first - customer first name
1842 =item last - customer first name
1844 =item company - company name
1846 =item address1 - address line 1
1848 =item address2 - address line 1
1858 =item pkg - line item description
1860 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1862 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1864 =item sdate - start date for recurring fee
1866 =item edate - end date for recurring fee
1870 If I<format> is "billco", the fields of the header CSV file are as follows:
1872 +-------------------------------------------------------------------+
1873 | FORMAT HEADER FILE |
1874 |-------------------------------------------------------------------|
1875 | Field | Description | Name | Type | Width |
1876 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1877 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1878 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1879 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1880 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1881 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1882 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1883 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1884 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1885 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1886 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1887 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1888 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1889 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1890 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1891 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1892 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1893 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1894 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1895 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1896 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1897 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1898 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1899 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1900 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1901 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1902 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1903 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1904 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1905 +-------+-------------------------------+------------+------+-------+
1907 If I<format> is "billco", the fields of the detail CSV file are as follows:
1909 FORMAT FOR DETAIL FILE
1911 Field | Description | Name | Type | Width
1912 1 | N/A-Leave Empty | RC | CHAR | 2
1913 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1914 3 | Account Number | TRACCTNUM | CHAR | 15
1915 4 | Invoice Number | TRINVOICE | CHAR | 15
1916 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1917 6 | Transaction Detail | DETAILS | CHAR | 100
1918 7 | Amount | AMT | NUM* | 9
1919 8 | Line Format Control** | LNCTRL | CHAR | 2
1920 9 | Grouping Code | GROUP | CHAR | 2
1921 10 | User Defined | ACCT CODE | CHAR | 15
1923 If format is 'oneline', there is no detail file. Each invoice has a
1924 header line only, with the fields:
1926 Agent number, agent name, customer number, first name, last name, address
1927 line 1, address line 2, city, state, zip, invoice date, invoice number,
1928 amount charged, amount due, previous balance, due date.
1930 and then, for each line item, three columns containing the package number,
1931 description, and amount.
1933 If format is 'bridgestone', there is no detail file. Each invoice has a
1934 header line with the following fields in a fixed-width format:
1936 Customer number (in display format), date, name (first last), company,
1937 address 1, address 2, city, state, zip.
1939 This is a mailing list format, and has no per-invoice fields. To avoid
1940 sending redundant notices, the spooling event should have a "once" or
1941 "once_percust_every" condition.
1946 my($self, %opt) = @_;
1948 eval "use Text::CSV_XS";
1951 my $cust_main = $self->cust_main;
1953 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1954 my $format = lc($opt{'format'});
1956 my $time = $opt{'time'} || time;
1958 my $tracctnum = ''; #leaking out from billco-specific sections :/
1959 if ( $format eq 'billco' ) {
1962 $self->conf->config('billco-account_num', $cust_main->agentnum);
1964 $tracctnum = $account_num eq 'display_custnum'
1965 ? $cust_main->display_custnum
1966 : $opt{'tracctnum'};
1969 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1971 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1973 my( $previous_balance, @unused ) = $self->previous; #previous balance
1975 my $pmt_cr_applied = 0;
1976 $pmt_cr_applied += $_->{'amount'}
1977 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1979 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1982 '', # 1 | N/A-Leave Empty CHAR 2
1983 '', # 2 | N/A-Leave Empty CHAR 15
1984 $tracctnum, # 3 | Transaction Account No CHAR 15
1985 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1986 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1987 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1988 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1989 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1990 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1991 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1992 '', # 10 | Ancillary Billing Information CHAR 30
1993 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1994 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1997 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
2000 $duedate, # 14 | Bill Due Date CHAR 10
2002 $previous_balance, # 15 | Previous Balance NUM* 9
2003 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2004 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2005 $totaldue, # 18 | Total Amt Due NUM* 9
2006 $totaldue, # 19 | Total Amt Due NUM* 9
2007 '', # 20 | 30 Day Aging NUM* 9
2008 '', # 21 | 60 Day Aging NUM* 9
2009 '', # 22 | 90 Day Aging NUM* 9
2010 'N', # 23 | Y/N CHAR 1
2011 '', # 24 | Remittance automation CHAR 100
2012 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2013 $self->custnum, # 26 | Customer Reference Number CHAR 15
2014 '0', # 27 | Federal Tax*** NUM* 9
2015 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2016 '0', # 29 | Other Taxes & Fees*** NUM* 9
2019 } elsif ( $format eq 'oneline' ) { #name
2021 my ($previous_balance) = $self->previous;
2022 $previous_balance = sprintf('%.2f', $previous_balance);
2023 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2029 $self->_items_pkg, #_items_nontax? no sections or anything
2034 $cust_main->agentnum,
2035 $cust_main->agent->agent,
2039 $cust_main->company,
2040 $cust_main->address1,
2041 $cust_main->address2,
2047 time2str("%x", $self->_date),
2052 $self->due_date2str("%x"),
2057 } elsif ( $format eq 'bridgestone' ) {
2059 # bypass the CSV stuff and just return this
2060 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2061 my $zip = $cust_main->zip;
2063 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2067 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2069 $cust_main->display_custnum,
2071 uc(substr($cust_main->contact_firstlast,0,30)),
2072 uc(substr($cust_main->company ,0,30)),
2073 uc(substr($cust_main->address1 ,0,30)),
2074 uc(substr($cust_main->address2 ,0,30)),
2075 uc(substr($cust_main->city ,0,20)),
2076 uc($cust_main->state),
2082 } elsif ( $format eq 'ics' ) {
2084 my $bill = $cust_main->bill_location;
2085 my $zip = $bill->zip;
2089 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2094 # minor false laziness with print_generic
2095 my ($previous_balance) = $self->previous;
2096 my $balance_due = $self->owed + $previous_balance;
2097 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2098 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2101 if ( $self->due_date and $time >= $self->due_date ) {
2102 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2106 my $header = sprintf(
2107 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2108 $cust_main->display_custnum, #BID
2109 uc($cust_main->first), #FNAME
2110 uc($cust_main->last), #LNAME
2111 '00', #BATCH, should this ever be anything else?
2112 uc($cust_main->company), #COMP
2113 uc($bill->address1), #STREET1
2114 uc($bill->address2), #STREET2
2115 uc($bill->city), #CITY
2116 uc($bill->state), #STATE
2119 time2str('%Y%m%d', $self->_date), #BILL_DATE
2120 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2121 ( map {sprintf('%0.2f', $_)}
2122 $balance_due, #AMNT_DUE
2123 $previous_balance, #PREV_BAL
2124 $payment_total, #PYMT_RCVD
2125 $credit_total, #CREDITS
2126 $previous_balance, #BEG_BAL--is this correct?
2127 $self->charged, #NEW_CHRG
2130 $past_due, #PAST_MSG
2134 my %svc_class = ('' => ''); # maybe cache this more persistently?
2136 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2138 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2139 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2143 my @dates = ( $self->_date, undef );
2144 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2145 $dates[1] = $prev->sdate; #questionable
2148 # generate an 01 detail for each service
2149 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2150 foreach my $cust_svc ( @svcs ) {
2151 $show_pkgnum = ''; # hide it if we're showing svcnums
2153 my $svcpart = $cust_svc->svcpart;
2154 if (!exists($svc_class{$svcpart})) {
2155 my $classnum = $cust_svc->part_svc->classnum;
2156 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2158 $svc_class{$svcpart} = $part_svc_class ?
2159 $part_svc_class->classname :
2163 my @h_label = $cust_svc->label(@dates, 'I');
2164 push @details, sprintf('01%-9s%-20s%-47s',
2166 $svc_class{$svcpart},
2169 } #foreach $cust_svc
2172 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2173 if ($cust_bill_pkg->recur > 0) {
2174 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2175 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2177 push @details, sprintf('02%-6s%-60s%-10s',
2180 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2182 } #foreach $cust_bill_pkg
2184 # Tag this row so that we know whether this is one page (1), two pages
2185 # (2), # or "big" (B). The tag will be stripped off before uploading.
2186 if ( scalar(@details) < 12 ) {
2188 } elsif ( scalar(@details) < 58 ) {
2194 return join('', $header, @details, "\n");
2202 time2str("%x", $self->_date),
2203 sprintf("%.2f", $self->charged),
2204 ( map { $cust_main->getfield($_) }
2205 qw( first last company address1 address2 city state zip country ) ),
2207 ) or die "can't create csv";
2210 my $header = $csv->string. "\n";
2213 if ( lc($opt{'format'}) eq 'billco' ) {
2216 foreach my $item ( $self->_items_pkg ) {
2219 '', # 1 | N/A-Leave Empty CHAR 2
2220 '', # 2 | N/A-Leave Empty CHAR 15
2221 $tracctnum, # 3 | Account Number CHAR 15
2222 $self->invnum, # 4 | Invoice Number CHAR 15
2223 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2224 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2225 $item->{'amount'}, # 7 | Amount NUM* 9
2226 '', # 8 | Line Format Control** CHAR 2
2227 '', # 9 | Grouping Code CHAR 2
2228 '', # 10 | User Defined CHAR 15
2231 $detail .= $csv->string. "\n";
2235 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2241 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2243 my($pkg, $setup, $recur, $sdate, $edate);
2244 if ( $cust_bill_pkg->pkgnum ) {
2246 ($pkg, $setup, $recur, $sdate, $edate) = (
2247 $cust_bill_pkg->part_pkg->pkg,
2248 ( $cust_bill_pkg->setup != 0
2249 ? sprintf("%.2f", $cust_bill_pkg->setup )
2251 ( $cust_bill_pkg->recur != 0
2252 ? sprintf("%.2f", $cust_bill_pkg->recur )
2254 ( $cust_bill_pkg->sdate
2255 ? time2str("%x", $cust_bill_pkg->sdate)
2257 ($cust_bill_pkg->edate
2258 ? time2str("%x", $cust_bill_pkg->edate)
2262 } else { #pkgnum tax
2263 next unless $cust_bill_pkg->setup != 0;
2264 $pkg = $cust_bill_pkg->desc;
2265 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2266 ( $sdate, $edate ) = ( '', '' );
2272 ( map { '' } (1..11) ),
2273 ($pkg, $setup, $recur, $sdate, $edate)
2274 ) or die "can't create csv";
2276 $detail .= $csv->string. "\n";
2282 ( $header, $detail );
2288 Pays this invoice with a compliemntary payment. If there is an error,
2289 returns the error, otherwise returns false.
2295 my $cust_pay = new FS::cust_pay ( {
2296 'invnum' => $self->invnum,
2297 'paid' => $self->owed,
2300 'payinfo' => $self->cust_main->payinfo,
2308 Attempts to pay this invoice with a credit card payment via a
2309 Business::OnlinePayment realtime gateway. See
2310 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2311 for supported processors.
2317 $self->realtime_bop( 'CC', @_ );
2322 Attempts to pay this invoice with an electronic check (ACH) payment via a
2323 Business::OnlinePayment realtime gateway. See
2324 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2325 for supported processors.
2331 $self->realtime_bop( 'ECHECK', @_ );
2336 Attempts to pay this invoice with phone bill (LEC) payment via a
2337 Business::OnlinePayment realtime gateway. See
2338 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2339 for supported processors.
2345 $self->realtime_bop( 'LEC', @_ );
2349 my( $self, $method ) = (shift,shift);
2350 my $conf = $self->conf;
2353 my $cust_main = $self->cust_main;
2354 my $balance = $cust_main->balance;
2355 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2356 $amount = sprintf("%.2f", $amount);
2357 return "not run (balance $balance)" unless $amount > 0;
2359 my $description = 'Internet Services';
2360 if ( $conf->exists('business-onlinepayment-description') ) {
2361 my $dtempl = $conf->config('business-onlinepayment-description');
2363 my $agent_obj = $cust_main->agent
2364 or die "can't retreive agent for $cust_main (agentnum ".
2365 $cust_main->agentnum. ")";
2366 my $agent = $agent_obj->agent;
2367 my $pkgs = join(', ',
2368 map { $_->part_pkg->pkg }
2369 grep { $_->pkgnum } $self->cust_bill_pkg
2371 $description = eval qq("$dtempl");
2374 $cust_main->realtime_bop($method, $amount,
2375 'description' => $description,
2376 'invnum' => $self->invnum,
2377 #this didn't do what we want, it just calls apply_payments_and_credits
2379 'apply_to_invoice' => 1,
2382 #this changes application behavior: auto payments
2383 #triggered against a specific invoice are now applied
2384 #to that invoice instead of oldest open.
2390 =item batch_card OPTION => VALUE...
2392 Adds a payment for this invoice to the pending credit card batch (see
2393 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2394 runs the payment using a realtime gateway.
2399 my ($self, %options) = @_;
2400 my $cust_main = $self->cust_main;
2402 $options{invnum} = $self->invnum;
2404 $cust_main->batch_card(%options);
2407 sub _agent_template {
2409 $self->cust_main->agent_template;
2412 sub _agent_invoice_from {
2414 $self->cust_main->agent_invoice_from;
2417 =item invoice_barcode DIR_OR_FALSE
2419 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2420 it is taken as the temp directory where the PNG file will be generated and the
2421 PNG file name is returned. Otherwise, the PNG image itself is returned.
2425 sub invoice_barcode {
2426 my ($self, $dir) = (shift,shift);
2428 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2429 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2430 my $gd = $gdbar->plot(Height => 30);
2433 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2437 ) or die "can't open temp file: $!\n";
2438 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2439 my $png_file = $bh->filename;
2446 =item invnum_date_pretty
2448 Returns a string with the invoice number and date, for example:
2449 "Invoice #54 (3/20/2008)"
2453 sub invnum_date_pretty {
2455 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2458 #sub _items_extra_usage_sections {
2460 # my $escape = shift;
2462 # my %sections = ();
2464 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2465 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2467 # next unless $cust_bill_pkg->pkgnum > 0;
2469 # foreach my $section ( keys %usage_class ) {
2471 # my $usage = $cust_bill_pkg->usage($section);
2473 # next unless $usage && $usage > 0;
2475 # $sections{$section} ||= 0;
2476 # $sections{$section} += $usage;
2482 # map { { 'description' => &{$escape}($_),
2483 # 'subtotal' => $sections{$_},
2484 # 'summarized' => '',
2485 # 'tax_section' => '',
2488 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2492 sub _items_extra_usage_sections {
2494 my $conf = $self->conf;
2502 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2504 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2505 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2506 next unless $cust_bill_pkg->pkgnum > 0;
2508 foreach my $classnum ( keys %usage_class ) {
2509 my $section = $usage_class{$classnum}->classname;
2510 $classnums{$section} = $classnum;
2512 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2513 my $amount = $detail->amount;
2514 next unless $amount && $amount > 0;
2516 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2517 $sections{$section}{amount} += $amount; #subtotal
2518 $sections{$section}{calls}++;
2519 $sections{$section}{duration} += $detail->duration;
2521 my $desc = $detail->regionname;
2522 my $description = $desc;
2523 $description = substr($desc, 0, $maxlength). '...'
2524 if $format eq 'latex' && length($desc) > $maxlength;
2526 $lines{$section}{$desc} ||= {
2527 description => &{$escape}($description),
2528 #pkgpart => $part_pkg->pkgpart,
2529 pkgnum => $cust_bill_pkg->pkgnum,
2534 #unit_amount => $cust_bill_pkg->unitrecur,
2535 quantity => $cust_bill_pkg->quantity,
2536 product_code => 'N/A',
2537 ext_description => [],
2540 $lines{$section}{$desc}{amount} += $amount;
2541 $lines{$section}{$desc}{calls}++;
2542 $lines{$section}{$desc}{duration} += $detail->duration;
2548 my %sectionmap = ();
2549 foreach (keys %sections) {
2550 my $usage_class = $usage_class{$classnums{$_}};
2551 $sectionmap{$_} = { 'description' => &{$escape}($_),
2552 'amount' => $sections{$_}{amount}, #subtotal
2553 'calls' => $sections{$_}{calls},
2554 'duration' => $sections{$_}{duration},
2556 'tax_section' => '',
2557 'sort_weight' => $usage_class->weight,
2558 ( $usage_class->format
2559 ? ( map { $_ => $usage_class->$_($format) }
2560 qw( description_generator header_generator total_generator total_line_generator )
2567 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2571 foreach my $section ( keys %lines ) {
2572 foreach my $line ( keys %{$lines{$section}} ) {
2573 my $l = $lines{$section}{$line};
2574 $l->{section} = $sectionmap{$section};
2575 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2576 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2581 return(\@sections, \@lines);
2587 my $end = $self->_date;
2589 # start at date of previous invoice + 1 second or 0 if no previous invoice
2590 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2591 $start = 0 if !$start;
2594 my $cust_main = $self->cust_main;
2595 my @pkgs = $cust_main->all_pkgs;
2596 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2599 foreach my $pkg ( @pkgs ) {
2600 my @h_cust_svc = $pkg->h_cust_svc($end);
2601 foreach my $h_cust_svc ( @h_cust_svc ) {
2602 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2603 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2605 my $inserted = $h_cust_svc->date_inserted;
2606 my $deleted = $h_cust_svc->date_deleted;
2607 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2609 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2611 # DID either activated or ported in; cannot be both for same DID simultaneously
2612 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2613 && (!$phone_inserted->lnp_status
2614 || $phone_inserted->lnp_status eq ''
2615 || $phone_inserted->lnp_status eq 'native')) {
2618 else { # this one not so clean, should probably move to (h_)svc_phone
2619 my $phone_portedin = qsearchs( 'h_svc_phone',
2620 { 'svcnum' => $h_cust_svc->svcnum,
2621 'lnp_status' => 'portedin' },
2622 FS::h_svc_phone->sql_h_searchs($end),
2624 $num_portedin++ if $phone_portedin;
2627 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2628 if($deleted >= $start && $deleted <= $end && $phone_deleted
2629 && (!$phone_deleted->lnp_status
2630 || $phone_deleted->lnp_status ne 'portingout')) {
2633 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2634 && $phone_deleted->lnp_status
2635 && $phone_deleted->lnp_status eq 'portingout') {
2639 # increment usage minutes
2640 if ( $phone_inserted ) {
2641 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2642 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2645 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2648 # don't look at this service again
2649 push @seen, $h_cust_svc->svcnum;
2653 $minutes = sprintf("%d", $minutes);
2654 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2655 . "$num_deactivated Ported-Out: $num_portedout ",
2656 "Total Minutes: $minutes");
2659 sub _items_accountcode_cdr {
2664 my $section = { 'amount' => 0,
2667 'sort_weight' => '',
2669 'description' => 'Usage by Account Code',
2675 my %accountcodes = ();
2677 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2678 next unless $cust_bill_pkg->pkgnum > 0;
2680 my @header = $cust_bill_pkg->details_header;
2681 next unless scalar(@header);
2682 $section->{'header'} = join(',',@header);
2684 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2686 $section->{'header'} = $detail->formatted('format' => $format)
2687 if($detail->detail eq $section->{'header'});
2689 my $accountcode = $detail->accountcode;
2690 next unless $accountcode;
2692 my $amount = $detail->amount;
2693 next unless $amount && $amount > 0;
2695 $accountcodes{$accountcode} ||= {
2696 description => $accountcode,
2703 product_code => 'N/A',
2704 section => $section,
2705 ext_description => [ $section->{'header'} ],
2709 $section->{'amount'} += $amount;
2710 $accountcodes{$accountcode}{'amount'} += $amount;
2711 $accountcodes{$accountcode}{calls}++;
2712 $accountcodes{$accountcode}{duration} += $detail->duration;
2713 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2717 foreach my $l ( values %accountcodes ) {
2718 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2719 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2720 foreach my $sorted_detail ( @sorted_detail ) {
2721 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2723 delete $l->{detail_temp};
2727 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2729 return ($section,\@sorted_lines);
2732 sub _items_svc_phone_sections {
2734 my $conf = $self->conf;
2742 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2744 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2745 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2747 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2748 next unless $cust_bill_pkg->pkgnum > 0;
2750 my @header = $cust_bill_pkg->details_header;
2751 next unless scalar(@header);
2753 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2755 my $phonenum = $detail->phonenum;
2756 next unless $phonenum;
2758 my $amount = $detail->amount;
2759 next unless $amount && $amount > 0;
2761 $sections{$phonenum} ||= { 'amount' => 0,
2764 'sort_weight' => -1,
2765 'phonenum' => $phonenum,
2767 $sections{$phonenum}{amount} += $amount; #subtotal
2768 $sections{$phonenum}{calls}++;
2769 $sections{$phonenum}{duration} += $detail->duration;
2771 my $desc = $detail->regionname;
2772 my $description = $desc;
2773 $description = substr($desc, 0, $maxlength). '...'
2774 if $format eq 'latex' && length($desc) > $maxlength;
2776 $lines{$phonenum}{$desc} ||= {
2777 description => &{$escape}($description),
2778 #pkgpart => $part_pkg->pkgpart,
2786 product_code => 'N/A',
2787 ext_description => [],
2790 $lines{$phonenum}{$desc}{amount} += $amount;
2791 $lines{$phonenum}{$desc}{calls}++;
2792 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2794 my $line = $usage_class{$detail->classnum}->classname;
2795 $sections{"$phonenum $line"} ||=
2799 'sort_weight' => $usage_class{$detail->classnum}->weight,
2800 'phonenum' => $phonenum,
2801 'header' => [ @header ],
2803 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2804 $sections{"$phonenum $line"}{calls}++;
2805 $sections{"$phonenum $line"}{duration} += $detail->duration;
2807 $lines{"$phonenum $line"}{$desc} ||= {
2808 description => &{$escape}($description),
2809 #pkgpart => $part_pkg->pkgpart,
2817 product_code => 'N/A',
2818 ext_description => [],
2821 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2822 $lines{"$phonenum $line"}{$desc}{calls}++;
2823 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2824 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2825 $detail->formatted('format' => $format);
2830 my %sectionmap = ();
2831 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2832 foreach ( keys %sections ) {
2833 my @header = @{ $sections{$_}{header} || [] };
2835 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2836 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2837 my $usage_class = $summary ? $simple : $usage_simple;
2838 my $ending = $summary ? ' usage charges' : '';
2841 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2843 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2844 'amount' => $sections{$_}{amount}, #subtotal
2845 'calls' => $sections{$_}{calls},
2846 'duration' => $sections{$_}{duration},
2848 'tax_section' => '',
2849 'phonenum' => $sections{$_}{phonenum},
2850 'sort_weight' => $sections{$_}{sort_weight},
2851 'post_total' => $summary, #inspire pagebreak
2853 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2854 qw( description_generator
2857 total_line_generator
2864 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2865 $a->{sort_weight} <=> $b->{sort_weight}
2870 foreach my $section ( keys %lines ) {
2871 foreach my $line ( keys %{$lines{$section}} ) {
2872 my $l = $lines{$section}{$line};
2873 $l->{section} = $sectionmap{$section};
2874 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2875 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2880 if($conf->exists('phone_usage_class_summary')) {
2881 # this only works with Latex
2885 # after this, we'll have only two sections per DID:
2886 # Calls Summary and Calls Detail
2887 foreach my $section ( @sections ) {
2888 if($section->{'post_total'}) {
2889 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2890 $section->{'total_line_generator'} = sub { '' };
2891 $section->{'total_generator'} = sub { '' };
2892 $section->{'header_generator'} = sub { '' };
2893 $section->{'description_generator'} = '';
2894 push @newsections, $section;
2895 my %calls_detail = %$section;
2896 $calls_detail{'post_total'} = '';
2897 $calls_detail{'sort_weight'} = '';
2898 $calls_detail{'description_generator'} = sub { '' };
2899 $calls_detail{'header_generator'} = sub {
2900 return ' & Date/Time & Called Number & Duration & Price'
2901 if $format eq 'latex';
2904 $calls_detail{'description'} = 'Calls Detail: '
2905 . $section->{'phonenum'};
2906 push @newsections, \%calls_detail;
2910 # after this, each usage class is collapsed/summarized into a single
2911 # line under the Calls Summary section
2912 foreach my $newsection ( @newsections ) {
2913 if($newsection->{'post_total'}) { # this means Calls Summary
2914 foreach my $section ( @sections ) {
2915 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2916 && !$section->{'post_total'});
2917 my $newdesc = $section->{'description'};
2918 my $tn = $section->{'phonenum'};
2919 $newdesc =~ s/$tn//g;
2920 my $line = { ext_description => [],
2924 calls => $section->{'calls'},
2925 section => $newsection,
2926 duration => $section->{'duration'},
2927 description => $newdesc,
2928 amount => sprintf("%.2f",$section->{'amount'}),
2929 product_code => 'N/A',
2931 push @newlines, $line;
2936 # after this, Calls Details is populated with all CDRs
2937 foreach my $newsection ( @newsections ) {
2938 if(!$newsection->{'post_total'}) { # this means Calls Details
2939 foreach my $line ( @lines ) {
2940 next unless (scalar(@{$line->{'ext_description'}}) &&
2941 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2943 my @extdesc = @{$line->{'ext_description'}};
2945 foreach my $extdesc ( @extdesc ) {
2946 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2947 push @newextdesc, $extdesc;
2949 $line->{'ext_description'} = \@newextdesc;
2950 $line->{'section'} = $newsection;
2951 push @newlines, $line;
2956 return(\@newsections, \@newlines);
2959 return(\@sections, \@lines);
2963 sub _items_previous {
2965 my $conf = $self->conf;
2966 my $cust_main = $self->cust_main;
2967 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2969 foreach ( @pr_cust_bill ) {
2970 my $date = $conf->exists('invoice_show_prior_due_date')
2971 ? 'due '. $_->due_date2str('short')
2972 : $self->time2str_local('short', $_->_date);
2974 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2975 #'pkgpart' => 'N/A',
2977 'amount' => sprintf("%.2f", $_->owed),
2983 # 'description' => 'Previous Balance',
2984 # #'pkgpart' => 'N/A',
2985 # 'pkgnum' => 'N/A',
2986 # 'amount' => sprintf("%10.2f", $pr_total ),
2987 # 'ext_description' => [ map {
2988 # "Invoice ". $_->invnum.
2989 # " (". time2str("%x",$_->_date). ") ".
2990 # sprintf("%10.2f", $_->owed)
2991 # } @pr_cust_bill ],
2996 sub _items_credits {
2997 my( $self, %opt ) = @_;
2998 my $trim_len = $opt{'trim_len'} || 60;
3003 if ( $self->conf->exists('previous_balance-payments_since') ) {
3004 if ( $opt{'template'} eq 'statement' ) {
3005 # then the current bill is a "statement" (i.e. an invoice sent as
3006 # a payment receipt)
3007 # and in that case we want to see payments on or after THIS invoice
3008 @objects = qsearch('cust_credit', {
3009 'custnum' => $self->custnum,
3010 '_date' => {op => '>=', value => $self->_date},
3014 $date = $self->previous_bill->_date if $self->previous_bill;
3015 @objects = qsearch('cust_credit', {
3016 'custnum' => $self->custnum,
3017 '_date' => {op => '>=', value => $date},
3021 @objects = $self->cust_credited;
3024 foreach my $obj ( @objects ) {
3025 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3027 my $reason = substr($cust_credit->reason, 0, $trim_len);
3028 $reason .= '...' if length($reason) < length($cust_credit->reason);
3029 $reason = " ($reason) " if $reason;
3032 #'description' => 'Credit ref\#'. $_->crednum.
3033 # " (". time2str("%x",$_->cust_credit->_date) .")".
3035 'description' => $self->mt('Credit applied').' '.
3036 $self->time2str_local('short', $obj->_date). $reason,
3037 'amount' => sprintf("%.2f",$obj->amount),
3045 sub _items_payments {
3050 my $detailed = $self->conf->exists('invoice_payment_details');
3052 if ( $self->conf->exists('previous_balance-payments_since') ) {
3053 # then show payments dated on/after the previous bill...
3054 if ( $opt{'template'} eq 'statement' ) {
3055 # then the current bill is a "statement" (i.e. an invoice sent as
3056 # a payment receipt)
3057 # and in that case we want to see payments on or after THIS invoice
3058 @objects = qsearch('cust_pay', {
3059 'custnum' => $self->custnum,
3060 '_date' => {op => '>=', value => $self->_date},
3063 # the normal case: payments on or after the previous invoice
3065 $date = $self->previous_bill->_date if $self->previous_bill;
3066 @objects = qsearch('cust_pay', {
3067 'custnum' => $self->custnum,
3068 '_date' => {op => '>=', value => $date},
3070 # and before the current bill...
3071 @objects = grep { $_->_date < $self->_date } @objects;
3074 @objects = $self->cust_bill_pay;
3077 foreach my $obj (@objects) {
3078 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3079 my $desc = $self->mt('Payment received').' '.
3080 $self->time2str_local('short', $cust_pay->_date );
3081 $desc .= $self->mt(' via ') .
3082 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3086 'description' => $desc,
3087 'amount' => sprintf("%.2f", $obj->amount )
3095 =item call_details [ OPTION => VALUE ... ]
3097 Returns an array of CSV strings representing the call details for this invoice
3098 The only option available is the boolean prepend_billed_number
3103 my ($self, %opt) = @_;
3105 my $format_function = sub { shift };
3107 if ($opt{prepend_billed_number}) {
3108 $format_function = sub {
3112 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3117 my @details = map { $_->details( 'format_function' => $format_function,
3118 'escape_function' => sub{ return() },
3122 $self->cust_bill_pkg;
3123 my $header = $details[0];
3124 ( $header, grep { $_ ne $header } @details );
3134 =item process_reprint
3138 sub process_reprint {
3139 process_re_X('print', @_);
3142 =item process_reemail
3146 sub process_reemail {
3147 process_re_X('email', @_);
3155 process_re_X('fax', @_);
3163 process_re_X('ftp', @_);
3170 sub process_respool {
3171 process_re_X('spool', @_);
3174 use Storable qw(thaw);
3178 my( $method, $job ) = ( shift, shift );
3179 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3181 my $param = thaw(decode_base64(shift));
3182 warn Dumper($param) if $DEBUG;
3193 # spool_invoice ftp_invoice fax_invoice print_invoice
3194 my($method, $job, %param ) = @_;
3196 warn "re_X $method for job $job with param:\n".
3197 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3200 #some false laziness w/search/cust_bill.html
3202 my $orderby = 'ORDER BY cust_bill._date';
3204 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3206 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3208 my @cust_bill = qsearch( {
3209 #'select' => "cust_bill.*",
3210 'table' => 'cust_bill',
3211 'addl_from' => $addl_from,
3213 'extra_sql' => $extra_sql,
3214 'order_by' => $orderby,
3218 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3220 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3223 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3224 foreach my $cust_bill ( @cust_bill ) {
3225 $cust_bill->$method();
3227 if ( $job ) { #progressbar foo
3229 if ( time - $min_sec > $last ) {
3230 my $error = $job->update_statustext(
3231 int( 100 * $num / scalar(@cust_bill) )
3233 die $error if $error;
3244 =head1 CLASS METHODS
3250 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3255 my ($class, $start, $end) = @_;
3257 $class->paid_sql($start, $end). ' - '.
3258 $class->credited_sql($start, $end);
3263 Returns an SQL fragment to retreive the net amount (charged minus credited).
3268 my ($class, $start, $end) = @_;
3269 'charged - '. $class->credited_sql($start, $end);
3274 Returns an SQL fragment to retreive the amount paid against this invoice.
3279 my ($class, $start, $end) = @_;
3280 $start &&= "AND cust_bill_pay._date <= $start";
3281 $end &&= "AND cust_bill_pay._date > $end";
3282 $start = '' unless defined($start);
3283 $end = '' unless defined($end);
3284 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3285 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3290 Returns an SQL fragment to retreive the amount credited against this invoice.
3295 my ($class, $start, $end) = @_;
3296 $start &&= "AND cust_credit_bill._date <= $start";
3297 $end &&= "AND cust_credit_bill._date > $end";
3298 $start = '' unless defined($start);
3299 $end = '' unless defined($end);
3300 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3301 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3306 Returns an SQL fragment to retrieve the due date of an invoice.
3307 Currently only supported on PostgreSQL.
3312 my $conf = new FS::Conf;
3316 cust_bill.invoice_terms,
3317 cust_main.invoice_terms,
3318 \''.($conf->config('invoice_default_terms') || '').'\'
3319 ), E\'Net (\\\\d+)\'
3321 ) * 86400 + cust_bill._date'
3324 =item search_sql_where HASHREF
3326 Class method which returns an SQL WHERE fragment to search for parameters
3327 specified in HASHREF. Valid parameters are
3333 List reference of start date, end date, as UNIX timestamps.
3343 List reference of charged limits (exclusive).
3347 List reference of charged limits (exclusive).
3351 flag, return open invoices only
3355 flag, return net invoices only
3359 =item newest_percust
3363 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3367 sub search_sql_where {
3368 my($class, $param) = @_;
3370 warn "$me search_sql_where called with params: \n".
3371 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3377 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3378 push @search, "cust_main.agentnum = $1";
3382 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3383 push @search, "cust_main.refnum = $1";
3387 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3388 push @search, "cust_bill.custnum = $1";
3391 #customer classnum (false laziness w/ cust_main/Search.pm)
3392 if ( $param->{'cust_classnum'} ) {
3394 my @classnum = ref( $param->{'cust_classnum'} )
3395 ? @{ $param->{'cust_classnum'} }
3396 : ( $param->{'cust_classnum'} );
3398 @classnum = grep /^(\d*)$/, @classnum;
3401 push @search, '( '. join(' OR ', map {
3402 $_ ? "cust_main.classnum = $_"
3403 : "cust_main.classnum IS NULL"
3413 if ( $param->{_date} ) {
3414 my($beginning, $ending) = @{$param->{_date}};
3416 push @search, "cust_bill._date >= $beginning",
3417 "cust_bill._date < $ending";
3421 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3422 push @search, "cust_bill.invnum >= $1";
3424 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3425 push @search, "cust_bill.invnum <= $1";
3429 if ( $param->{charged} ) {
3430 my @charged = ref($param->{charged})
3431 ? @{ $param->{charged} }
3432 : ($param->{charged});
3434 push @search, map { s/^charged/cust_bill.charged/; $_; }
3438 my $owed_sql = FS::cust_bill->owed_sql;
3441 if ( $param->{owed} ) {
3442 my @owed = ref($param->{owed})
3443 ? @{ $param->{owed} }
3445 push @search, map { s/^owed/$owed_sql/; $_; }
3450 push @search, "0 != $owed_sql"
3451 if $param->{'open'};
3452 push @search, '0 != '. FS::cust_bill->net_sql
3456 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3457 if $param->{'days'};
3460 if ( $param->{'newest_percust'} ) {
3462 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3463 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3465 my @newest_where = map { my $x = $_;
3466 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3469 grep ! /^cust_main./, @search;
3470 my $newest_where = scalar(@newest_where)
3471 ? ' AND '. join(' AND ', @newest_where)
3475 push @search, "cust_bill._date = (
3476 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3477 WHERE newest_cust_bill.custnum = cust_bill.custnum
3483 #promised_date - also has an option to accept nulls
3484 if ( $param->{promised_date} ) {
3485 my($beginning, $ending, $null) = @{$param->{promised_date}};
3487 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3488 "cust_bill.promised_date < $ending )" .
3489 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3492 #agent virtualization
3493 my $curuser = $FS::CurrentUser::CurrentUser;
3494 if ( $curuser->username eq 'fs_queue'
3495 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3497 my $newuser = qsearchs('access_user', {
3498 'username' => $username,
3502 $curuser = $newuser;
3504 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3507 push @search, $curuser->agentnums_sql;
3509 join(' AND ', @search );
3521 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3522 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base