2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $DEBUG $me );
7 use Fcntl qw(:flock); #for spool_csv
9 use List::Util qw(min max sum);
13 use Storable qw( freeze thaw );
15 use FS::UID qw( datasrc );
16 use FS::Misc qw( send_email send_fax do_print );
17 use FS::Record qw( qsearch qsearchs dbh );
19 use FS::cust_statement;
20 use FS::cust_bill_pkg;
21 use FS::cust_bill_pkg_display;
22 use FS::cust_bill_pkg_detail;
26 use FS::cust_credit_bill;
28 use FS::cust_pay_batch;
29 use FS::cust_bill_event;
32 use FS::cust_bill_pay;
33 use FS::cust_bill_pay_batch;
34 use FS::part_bill_event;
37 use FS::cust_bill_batch;
38 use FS::cust_bill_pay_pkg;
39 use FS::cust_credit_bill_pkg;
40 use FS::discount_plan;
41 use FS::cust_bill_void;
45 $me = '[FS::cust_bill]';
47 #ask FS::UID to run this stuff for us later
48 FS::UID->install_callback( sub {
49 my $conf = new FS::Conf; #global
54 FS::cust_bill - Object methods for cust_bill records
60 $record = new FS::cust_bill \%hash;
61 $record = new FS::cust_bill { 'column' => 'value' };
63 $error = $record->insert;
65 $error = $new_record->replace($old_record);
67 $error = $record->delete;
69 $error = $record->check;
71 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
73 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
75 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
77 @cust_pay_objects = $cust_bill->cust_pay;
79 $tax_amount = $record->tax;
81 @lines = $cust_bill->print_text;
82 @lines = $cust_bill->print_text('time' => $time);
86 An FS::cust_bill object represents an invoice; a declaration that a customer
87 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
88 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
89 following fields are currently supported:
95 =item invnum - primary key (assigned automatically for new invoices)
97 =item custnum - customer (see L<FS::cust_main>)
99 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
100 L<Time::Local> and L<Date::Parse> for conversion functions.
102 =item charged - amount of this invoice
104 =item invoice_terms - optional terms override for this specific invoice
108 Customer info at invoice generation time
112 =item billing_balance - the customer's balance at the time the invoice was
113 generated (not including charges on this invoice)
115 =item previous_balance - the billing_balance of this customer's previous
116 invoice plus the charges on that invoice
124 =item printed - deprecated
132 =item closed - books closed flag, empty or `Y'
134 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
136 =item agent_invid - legacy invoice number
138 =item promised_date - customer promised payment date, for collection
148 Creates a new invoice. To add the invoice to the database, see L<"insert">.
149 Invoices are normally created by calling the bill method of a customer object
150 (see L<FS::cust_main>).
154 sub table { 'cust_bill'; }
156 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
157 # (except email_subject and invnum_date_pretty)
160 $self->conf->config('notice_name') || 'Invoice'
163 sub cust_linked { $_[0]->cust_main_custnum; }
164 sub cust_unlinked_msg {
166 "WARNING: can't find cust_main.custnum ". $self->custnum.
167 ' (cust_bill.invnum '. $self->invnum. ')';
172 Adds this invoice to the database ("Posts" the invoice). If there is an error,
173 returns the error, otherwise returns false.
179 warn "$me insert called\n" if $DEBUG;
181 local $SIG{HUP} = 'IGNORE';
182 local $SIG{INT} = 'IGNORE';
183 local $SIG{QUIT} = 'IGNORE';
184 local $SIG{TERM} = 'IGNORE';
185 local $SIG{TSTP} = 'IGNORE';
186 local $SIG{PIPE} = 'IGNORE';
188 my $oldAutoCommit = $FS::UID::AutoCommit;
189 local $FS::UID::AutoCommit = 0;
192 my $error = $self->SUPER::insert;
194 $dbh->rollback if $oldAutoCommit;
198 if ( $self->get('cust_bill_pkg') ) {
199 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
200 $cust_bill_pkg->invnum($self->invnum);
201 my $error = $cust_bill_pkg->insert;
203 $dbh->rollback if $oldAutoCommit;
204 return "can't create invoice line item: $error";
209 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
216 Voids this invoice: deletes the invoice and adds a record of the voided invoice
217 to the FS::cust_bill_void table (and related tables starting from
218 FS::cust_bill_pkg_void).
224 my $reason = scalar(@_) ? shift : '';
226 local $SIG{HUP} = 'IGNORE';
227 local $SIG{INT} = 'IGNORE';
228 local $SIG{QUIT} = 'IGNORE';
229 local $SIG{TERM} = 'IGNORE';
230 local $SIG{TSTP} = 'IGNORE';
231 local $SIG{PIPE} = 'IGNORE';
233 my $oldAutoCommit = $FS::UID::AutoCommit;
234 local $FS::UID::AutoCommit = 0;
237 my $cust_bill_void = new FS::cust_bill_void ( {
238 map { $_ => $self->get($_) } $self->fields
240 $cust_bill_void->reason($reason);
241 my $error = $cust_bill_void->insert;
243 $dbh->rollback if $oldAutoCommit;
247 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
248 my $error = $cust_bill_pkg->void($reason);
250 $dbh->rollback if $oldAutoCommit;
255 $error = $self->delete;
257 $dbh->rollback if $oldAutoCommit;
261 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
269 This method now works but you probably shouldn't use it. Instead, apply a
270 credit against the invoice, or use the new void method.
272 Using this method to delete invoices outright is really, really bad. There
273 would be no record you ever posted this invoice, and there are no check to
274 make sure charged = 0 or that there are no associated cust_bill_pkg records.
276 Really, don't use it.
282 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
284 local $SIG{HUP} = 'IGNORE';
285 local $SIG{INT} = 'IGNORE';
286 local $SIG{QUIT} = 'IGNORE';
287 local $SIG{TERM} = 'IGNORE';
288 local $SIG{TSTP} = 'IGNORE';
289 local $SIG{PIPE} = 'IGNORE';
291 my $oldAutoCommit = $FS::UID::AutoCommit;
292 local $FS::UID::AutoCommit = 0;
295 foreach my $table (qw(
306 foreach my $linked ( $self->$table() ) {
307 my $error = $linked->delete;
309 $dbh->rollback if $oldAutoCommit;
316 my $error = $self->SUPER::delete(@_);
318 $dbh->rollback if $oldAutoCommit;
322 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
328 =item replace [ OLD_RECORD ]
330 You can, but probably shouldn't modify invoices...
332 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
333 supplied, replaces this record. If there is an error, returns the error,
334 otherwise returns false.
338 #replace can be inherited from Record.pm
340 # replace_check is now the preferred way to #implement replace data checks
341 # (so $object->replace() works without an argument)
344 my( $new, $old ) = ( shift, shift );
345 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
346 #return "Can't change _date!" unless $old->_date eq $new->_date;
347 return "Can't change _date" unless $old->_date == $new->_date;
348 return "Can't change charged" unless $old->charged == $new->charged
349 || $old->charged == 0
350 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
356 =item add_cc_surcharge
362 sub add_cc_surcharge {
363 my ($self, $pkgnum, $amount) = (shift, shift, shift);
366 my $cust_bill_pkg = new FS::cust_bill_pkg({
367 'invnum' => $self->invnum,
371 $error = $cust_bill_pkg->insert;
372 return $error if $error;
374 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
375 $self->charged($self->charged+$amount);
376 $error = $self->replace;
377 return $error if $error;
379 $self->apply_payments_and_credits;
385 Checks all fields to make sure this is a valid invoice. If there is an error,
386 returns the error, otherwise returns false. Called by the insert and replace
395 $self->ut_numbern('invnum')
396 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
397 || $self->ut_numbern('_date')
398 || $self->ut_money('charged')
399 || $self->ut_numbern('printed')
400 || $self->ut_enum('closed', [ '', 'Y' ])
401 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
402 || $self->ut_numbern('agent_invid') #varchar?
404 return $error if $error;
406 $self->_date(time) unless $self->_date;
408 $self->printed(0) if $self->printed eq '';
415 Returns the displayed invoice number for this invoice: agent_invid if
416 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
422 my $conf = $self->conf;
423 if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
424 return $self->agent_invid;
426 return $self->invnum;
432 Returns the customer's last invoice before this one.
438 if ( !$self->get('previous_bill') ) {
439 $self->set('previous_bill', qsearchs({
440 'table' => 'cust_bill',
441 'hashref' => { 'custnum' => $self->custnum,
442 '_date' => { op=>'<', value=>$self->_date } },
443 'order_by' => 'ORDER BY _date DESC LIMIT 1',
446 $self->get('previous_bill');
451 Returns a list consisting of the total previous balance for this customer,
452 followed by the previous outstanding invoices (as FS::cust_bill objects also).
459 my @cust_bill = sort { $a->_date <=> $b->_date }
460 grep { $_->owed != 0 }
461 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
462 #'_date' => { op=>'<', value=>$self->_date },
463 'invnum' => { op=>'<', value=>$self->invnum },
466 foreach ( @cust_bill ) { $total += $_->owed; }
470 =item enable_previous
472 Whether to show the 'Previous Charges' section when printing this invoice.
473 The negation of the 'disable_previous_balance' config setting.
477 sub enable_previous {
479 my $agentnum = $self->cust_main->agentnum;
480 !$self->conf->exists('disable_previous_balance', $agentnum);
485 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
492 { 'table' => 'cust_bill_pkg',
493 'hashref' => { 'invnum' => $self->invnum },
494 'order_by' => 'ORDER BY billpkgnum',
499 =item cust_bill_pkg_pkgnum PKGNUM
501 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
506 sub cust_bill_pkg_pkgnum {
507 my( $self, $pkgnum ) = @_;
509 { 'table' => 'cust_bill_pkg',
510 'hashref' => { 'invnum' => $self->invnum,
513 'order_by' => 'ORDER BY billpkgnum',
520 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
527 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
528 $self->cust_bill_pkg;
530 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
535 Returns true if any of the packages (or their definitions) corresponding to the
536 line items for this invoice have the no_auto flag set.
542 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
545 =item open_cust_bill_pkg
547 Returns the open line items for this invoice.
549 Note that cust_bill_pkg with both setup and recur fees are returned as two
550 separate line items, each with only one fee.
554 # modeled after cust_main::open_cust_bill
555 sub open_cust_bill_pkg {
558 # grep { $_->owed > 0 } $self->cust_bill_pkg
560 my %other = ( 'recur' => 'setup',
561 'setup' => 'recur', );
563 foreach my $field ( qw( recur setup )) {
564 push @open, map { $_->set( $other{$field}, 0 ); $_; }
565 grep { $_->owed($field) > 0 }
566 $self->cust_bill_pkg;
572 =item cust_bill_event
574 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
578 sub cust_bill_event {
580 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
583 =item num_cust_bill_event
585 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
589 sub num_cust_bill_event {
592 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
593 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
594 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
595 $sth->fetchrow_arrayref->[0];
600 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
604 #false laziness w/cust_pkg.pm
608 'table' => 'cust_event',
609 'addl_from' => 'JOIN part_event USING ( eventpart )',
610 'hashref' => { 'tablenum' => $self->invnum },
611 'extra_sql' => " AND eventtable = 'cust_bill' ",
617 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
621 #false laziness w/cust_pkg.pm
625 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
626 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
627 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
628 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
629 $sth->fetchrow_arrayref->[0];
634 Returns the customer (see L<FS::cust_main>) for this invoice.
640 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
643 =item cust_suspend_if_balance_over AMOUNT
645 Suspends the customer associated with this invoice if the total amount owed on
646 this invoice and all older invoices is greater than the specified amount.
648 Returns a list: an empty list on success or a list of errors.
652 sub cust_suspend_if_balance_over {
653 my( $self, $amount ) = ( shift, shift );
654 my $cust_main = $self->cust_main;
655 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
658 $cust_main->suspend(@_);
664 Depreciated. See the cust_credited method.
666 #Returns a list consisting of the total previous credited (see
667 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
668 #outstanding credits (FS::cust_credit objects).
674 croak "FS::cust_bill->cust_credit depreciated; see ".
675 "FS::cust_bill->cust_credit_bill";
678 #my @cust_credit = sort { $a->_date <=> $b->_date }
679 # grep { $_->credited != 0 && $_->_date < $self->_date }
680 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
682 #foreach (@cust_credit) { $total += $_->credited; }
683 #$total, @cust_credit;
688 Depreciated. See the cust_bill_pay method.
690 #Returns all payments (see L<FS::cust_pay>) for this invoice.
696 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
698 #sort { $a->_date <=> $b->_date }
699 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
705 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
708 sub cust_bill_pay_batch {
710 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
715 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
721 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
722 sort { $a->_date <=> $b->_date }
723 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
728 =item cust_credit_bill
730 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
736 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
737 sort { $a->_date <=> $b->_date }
738 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
742 sub cust_credit_bill {
743 shift->cust_credited(@_);
746 #=item cust_bill_pay_pkgnum PKGNUM
748 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
749 #with matching pkgnum.
753 #sub cust_bill_pay_pkgnum {
754 # my( $self, $pkgnum ) = @_;
755 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
756 # sort { $a->_date <=> $b->_date }
757 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
758 # 'pkgnum' => $pkgnum,
763 =item cust_bill_pay_pkg PKGNUM
765 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
766 applied against the matching pkgnum.
770 sub cust_bill_pay_pkg {
771 my( $self, $pkgnum ) = @_;
774 'select' => 'cust_bill_pay_pkg.*',
775 'table' => 'cust_bill_pay_pkg',
776 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
777 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
778 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
779 " AND cust_bill_pkg.pkgnum = $pkgnum",
784 #=item cust_credited_pkgnum PKGNUM
786 #=item cust_credit_bill_pkgnum PKGNUM
788 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
789 #with matching pkgnum.
793 #sub cust_credited_pkgnum {
794 # my( $self, $pkgnum ) = @_;
795 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
796 # sort { $a->_date <=> $b->_date }
797 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
798 # 'pkgnum' => $pkgnum,
803 #sub cust_credit_bill_pkgnum {
804 # shift->cust_credited_pkgnum(@_);
807 =item cust_credit_bill_pkg PKGNUM
809 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
810 applied against the matching pkgnum.
814 sub cust_credit_bill_pkg {
815 my( $self, $pkgnum ) = @_;
818 'select' => 'cust_credit_bill_pkg.*',
819 'table' => 'cust_credit_bill_pkg',
820 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
821 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
822 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
823 " AND cust_bill_pkg.pkgnum = $pkgnum",
828 =item cust_bill_batch
830 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
834 sub cust_bill_batch {
836 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
841 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
842 hash keyed by term length.
848 FS::discount_plan->all($self);
853 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
860 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
862 foreach (@taxlines) { $total += $_->setup; }
868 Returns the amount owed (still outstanding) on this invoice, which is charged
869 minus all payment applications (see L<FS::cust_bill_pay>) and credit
870 applications (see L<FS::cust_credit_bill>).
876 my $balance = $self->charged;
877 $balance -= $_->amount foreach ( $self->cust_bill_pay );
878 $balance -= $_->amount foreach ( $self->cust_credited );
879 $balance = sprintf( "%.2f", $balance);
880 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
885 my( $self, $pkgnum ) = @_;
887 #my $balance = $self->charged;
889 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
891 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
892 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
894 $balance = sprintf( "%.2f", $balance);
895 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
901 Returns true if this invoice should be hidden. See the
902 selfservice-hide_invoices-taxclass configuraiton setting.
908 my $conf = $self->conf;
909 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
911 my @cust_bill_pkg = $self->cust_bill_pkg;
912 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
913 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
916 =item apply_payments_and_credits [ OPTION => VALUE ... ]
918 Applies unapplied payments and credits to this invoice.
920 A hash of optional arguments may be passed. Currently "manual" is supported.
921 If true, a payment receipt is sent instead of a statement when
922 'payment_receipt_email' configuration option is set.
924 If there is an error, returns the error, otherwise returns false.
928 sub apply_payments_and_credits {
929 my( $self, %options ) = @_;
930 my $conf = $self->conf;
932 local $SIG{HUP} = 'IGNORE';
933 local $SIG{INT} = 'IGNORE';
934 local $SIG{QUIT} = 'IGNORE';
935 local $SIG{TERM} = 'IGNORE';
936 local $SIG{TSTP} = 'IGNORE';
937 local $SIG{PIPE} = 'IGNORE';
939 my $oldAutoCommit = $FS::UID::AutoCommit;
940 local $FS::UID::AutoCommit = 0;
943 $self->select_for_update; #mutex
945 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
946 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
948 if ( $conf->exists('pkg-balances') ) {
949 # limit @payments & @credits to those w/ a pkgnum grepped from $self
950 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
951 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
952 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
955 while ( $self->owed > 0 and ( @payments || @credits ) ) {
958 if ( @payments && @credits ) {
960 #decide which goes first by weight of top (unapplied) line item
962 my @open_lineitems = $self->open_cust_bill_pkg;
965 max( map { $_->part_pkg->pay_weight || 0 }
970 my $max_credit_weight =
971 max( map { $_->part_pkg->credit_weight || 0 }
977 #if both are the same... payments first? it has to be something
978 if ( $max_pay_weight >= $max_credit_weight ) {
984 } elsif ( @payments ) {
986 } elsif ( @credits ) {
989 die "guru meditation #12 and 35";
993 if ( $app eq 'pay' ) {
995 my $payment = shift @payments;
996 $unapp_amount = $payment->unapplied;
997 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
998 $app->pkgnum( $payment->pkgnum )
999 if $conf->exists('pkg-balances') && $payment->pkgnum;
1001 } elsif ( $app eq 'credit' ) {
1003 my $credit = shift @credits;
1004 $unapp_amount = $credit->credited;
1005 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1006 $app->pkgnum( $credit->pkgnum )
1007 if $conf->exists('pkg-balances') && $credit->pkgnum;
1010 die "guru meditation #12 and 35";
1014 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1015 warn "owed_pkgnum ". $app->pkgnum;
1016 $owed = $self->owed_pkgnum($app->pkgnum);
1018 $owed = $self->owed;
1020 next unless $owed > 0;
1022 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1023 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1025 $app->invnum( $self->invnum );
1027 my $error = $app->insert(%options);
1029 $dbh->rollback if $oldAutoCommit;
1030 return "Error inserting ". $app->table. " record: $error";
1032 die $error if $error;
1036 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1041 =item generate_email OPTION => VALUE ...
1049 sender address, required
1053 alternate template name, optional
1057 text attachment arrayref, optional
1061 email subject, optional
1065 notice name instead of "Invoice", optional
1069 Returns an argument list to be passed to L<FS::Misc::send_email>.
1075 sub generate_email {
1079 my $conf = $self->conf;
1081 my $me = '[FS::cust_bill::generate_email]';
1084 'from' => $args{'from'},
1085 'subject' => ($args{'subject'} || $self->email_subject),
1086 'custnum' => $self->custnum,
1087 'msgtype' => 'invoice',
1090 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1092 my $cust_main = $self->cust_main;
1094 if (ref($args{'to'}) eq 'ARRAY') {
1095 $return{'to'} = $args{'to'};
1097 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1098 $cust_main->invoicing_list
1102 if ( $conf->exists('invoice_html') ) {
1104 warn "$me creating HTML/text multipart message"
1107 $return{'nobody'} = 1;
1109 my $alternative = build MIME::Entity
1110 'Type' => 'multipart/alternative',
1111 #'Encoding' => '7bit',
1112 'Disposition' => 'inline'
1116 if ( $conf->exists('invoice_email_pdf')
1117 and scalar($conf->config('invoice_email_pdf_note')) ) {
1119 warn "$me using 'invoice_email_pdf_note' in multipart message"
1121 $data = [ map { $_ . "\n" }
1122 $conf->config('invoice_email_pdf_note')
1127 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1129 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1130 $data = $args{'print_text'};
1132 $data = [ $self->print_text(\%args) ];
1137 $alternative->attach(
1138 'Type' => 'text/plain',
1139 'Encoding' => 'quoted-printable',
1140 #'Encoding' => '7bit',
1142 'Disposition' => 'inline',
1149 if ( $conf->exists('invoice_email_pdf')
1150 and scalar($conf->config('invoice_email_pdf_note')) ) {
1152 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1156 $args{'from'} =~ /\@([\w\.\-]+)/;
1157 my $from = $1 || 'example.com';
1158 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1161 my $agentnum = $cust_main->agentnum;
1162 if ( defined($args{'template'}) && length($args{'template'})
1163 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1166 $logo = 'logo_'. $args{'template'}. '.png';
1170 my $image_data = $conf->config_binary( $logo, $agentnum);
1172 $image = build MIME::Entity
1173 'Type' => 'image/png',
1174 'Encoding' => 'base64',
1175 'Data' => $image_data,
1176 'Filename' => 'logo.png',
1177 'Content-ID' => "<$content_id>",
1180 if ($conf->exists('invoice-barcode')) {
1181 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1182 $barcode = build MIME::Entity
1183 'Type' => 'image/png',
1184 'Encoding' => 'base64',
1185 'Data' => $self->invoice_barcode(0),
1186 'Filename' => 'barcode.png',
1187 'Content-ID' => "<$barcode_content_id>",
1189 $args{'barcode_cid'} = $barcode_content_id;
1192 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1195 $alternative->attach(
1196 'Type' => 'text/html',
1197 'Encoding' => 'quoted-printable',
1198 'Data' => [ '<html>',
1201 ' '. encode_entities($return{'subject'}),
1204 ' <body bgcolor="#e8e8e8">',
1209 'Disposition' => 'inline',
1210 #'Filename' => 'invoice.pdf',
1214 my @otherparts = ();
1215 if ( $cust_main->email_csv_cdr ) {
1217 push @otherparts, build MIME::Entity
1218 'Type' => 'text/csv',
1219 'Encoding' => '7bit',
1220 'Data' => [ map { "$_\n" }
1221 $self->call_details('prepend_billed_number' => 1)
1223 'Disposition' => 'attachment',
1224 'Filename' => 'usage-'. $self->invnum. '.csv',
1229 if ( $conf->exists('invoice_email_pdf') ) {
1234 # multipart/alternative
1240 my $related = build MIME::Entity 'Type' => 'multipart/related',
1241 'Encoding' => '7bit';
1243 #false laziness w/Misc::send_email
1244 $related->head->replace('Content-type',
1245 $related->mime_type.
1246 '; boundary="'. $related->head->multipart_boundary. '"'.
1247 '; type=multipart/alternative'
1250 $related->add_part($alternative);
1252 $related->add_part($image) if $image;
1254 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1256 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1260 #no other attachment:
1262 # multipart/alternative
1267 $return{'content-type'} = 'multipart/related';
1268 if ($conf->exists('invoice-barcode') && $barcode) {
1269 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1271 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1273 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1274 #$return{'disposition'} = 'inline';
1280 if ( $conf->exists('invoice_email_pdf') ) {
1281 warn "$me creating PDF attachment"
1284 #mime parts arguments a la MIME::Entity->build().
1285 $return{'mimeparts'} = [
1286 { $self->mimebuild_pdf(\%args) }
1290 if ( $conf->exists('invoice_email_pdf')
1291 and scalar($conf->config('invoice_email_pdf_note')) ) {
1293 warn "$me using 'invoice_email_pdf_note'"
1295 $return{'body'} = [ map { $_ . "\n" }
1296 $conf->config('invoice_email_pdf_note')
1301 warn "$me not using 'invoice_email_pdf_note'"
1303 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1304 $return{'body'} = $args{'print_text'};
1306 $return{'body'} = [ $self->print_text(\%args) ];
1319 Returns a list suitable for passing to MIME::Entity->build(), representing
1320 this invoice as PDF attachment.
1327 'Type' => 'application/pdf',
1328 'Encoding' => 'base64',
1329 'Data' => [ $self->print_pdf(@_) ],
1330 'Disposition' => 'attachment',
1331 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1337 Sends this invoice to the destinations configured for this customer: sends
1338 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1340 Options can be passed as a hashref. Positional parameters are no longer
1343 I<template>: a suffix for alternate invoices
1345 I<agentnum>: obsolete, now does nothing.
1347 I<invoice_from> overrides the default email invoice From: address.
1349 I<amount>: obsolete, does nothing
1351 I<notice_name> overrides "Invoice" as the name of the sent document
1352 (templates from 10/2009 or newer required).
1354 I<lpr> overrides the system 'lpr' option as the command to print a document
1355 from standard input.
1361 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1362 my $conf = $self->conf;
1364 my $cust_main = $self->cust_main;
1366 my @invoicing_list = $cust_main->invoicing_list;
1369 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1370 && ! $self->invoice_noemail;
1373 if grep { $_ eq 'POST' } @invoicing_list; #postal
1375 #this has never been used post-$ORIGINAL_ISP afaik
1376 $self->fax_invoice($opt)
1377 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1383 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1385 Sends this invoice to the customer's email destination(s).
1387 Options must be passed as a hashref. Positional parameters are no longer
1390 I<template>, if specified, is the name of a suffix for alternate invoices.
1392 I<invoice_from>, if specified, overrides the default email invoice From:
1395 I<notice_name> is the name of the sent document.
1399 sub queueable_email {
1402 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1403 or die "invalid invoice number: " . $opt{invnum};
1405 my %args = map {$_ => $opt{$_}}
1407 qw( invoice_from notice_name no_coupon template );
1409 my $error = $self->email( \%args );
1410 die $error if $error;
1416 return if $self->hide;
1417 my $conf = $self->conf;
1418 my $opt = shift || {};
1419 if ($opt and !ref($opt)) {
1420 die "FS::cust_bill::email called with positional parameters";
1423 my $template = $opt->{template};
1424 my $from = delete $opt->{invoice_from};
1426 # this is where we set the From: address
1427 $from ||= $self->_agent_invoice_from || #XXX should go away
1428 $conf->config('invoice_from', $self->cust_main->agentnum );
1430 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1431 $self->cust_main->invoicing_list;
1433 if ( ! @invoicing_list ) { #no recipients
1434 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1435 die 'No recipients for customer #'. $self->custnum;
1437 #default: better to notify this person than silence
1438 @invoicing_list = ($from);
1442 # this is where we set the Subject:
1443 my $subject = $self->email_subject($template);
1445 my $error = send_email(
1446 $self->generate_email(
1448 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1449 'subject' => $subject,
1450 %$opt, # template, etc.
1453 die "can't email invoice: $error\n" if $error;
1454 #die "$error\n" if $error;
1460 my $conf = $self->conf;
1462 #my $template = scalar(@_) ? shift : '';
1465 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1468 my $cust_main = $self->cust_main;
1469 my $name = $cust_main->name;
1470 my $name_short = $cust_main->name_short;
1471 my $invoice_number = $self->invnum;
1472 my $invoice_date = $self->_date_pretty;
1474 eval qq("$subject");
1477 =item lpr_data HASHREF
1479 Returns the postscript or plaintext for this invoice as an arrayref.
1481 Options must be passed as a hashref. Positional parameters are no longer
1484 I<template>, if specified, is the name of a suffix for alternate invoices.
1486 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1492 my $conf = $self->conf;
1493 my $opt = shift || {};
1494 if ($opt and !ref($opt)) {
1495 # nobody does this anyway
1496 die "FS::cust_bill::lpr_data called with positional parameters";
1499 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1500 [ $self->$method( $opt ) ];
1505 Prints this invoice.
1507 Options must be passed as a hashref.
1509 I<template>, if specified, is the name of a suffix for alternate invoices.
1511 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1517 return if $self->hide;
1518 my $conf = $self->conf;
1519 my $opt = shift || {};
1520 if ($opt and !ref($opt)) {
1521 die "FS::cust_bill::print called with positional parameters";
1524 my $lpr = delete $opt->{lpr};
1525 if($conf->exists('invoice_print_pdf')) {
1526 # Add the invoice to the current batch.
1527 $self->batch_invoice($opt);
1531 $self->lpr_data($opt),
1532 'agentnum' => $self->cust_main->agentnum,
1538 =item fax_invoice HASHREF
1542 Options must be passed as a hashref.
1544 I<template>, if specified, is the name of a suffix for alternate invoices.
1546 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1552 return if $self->hide;
1553 my $conf = $self->conf;
1554 my $opt = shift || {};
1555 if ($opt and !ref($opt)) {
1556 die "FS::cust_bill::fax_invoice called with positional parameters";
1559 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1560 unless $conf->exists('invoice_latex');
1562 my $dialstring = $self->cust_main->getfield('fax');
1565 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1566 'dialstring' => $dialstring,
1568 die $error if $error;
1572 =item batch_invoice [ HASHREF ]
1574 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1575 isn't an open batch, one will be created.
1580 my ($self, $opt) = @_;
1581 my $bill_batch = $self->get_open_bill_batch;
1582 my $cust_bill_batch = FS::cust_bill_batch->new({
1583 batchnum => $bill_batch->batchnum,
1584 invnum => $self->invnum,
1586 return $cust_bill_batch->insert($opt);
1589 =item get_open_batch
1591 Returns the currently open batch as an FS::bill_batch object, creating a new
1592 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1597 sub get_open_bill_batch {
1599 my $conf = $self->conf;
1600 my $hashref = { status => 'O' };
1601 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1602 ? $self->cust_main->agentnum
1604 my $batch = qsearchs('bill_batch', $hashref);
1605 return $batch if $batch;
1606 $batch = FS::bill_batch->new($hashref);
1607 my $error = $batch->insert;
1608 die $error if $error;
1612 =item ftp_invoice [ TEMPLATENAME ]
1614 Sends this invoice data via FTP.
1616 TEMPLATENAME is unused?
1622 my $conf = $self->conf;
1623 my $template = scalar(@_) ? shift : '';
1626 'protocol' => 'ftp',
1627 'server' => $conf->config('cust_bill-ftpserver'),
1628 'username' => $conf->config('cust_bill-ftpusername'),
1629 'password' => $conf->config('cust_bill-ftppassword'),
1630 'dir' => $conf->config('cust_bill-ftpdir'),
1631 'format' => $conf->config('cust_bill-ftpformat'),
1635 =item spool_invoice [ TEMPLATENAME ]
1637 Spools this invoice data (see L<FS::spool_csv>)
1639 TEMPLATENAME is unused?
1645 my $conf = $self->conf;
1646 my $template = scalar(@_) ? shift : '';
1649 'format' => $conf->config('cust_bill-spoolformat'),
1650 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1654 =item send_csv OPTION => VALUE, ...
1656 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1660 protocol - currently only "ftp"
1666 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1667 and YYMMDDHHMMSS is a timestamp.
1669 See L</print_csv> for a description of the output format.
1674 my($self, %opt) = @_;
1678 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1679 mkdir $spooldir, 0700 unless -d $spooldir;
1681 # don't localize dates here, they're a defined format
1682 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1683 my $file = "$spooldir/$tracctnum.csv";
1685 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1687 open(CSV, ">$file") or die "can't open $file: $!";
1695 if ( $opt{protocol} eq 'ftp' ) {
1696 eval "use Net::FTP;";
1698 $net = Net::FTP->new($opt{server}) or die @$;
1700 die "unknown protocol: $opt{protocol}";
1703 $net->login( $opt{username}, $opt{password} )
1704 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1706 $net->binary or die "can't set binary mode";
1708 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1710 $net->put($file) or die "can't put $file: $!";
1720 Spools CSV invoice data.
1726 =item format - any of FS::Misc::::Invoicing::spool_formats
1728 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1729 customer has the corresponding invoice destinations set (see
1730 L<FS::cust_main_invoice>).
1732 =item agent_spools - if set to a true value, will spool to per-agent files
1733 rather than a single global file
1735 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1736 append to that spool. L<FS::Cron::upload> will then send the spool file to
1739 =item balanceover - if set, only spools the invoice if the total amount owed on
1740 this invoice and all older invoices is greater than the specified amount.
1742 =item time - the "current time". Controls the printing of past due messages
1750 my($self, %opt) = @_;
1752 my $time = $opt{'time'} || time;
1753 my $cust_main = $self->cust_main;
1755 if ( $opt{'dest'} ) {
1756 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1757 $cust_main->invoicing_list;
1758 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1759 || ! keys %invoicing_list;
1762 if ( $opt{'balanceover'} ) {
1764 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1767 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1768 mkdir $spooldir, 0700 unless -d $spooldir;
1770 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1773 if ( $opt{'agent_spools'} ) {
1774 $file = 'agentnum'.$cust_main->agentnum;
1779 if ( $opt{'upload_targetnum'} ) {
1780 $spooldir .= '/target'.$opt{'upload_targetnum'};
1781 mkdir $spooldir, 0700 unless -d $spooldir;
1782 } # otherwise it just goes into export.xxx/cust_bill
1784 if ( lc($opt{'format'}) eq 'billco' ) {
1788 $file = "$spooldir/$file.csv";
1790 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1792 open(CSV, ">>$file") or die "can't open $file: $!";
1793 flock(CSV, LOCK_EX);
1798 if ( lc($opt{'format'}) eq 'billco' ) {
1800 flock(CSV, LOCK_UN);
1803 $file =~ s/-header.csv$/-detail.csv/;
1805 open(CSV,">>$file") or die "can't open $file: $!";
1806 flock(CSV, LOCK_EX);
1810 print CSV $detail if defined($detail);
1812 flock(CSV, LOCK_UN);
1819 =item print_csv OPTION => VALUE, ...
1821 Returns CSV data for this invoice.
1825 format - 'default', 'billco', 'oneline', 'bridgestone'
1827 Returns a list consisting of two scalars. The first is a single line of CSV
1828 header information for this invoice. The second is one or more lines of CSV
1829 detail information for this invoice.
1831 If I<format> is not specified or "default", the fields of the CSV file are as
1834 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1835 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1839 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1841 B<record_type> is C<cust_bill> for the initial header line only. The
1842 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1843 fields are filled in.
1845 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1846 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1849 =item invnum - invoice number
1851 =item custnum - customer number
1853 =item _date - invoice date
1855 =item charged - total invoice amount
1857 =item first - customer first name
1859 =item last - customer first name
1861 =item company - company name
1863 =item address1 - address line 1
1865 =item address2 - address line 1
1875 =item pkg - line item description
1877 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1879 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1881 =item sdate - start date for recurring fee
1883 =item edate - end date for recurring fee
1887 If I<format> is "billco", the fields of the header CSV file are as follows:
1889 +-------------------------------------------------------------------+
1890 | FORMAT HEADER FILE |
1891 |-------------------------------------------------------------------|
1892 | Field | Description | Name | Type | Width |
1893 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1894 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1895 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1896 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1897 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1898 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1899 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1900 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1901 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1902 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1903 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1904 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1905 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1906 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1907 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1908 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1909 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1910 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1911 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1912 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1913 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1914 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1915 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1916 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1917 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1918 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1919 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1920 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1921 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1922 +-------+-------------------------------+------------+------+-------+
1924 If I<format> is "billco", the fields of the detail CSV file are as follows:
1926 FORMAT FOR DETAIL FILE
1928 Field | Description | Name | Type | Width
1929 1 | N/A-Leave Empty | RC | CHAR | 2
1930 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1931 3 | Account Number | TRACCTNUM | CHAR | 15
1932 4 | Invoice Number | TRINVOICE | CHAR | 15
1933 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1934 6 | Transaction Detail | DETAILS | CHAR | 100
1935 7 | Amount | AMT | NUM* | 9
1936 8 | Line Format Control** | LNCTRL | CHAR | 2
1937 9 | Grouping Code | GROUP | CHAR | 2
1938 10 | User Defined | ACCT CODE | CHAR | 15
1940 If format is 'oneline', there is no detail file. Each invoice has a
1941 header line only, with the fields:
1943 Agent number, agent name, customer number, first name, last name, address
1944 line 1, address line 2, city, state, zip, invoice date, invoice number,
1945 amount charged, amount due, previous balance, due date.
1947 and then, for each line item, three columns containing the package number,
1948 description, and amount.
1950 If format is 'bridgestone', there is no detail file. Each invoice has a
1951 header line with the following fields in a fixed-width format:
1953 Customer number (in display format), date, name (first last), company,
1954 address 1, address 2, city, state, zip.
1956 This is a mailing list format, and has no per-invoice fields. To avoid
1957 sending redundant notices, the spooling event should have a "once" or
1958 "once_percust_every" condition.
1963 my($self, %opt) = @_;
1965 eval "use Text::CSV_XS";
1968 my $cust_main = $self->cust_main;
1970 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1971 my $format = lc($opt{'format'});
1973 my $time = $opt{'time'} || time;
1975 my $tracctnum = ''; #leaking out from billco-specific sections :/
1976 if ( $format eq 'billco' ) {
1979 $self->conf->config('billco-account_num', $cust_main->agentnum);
1981 $tracctnum = $account_num eq 'display_custnum'
1982 ? $cust_main->display_custnum
1983 : $opt{'tracctnum'};
1986 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1988 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1990 my( $previous_balance, @unused ) = $self->previous; #previous balance
1992 my $pmt_cr_applied = 0;
1993 $pmt_cr_applied += $_->{'amount'}
1994 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1996 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1999 '', # 1 | N/A-Leave Empty CHAR 2
2000 '', # 2 | N/A-Leave Empty CHAR 15
2001 $tracctnum, # 3 | Transaction Account No CHAR 15
2002 $self->invnum, # 4 | Transaction Invoice No CHAR 15
2003 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
2004 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
2005 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
2006 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
2007 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
2008 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
2009 '', # 10 | Ancillary Billing Information CHAR 30
2010 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
2011 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
2014 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
2017 $duedate, # 14 | Bill Due Date CHAR 10
2019 $previous_balance, # 15 | Previous Balance NUM* 9
2020 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2021 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2022 $totaldue, # 18 | Total Amt Due NUM* 9
2023 $totaldue, # 19 | Total Amt Due NUM* 9
2024 '', # 20 | 30 Day Aging NUM* 9
2025 '', # 21 | 60 Day Aging NUM* 9
2026 '', # 22 | 90 Day Aging NUM* 9
2027 'N', # 23 | Y/N CHAR 1
2028 '', # 24 | Remittance automation CHAR 100
2029 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2030 $self->custnum, # 26 | Customer Reference Number CHAR 15
2031 '0', # 27 | Federal Tax*** NUM* 9
2032 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2033 '0', # 29 | Other Taxes & Fees*** NUM* 9
2036 } elsif ( $format eq 'oneline' ) { #name
2038 my ($previous_balance) = $self->previous;
2039 $previous_balance = sprintf('%.2f', $previous_balance);
2040 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2046 $self->_items_pkg, #_items_nontax? no sections or anything
2051 $cust_main->agentnum,
2052 $cust_main->agent->agent,
2056 $cust_main->company,
2057 $cust_main->address1,
2058 $cust_main->address2,
2064 time2str("%x", $self->_date),
2069 $self->due_date2str("%x"),
2074 } elsif ( $format eq 'bridgestone' ) {
2076 # bypass the CSV stuff and just return this
2077 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2078 my $zip = $cust_main->zip;
2080 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2084 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2086 $cust_main->display_custnum,
2088 uc(substr($cust_main->contact_firstlast,0,30)),
2089 uc(substr($cust_main->company ,0,30)),
2090 uc(substr($cust_main->address1 ,0,30)),
2091 uc(substr($cust_main->address2 ,0,30)),
2092 uc(substr($cust_main->city ,0,20)),
2093 uc($cust_main->state),
2099 } elsif ( $format eq 'ics' ) {
2101 my $bill = $cust_main->bill_location;
2102 my $zip = $bill->zip;
2106 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2111 # minor false laziness with print_generic
2112 my ($previous_balance) = $self->previous;
2113 my $balance_due = $self->owed + $previous_balance;
2114 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2115 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2118 if ( $self->due_date and $time >= $self->due_date ) {
2119 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2123 my $header = sprintf(
2124 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2125 $cust_main->display_custnum, #BID
2126 uc($cust_main->first), #FNAME
2127 uc($cust_main->last), #LNAME
2128 '00', #BATCH, should this ever be anything else?
2129 uc($cust_main->company), #COMP
2130 uc($bill->address1), #STREET1
2131 uc($bill->address2), #STREET2
2132 uc($bill->city), #CITY
2133 uc($bill->state), #STATE
2136 time2str('%Y%m%d', $self->_date), #BILL_DATE
2137 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2138 ( map {sprintf('%0.2f', $_)}
2139 $balance_due, #AMNT_DUE
2140 $previous_balance, #PREV_BAL
2141 $payment_total, #PYMT_RCVD
2142 $credit_total, #CREDITS
2143 $previous_balance, #BEG_BAL--is this correct?
2144 $self->charged, #NEW_CHRG
2147 $past_due, #PAST_MSG
2151 my %svc_class = ('' => ''); # maybe cache this more persistently?
2153 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2155 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2156 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2160 my @dates = ( $self->_date, undef );
2161 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2162 $dates[1] = $prev->sdate; #questionable
2165 # generate an 01 detail for each service
2166 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2167 foreach my $cust_svc ( @svcs ) {
2168 $show_pkgnum = ''; # hide it if we're showing svcnums
2170 my $svcpart = $cust_svc->svcpart;
2171 if (!exists($svc_class{$svcpart})) {
2172 my $classnum = $cust_svc->part_svc->classnum;
2173 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2175 $svc_class{$svcpart} = $part_svc_class ?
2176 $part_svc_class->classname :
2180 my @h_label = $cust_svc->label(@dates, 'I');
2181 push @details, sprintf('01%-9s%-20s%-47s',
2183 $svc_class{$svcpart},
2186 } #foreach $cust_svc
2189 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2190 if ($cust_bill_pkg->recur > 0) {
2191 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2192 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2194 push @details, sprintf('02%-6s%-60s%-10s',
2197 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2199 } #foreach $cust_bill_pkg
2201 # Tag this row so that we know whether this is one page (1), two pages
2202 # (2), # or "big" (B). The tag will be stripped off before uploading.
2203 if ( scalar(@details) < 12 ) {
2205 } elsif ( scalar(@details) < 58 ) {
2211 return join('', $header, @details, "\n");
2219 time2str("%x", $self->_date),
2220 sprintf("%.2f", $self->charged),
2221 ( map { $cust_main->getfield($_) }
2222 qw( first last company address1 address2 city state zip country ) ),
2224 ) or die "can't create csv";
2227 my $header = $csv->string. "\n";
2230 if ( lc($opt{'format'}) eq 'billco' ) {
2233 foreach my $item ( $self->_items_pkg ) {
2236 '', # 1 | N/A-Leave Empty CHAR 2
2237 '', # 2 | N/A-Leave Empty CHAR 15
2238 $tracctnum, # 3 | Account Number CHAR 15
2239 $self->invnum, # 4 | Invoice Number CHAR 15
2240 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2241 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2242 $item->{'amount'}, # 7 | Amount NUM* 9
2243 '', # 8 | Line Format Control** CHAR 2
2244 '', # 9 | Grouping Code CHAR 2
2245 '', # 10 | User Defined CHAR 15
2248 $detail .= $csv->string. "\n";
2252 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2258 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2260 my($pkg, $setup, $recur, $sdate, $edate);
2261 if ( $cust_bill_pkg->pkgnum ) {
2263 ($pkg, $setup, $recur, $sdate, $edate) = (
2264 $cust_bill_pkg->part_pkg->pkg,
2265 ( $cust_bill_pkg->setup != 0
2266 ? sprintf("%.2f", $cust_bill_pkg->setup )
2268 ( $cust_bill_pkg->recur != 0
2269 ? sprintf("%.2f", $cust_bill_pkg->recur )
2271 ( $cust_bill_pkg->sdate
2272 ? time2str("%x", $cust_bill_pkg->sdate)
2274 ($cust_bill_pkg->edate
2275 ? time2str("%x", $cust_bill_pkg->edate)
2279 } else { #pkgnum tax
2280 next unless $cust_bill_pkg->setup != 0;
2281 $pkg = $cust_bill_pkg->desc;
2282 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2283 ( $sdate, $edate ) = ( '', '' );
2289 ( map { '' } (1..11) ),
2290 ($pkg, $setup, $recur, $sdate, $edate)
2291 ) or die "can't create csv";
2293 $detail .= $csv->string. "\n";
2299 ( $header, $detail );
2305 Pays this invoice with a compliemntary payment. If there is an error,
2306 returns the error, otherwise returns false.
2312 my $cust_pay = new FS::cust_pay ( {
2313 'invnum' => $self->invnum,
2314 'paid' => $self->owed,
2317 'payinfo' => $self->cust_main->payinfo,
2325 Attempts to pay this invoice with a credit card payment via a
2326 Business::OnlinePayment realtime gateway. See
2327 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2328 for supported processors.
2334 $self->realtime_bop( 'CC', @_ );
2339 Attempts to pay this invoice with an electronic check (ACH) payment via a
2340 Business::OnlinePayment realtime gateway. See
2341 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2342 for supported processors.
2348 $self->realtime_bop( 'ECHECK', @_ );
2353 Attempts to pay this invoice with phone bill (LEC) payment via a
2354 Business::OnlinePayment realtime gateway. See
2355 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2356 for supported processors.
2362 $self->realtime_bop( 'LEC', @_ );
2366 my( $self, $method ) = (shift,shift);
2367 my $conf = $self->conf;
2370 my $cust_main = $self->cust_main;
2371 my $balance = $cust_main->balance;
2372 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2373 $amount = sprintf("%.2f", $amount);
2374 return "not run (balance $balance)" unless $amount > 0;
2376 my $description = 'Internet Services';
2377 if ( $conf->exists('business-onlinepayment-description') ) {
2378 my $dtempl = $conf->config('business-onlinepayment-description');
2380 my $agent_obj = $cust_main->agent
2381 or die "can't retreive agent for $cust_main (agentnum ".
2382 $cust_main->agentnum. ")";
2383 my $agent = $agent_obj->agent;
2384 my $pkgs = join(', ',
2385 map { $_->part_pkg->pkg }
2386 grep { $_->pkgnum } $self->cust_bill_pkg
2388 $description = eval qq("$dtempl");
2391 $cust_main->realtime_bop($method, $amount,
2392 'description' => $description,
2393 'invnum' => $self->invnum,
2394 #this didn't do what we want, it just calls apply_payments_and_credits
2396 'apply_to_invoice' => 1,
2399 #this changes application behavior: auto payments
2400 #triggered against a specific invoice are now applied
2401 #to that invoice instead of oldest open.
2407 =item batch_card OPTION => VALUE...
2409 Adds a payment for this invoice to the pending credit card batch (see
2410 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2411 runs the payment using a realtime gateway.
2416 my ($self, %options) = @_;
2417 my $cust_main = $self->cust_main;
2419 $options{invnum} = $self->invnum;
2421 $cust_main->batch_card(%options);
2424 sub _agent_template {
2426 $self->cust_main->agent_template;
2429 sub _agent_invoice_from {
2431 $self->cust_main->agent_invoice_from;
2434 =item invoice_barcode DIR_OR_FALSE
2436 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2437 it is taken as the temp directory where the PNG file will be generated and the
2438 PNG file name is returned. Otherwise, the PNG image itself is returned.
2442 sub invoice_barcode {
2443 my ($self, $dir) = (shift,shift);
2445 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2446 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2447 my $gd = $gdbar->plot(Height => 30);
2450 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2454 ) or die "can't open temp file: $!\n";
2455 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2456 my $png_file = $bh->filename;
2463 =item invnum_date_pretty
2465 Returns a string with the invoice number and date, for example:
2466 "Invoice #54 (3/20/2008)"
2470 sub invnum_date_pretty {
2472 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2475 #sub _items_extra_usage_sections {
2477 # my $escape = shift;
2479 # my %sections = ();
2481 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2482 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2484 # next unless $cust_bill_pkg->pkgnum > 0;
2486 # foreach my $section ( keys %usage_class ) {
2488 # my $usage = $cust_bill_pkg->usage($section);
2490 # next unless $usage && $usage > 0;
2492 # $sections{$section} ||= 0;
2493 # $sections{$section} += $usage;
2499 # map { { 'description' => &{$escape}($_),
2500 # 'subtotal' => $sections{$_},
2501 # 'summarized' => '',
2502 # 'tax_section' => '',
2505 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2509 sub _items_extra_usage_sections {
2511 my $conf = $self->conf;
2519 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2521 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2522 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2523 next unless $cust_bill_pkg->pkgnum > 0;
2525 foreach my $classnum ( keys %usage_class ) {
2526 my $section = $usage_class{$classnum}->classname;
2527 $classnums{$section} = $classnum;
2529 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2530 my $amount = $detail->amount;
2531 next unless $amount && $amount > 0;
2533 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2534 $sections{$section}{amount} += $amount; #subtotal
2535 $sections{$section}{calls}++;
2536 $sections{$section}{duration} += $detail->duration;
2538 my $desc = $detail->regionname;
2539 my $description = $desc;
2540 $description = substr($desc, 0, $maxlength). '...'
2541 if $format eq 'latex' && length($desc) > $maxlength;
2543 $lines{$section}{$desc} ||= {
2544 description => &{$escape}($description),
2545 #pkgpart => $part_pkg->pkgpart,
2546 pkgnum => $cust_bill_pkg->pkgnum,
2551 #unit_amount => $cust_bill_pkg->unitrecur,
2552 quantity => $cust_bill_pkg->quantity,
2553 product_code => 'N/A',
2554 ext_description => [],
2557 $lines{$section}{$desc}{amount} += $amount;
2558 $lines{$section}{$desc}{calls}++;
2559 $lines{$section}{$desc}{duration} += $detail->duration;
2565 my %sectionmap = ();
2566 foreach (keys %sections) {
2567 my $usage_class = $usage_class{$classnums{$_}};
2568 $sectionmap{$_} = { 'description' => &{$escape}($_),
2569 'amount' => $sections{$_}{amount}, #subtotal
2570 'calls' => $sections{$_}{calls},
2571 'duration' => $sections{$_}{duration},
2573 'tax_section' => '',
2574 'sort_weight' => $usage_class->weight,
2575 ( $usage_class->format
2576 ? ( map { $_ => $usage_class->$_($format) }
2577 qw( description_generator header_generator total_generator total_line_generator )
2584 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2588 foreach my $section ( keys %lines ) {
2589 foreach my $line ( keys %{$lines{$section}} ) {
2590 my $l = $lines{$section}{$line};
2591 $l->{section} = $sectionmap{$section};
2592 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2593 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2598 return(\@sections, \@lines);
2604 my $end = $self->_date;
2606 # start at date of previous invoice + 1 second or 0 if no previous invoice
2607 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2608 $start = 0 if !$start;
2611 my $cust_main = $self->cust_main;
2612 my @pkgs = $cust_main->all_pkgs;
2613 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2616 foreach my $pkg ( @pkgs ) {
2617 my @h_cust_svc = $pkg->h_cust_svc($end);
2618 foreach my $h_cust_svc ( @h_cust_svc ) {
2619 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2620 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2622 my $inserted = $h_cust_svc->date_inserted;
2623 my $deleted = $h_cust_svc->date_deleted;
2624 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2626 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2628 # DID either activated or ported in; cannot be both for same DID simultaneously
2629 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2630 && (!$phone_inserted->lnp_status
2631 || $phone_inserted->lnp_status eq ''
2632 || $phone_inserted->lnp_status eq 'native')) {
2635 else { # this one not so clean, should probably move to (h_)svc_phone
2636 my $phone_portedin = qsearchs( 'h_svc_phone',
2637 { 'svcnum' => $h_cust_svc->svcnum,
2638 'lnp_status' => 'portedin' },
2639 FS::h_svc_phone->sql_h_searchs($end),
2641 $num_portedin++ if $phone_portedin;
2644 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2645 if($deleted >= $start && $deleted <= $end && $phone_deleted
2646 && (!$phone_deleted->lnp_status
2647 || $phone_deleted->lnp_status ne 'portingout')) {
2650 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2651 && $phone_deleted->lnp_status
2652 && $phone_deleted->lnp_status eq 'portingout') {
2656 # increment usage minutes
2657 if ( $phone_inserted ) {
2658 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2659 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2662 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2665 # don't look at this service again
2666 push @seen, $h_cust_svc->svcnum;
2670 $minutes = sprintf("%d", $minutes);
2671 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2672 . "$num_deactivated Ported-Out: $num_portedout ",
2673 "Total Minutes: $minutes");
2676 sub _items_accountcode_cdr {
2681 my $section = { 'amount' => 0,
2684 'sort_weight' => '',
2686 'description' => 'Usage by Account Code',
2692 my %accountcodes = ();
2694 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2695 next unless $cust_bill_pkg->pkgnum > 0;
2697 my @header = $cust_bill_pkg->details_header;
2698 next unless scalar(@header);
2699 $section->{'header'} = join(',',@header);
2701 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2703 $section->{'header'} = $detail->formatted('format' => $format)
2704 if($detail->detail eq $section->{'header'});
2706 my $accountcode = $detail->accountcode;
2707 next unless $accountcode;
2709 my $amount = $detail->amount;
2710 next unless $amount && $amount > 0;
2712 $accountcodes{$accountcode} ||= {
2713 description => $accountcode,
2720 product_code => 'N/A',
2721 section => $section,
2722 ext_description => [ $section->{'header'} ],
2726 $section->{'amount'} += $amount;
2727 $accountcodes{$accountcode}{'amount'} += $amount;
2728 $accountcodes{$accountcode}{calls}++;
2729 $accountcodes{$accountcode}{duration} += $detail->duration;
2730 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2734 foreach my $l ( values %accountcodes ) {
2735 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2736 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2737 foreach my $sorted_detail ( @sorted_detail ) {
2738 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2740 delete $l->{detail_temp};
2744 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2746 return ($section,\@sorted_lines);
2749 sub _items_svc_phone_sections {
2751 my $conf = $self->conf;
2759 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2761 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2762 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2764 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2765 next unless $cust_bill_pkg->pkgnum > 0;
2767 my @header = $cust_bill_pkg->details_header;
2768 next unless scalar(@header);
2770 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2772 my $phonenum = $detail->phonenum;
2773 next unless $phonenum;
2775 my $amount = $detail->amount;
2776 next unless $amount && $amount > 0;
2778 $sections{$phonenum} ||= { 'amount' => 0,
2781 'sort_weight' => -1,
2782 'phonenum' => $phonenum,
2784 $sections{$phonenum}{amount} += $amount; #subtotal
2785 $sections{$phonenum}{calls}++;
2786 $sections{$phonenum}{duration} += $detail->duration;
2788 my $desc = $detail->regionname;
2789 my $description = $desc;
2790 $description = substr($desc, 0, $maxlength). '...'
2791 if $format eq 'latex' && length($desc) > $maxlength;
2793 $lines{$phonenum}{$desc} ||= {
2794 description => &{$escape}($description),
2795 #pkgpart => $part_pkg->pkgpart,
2803 product_code => 'N/A',
2804 ext_description => [],
2807 $lines{$phonenum}{$desc}{amount} += $amount;
2808 $lines{$phonenum}{$desc}{calls}++;
2809 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2811 my $line = $usage_class{$detail->classnum}->classname;
2812 $sections{"$phonenum $line"} ||=
2816 'sort_weight' => $usage_class{$detail->classnum}->weight,
2817 'phonenum' => $phonenum,
2818 'header' => [ @header ],
2820 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2821 $sections{"$phonenum $line"}{calls}++;
2822 $sections{"$phonenum $line"}{duration} += $detail->duration;
2824 $lines{"$phonenum $line"}{$desc} ||= {
2825 description => &{$escape}($description),
2826 #pkgpart => $part_pkg->pkgpart,
2834 product_code => 'N/A',
2835 ext_description => [],
2838 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2839 $lines{"$phonenum $line"}{$desc}{calls}++;
2840 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2841 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2842 $detail->formatted('format' => $format);
2847 my %sectionmap = ();
2848 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2849 foreach ( keys %sections ) {
2850 my @header = @{ $sections{$_}{header} || [] };
2852 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2853 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2854 my $usage_class = $summary ? $simple : $usage_simple;
2855 my $ending = $summary ? ' usage charges' : '';
2858 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2860 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2861 'amount' => $sections{$_}{amount}, #subtotal
2862 'calls' => $sections{$_}{calls},
2863 'duration' => $sections{$_}{duration},
2865 'tax_section' => '',
2866 'phonenum' => $sections{$_}{phonenum},
2867 'sort_weight' => $sections{$_}{sort_weight},
2868 'post_total' => $summary, #inspire pagebreak
2870 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2871 qw( description_generator
2874 total_line_generator
2881 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2882 $a->{sort_weight} <=> $b->{sort_weight}
2887 foreach my $section ( keys %lines ) {
2888 foreach my $line ( keys %{$lines{$section}} ) {
2889 my $l = $lines{$section}{$line};
2890 $l->{section} = $sectionmap{$section};
2891 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2892 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2897 if($conf->exists('phone_usage_class_summary')) {
2898 # this only works with Latex
2902 # after this, we'll have only two sections per DID:
2903 # Calls Summary and Calls Detail
2904 foreach my $section ( @sections ) {
2905 if($section->{'post_total'}) {
2906 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2907 $section->{'total_line_generator'} = sub { '' };
2908 $section->{'total_generator'} = sub { '' };
2909 $section->{'header_generator'} = sub { '' };
2910 $section->{'description_generator'} = '';
2911 push @newsections, $section;
2912 my %calls_detail = %$section;
2913 $calls_detail{'post_total'} = '';
2914 $calls_detail{'sort_weight'} = '';
2915 $calls_detail{'description_generator'} = sub { '' };
2916 $calls_detail{'header_generator'} = sub {
2917 return ' & Date/Time & Called Number & Duration & Price'
2918 if $format eq 'latex';
2921 $calls_detail{'description'} = 'Calls Detail: '
2922 . $section->{'phonenum'};
2923 push @newsections, \%calls_detail;
2927 # after this, each usage class is collapsed/summarized into a single
2928 # line under the Calls Summary section
2929 foreach my $newsection ( @newsections ) {
2930 if($newsection->{'post_total'}) { # this means Calls Summary
2931 foreach my $section ( @sections ) {
2932 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2933 && !$section->{'post_total'});
2934 my $newdesc = $section->{'description'};
2935 my $tn = $section->{'phonenum'};
2936 $newdesc =~ s/$tn//g;
2937 my $line = { ext_description => [],
2941 calls => $section->{'calls'},
2942 section => $newsection,
2943 duration => $section->{'duration'},
2944 description => $newdesc,
2945 amount => sprintf("%.2f",$section->{'amount'}),
2946 product_code => 'N/A',
2948 push @newlines, $line;
2953 # after this, Calls Details is populated with all CDRs
2954 foreach my $newsection ( @newsections ) {
2955 if(!$newsection->{'post_total'}) { # this means Calls Details
2956 foreach my $line ( @lines ) {
2957 next unless (scalar(@{$line->{'ext_description'}}) &&
2958 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2960 my @extdesc = @{$line->{'ext_description'}};
2962 foreach my $extdesc ( @extdesc ) {
2963 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2964 push @newextdesc, $extdesc;
2966 $line->{'ext_description'} = \@newextdesc;
2967 $line->{'section'} = $newsection;
2968 push @newlines, $line;
2973 return(\@newsections, \@newlines);
2976 return(\@sections, \@lines);
2980 sub _items_previous {
2982 my $conf = $self->conf;
2983 my $cust_main = $self->cust_main;
2984 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2986 foreach ( @pr_cust_bill ) {
2987 my $date = $conf->exists('invoice_show_prior_due_date')
2988 ? 'due '. $_->due_date2str('short')
2989 : $self->time2str_local('short', $_->_date);
2991 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2992 #'pkgpart' => 'N/A',
2994 'amount' => sprintf("%.2f", $_->owed),
3000 # 'description' => 'Previous Balance',
3001 # #'pkgpart' => 'N/A',
3002 # 'pkgnum' => 'N/A',
3003 # 'amount' => sprintf("%10.2f", $pr_total ),
3004 # 'ext_description' => [ map {
3005 # "Invoice ". $_->invnum.
3006 # " (". time2str("%x",$_->_date). ") ".
3007 # sprintf("%10.2f", $_->owed)
3008 # } @pr_cust_bill ],
3013 sub _items_credits {
3014 my( $self, %opt ) = @_;
3015 my $trim_len = $opt{'trim_len'} || 60;
3020 if ( $self->conf->exists('previous_balance-payments_since') ) {
3021 if ( $opt{'template'} eq 'statement' ) {
3022 # then the current bill is a "statement" (i.e. an invoice sent as
3023 # a payment receipt)
3024 # and in that case we want to see payments on or after THIS invoice
3025 @objects = qsearch('cust_credit', {
3026 'custnum' => $self->custnum,
3027 '_date' => {op => '>=', value => $self->_date},
3031 $date = $self->previous_bill->_date if $self->previous_bill;
3032 @objects = qsearch('cust_credit', {
3033 'custnum' => $self->custnum,
3034 '_date' => {op => '>=', value => $date},
3038 @objects = $self->cust_credited;
3041 foreach my $obj ( @objects ) {
3042 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3044 my $reason = substr($cust_credit->reason, 0, $trim_len);
3045 $reason .= '...' if length($reason) < length($cust_credit->reason);
3046 $reason = " ($reason) " if $reason;
3049 #'description' => 'Credit ref\#'. $_->crednum.
3050 # " (". time2str("%x",$_->cust_credit->_date) .")".
3052 'description' => $self->mt('Credit applied').' '.
3053 $self->time2str_local('short', $obj->_date). $reason,
3054 'amount' => sprintf("%.2f",$obj->amount),
3062 sub _items_payments {
3067 my $detailed = $self->conf->exists('invoice_payment_details');
3069 if ( $self->conf->exists('previous_balance-payments_since') ) {
3070 # then show payments dated on/after the previous bill...
3071 if ( $opt{'template'} eq 'statement' ) {
3072 # then the current bill is a "statement" (i.e. an invoice sent as
3073 # a payment receipt)
3074 # and in that case we want to see payments on or after THIS invoice
3075 @objects = qsearch('cust_pay', {
3076 'custnum' => $self->custnum,
3077 '_date' => {op => '>=', value => $self->_date},
3080 # the normal case: payments on or after the previous invoice
3082 $date = $self->previous_bill->_date if $self->previous_bill;
3083 @objects = qsearch('cust_pay', {
3084 'custnum' => $self->custnum,
3085 '_date' => {op => '>=', value => $date},
3087 # and before the current bill...
3088 @objects = grep { $_->_date < $self->_date } @objects;
3091 @objects = $self->cust_bill_pay;
3094 foreach my $obj (@objects) {
3095 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3096 my $desc = $self->mt('Payment received').' '.
3097 $self->time2str_local('short', $cust_pay->_date );
3098 $desc .= $self->mt(' via ') .
3099 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3103 'description' => $desc,
3104 'amount' => sprintf("%.2f", $obj->amount )
3112 =item call_details [ OPTION => VALUE ... ]
3114 Returns an array of CSV strings representing the call details for this invoice
3115 The only option available is the boolean prepend_billed_number
3120 my ($self, %opt) = @_;
3122 my $format_function = sub { shift };
3124 if ($opt{prepend_billed_number}) {
3125 $format_function = sub {
3129 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3134 my @details = map { $_->details( 'format_function' => $format_function,
3135 'escape_function' => sub{ return() },
3139 $self->cust_bill_pkg;
3140 my $header = $details[0];
3141 ( $header, grep { $_ ne $header } @details );
3151 =item process_reprint
3155 sub process_reprint {
3156 process_re_X('print', @_);
3159 =item process_reemail
3163 sub process_reemail {
3164 process_re_X('email', @_);
3172 process_re_X('fax', @_);
3180 process_re_X('ftp', @_);
3187 sub process_respool {
3188 process_re_X('spool', @_);
3191 use Storable qw(thaw);
3195 my( $method, $job ) = ( shift, shift );
3196 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3198 my $param = thaw(decode_base64(shift));
3199 warn Dumper($param) if $DEBUG;
3210 # spool_invoice ftp_invoice fax_invoice print_invoice
3211 my($method, $job, %param ) = @_;
3213 warn "re_X $method for job $job with param:\n".
3214 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3217 #some false laziness w/search/cust_bill.html
3219 my $orderby = 'ORDER BY cust_bill._date';
3221 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3223 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3225 my @cust_bill = qsearch( {
3226 #'select' => "cust_bill.*",
3227 'table' => 'cust_bill',
3228 'addl_from' => $addl_from,
3230 'extra_sql' => $extra_sql,
3231 'order_by' => $orderby,
3235 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3237 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3240 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3241 foreach my $cust_bill ( @cust_bill ) {
3242 $cust_bill->$method();
3244 if ( $job ) { #progressbar foo
3246 if ( time - $min_sec > $last ) {
3247 my $error = $job->update_statustext(
3248 int( 100 * $num / scalar(@cust_bill) )
3250 die $error if $error;
3261 =head1 CLASS METHODS
3267 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3272 my ($class, $start, $end) = @_;
3274 $class->paid_sql($start, $end). ' - '.
3275 $class->credited_sql($start, $end);
3280 Returns an SQL fragment to retreive the net amount (charged minus credited).
3285 my ($class, $start, $end) = @_;
3286 'charged - '. $class->credited_sql($start, $end);
3291 Returns an SQL fragment to retreive the amount paid against this invoice.
3296 my ($class, $start, $end) = @_;
3297 $start &&= "AND cust_bill_pay._date <= $start";
3298 $end &&= "AND cust_bill_pay._date > $end";
3299 $start = '' unless defined($start);
3300 $end = '' unless defined($end);
3301 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3302 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3307 Returns an SQL fragment to retreive the amount credited against this invoice.
3312 my ($class, $start, $end) = @_;
3313 $start &&= "AND cust_credit_bill._date <= $start";
3314 $end &&= "AND cust_credit_bill._date > $end";
3315 $start = '' unless defined($start);
3316 $end = '' unless defined($end);
3317 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3318 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3323 Returns an SQL fragment to retrieve the due date of an invoice.
3324 Currently only supported on PostgreSQL.
3329 my $conf = new FS::Conf;
3333 cust_bill.invoice_terms,
3334 cust_main.invoice_terms,
3335 \''.($conf->config('invoice_default_terms') || '').'\'
3336 ), E\'Net (\\\\d+)\'
3338 ) * 86400 + cust_bill._date'
3341 =item search_sql_where HASHREF
3343 Class method which returns an SQL WHERE fragment to search for parameters
3344 specified in HASHREF. Valid parameters are
3350 List reference of start date, end date, as UNIX timestamps.
3360 List reference of charged limits (exclusive).
3364 List reference of charged limits (exclusive).
3368 flag, return open invoices only
3372 flag, return net invoices only
3376 =item newest_percust
3380 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3384 sub search_sql_where {
3385 my($class, $param) = @_;
3387 warn "$me search_sql_where called with params: \n".
3388 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3394 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3395 push @search, "cust_main.agentnum = $1";
3399 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3400 push @search, "cust_main.refnum = $1";
3404 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3405 push @search, "cust_bill.custnum = $1";
3408 #customer classnum (false laziness w/ cust_main/Search.pm)
3409 if ( $param->{'cust_classnum'} ) {
3411 my @classnum = ref( $param->{'cust_classnum'} )
3412 ? @{ $param->{'cust_classnum'} }
3413 : ( $param->{'cust_classnum'} );
3415 @classnum = grep /^(\d*)$/, @classnum;
3418 push @search, '( '. join(' OR ', map {
3419 $_ ? "cust_main.classnum = $_"
3420 : "cust_main.classnum IS NULL"
3430 if ( $param->{_date} ) {
3431 my($beginning, $ending) = @{$param->{_date}};
3433 push @search, "cust_bill._date >= $beginning",
3434 "cust_bill._date < $ending";
3438 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3439 push @search, "cust_bill.invnum >= $1";
3441 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3442 push @search, "cust_bill.invnum <= $1";
3446 if ( $param->{charged} ) {
3447 my @charged = ref($param->{charged})
3448 ? @{ $param->{charged} }
3449 : ($param->{charged});
3451 push @search, map { s/^charged/cust_bill.charged/; $_; }
3455 my $owed_sql = FS::cust_bill->owed_sql;
3458 if ( $param->{owed} ) {
3459 my @owed = ref($param->{owed})
3460 ? @{ $param->{owed} }
3462 push @search, map { s/^owed/$owed_sql/; $_; }
3467 push @search, "0 != $owed_sql"
3468 if $param->{'open'};
3469 push @search, '0 != '. FS::cust_bill->net_sql
3473 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3474 if $param->{'days'};
3477 if ( $param->{'newest_percust'} ) {
3479 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3480 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3482 my @newest_where = map { my $x = $_;
3483 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3486 grep ! /^cust_main./, @search;
3487 my $newest_where = scalar(@newest_where)
3488 ? ' AND '. join(' AND ', @newest_where)
3492 push @search, "cust_bill._date = (
3493 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3494 WHERE newest_cust_bill.custnum = cust_bill.custnum
3500 #promised_date - also has an option to accept nulls
3501 if ( $param->{promised_date} ) {
3502 my($beginning, $ending, $null) = @{$param->{promised_date}};
3504 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3505 "cust_bill.promised_date < $ending )" .
3506 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3509 #agent virtualization
3510 my $curuser = $FS::CurrentUser::CurrentUser;
3511 if ( $curuser->username eq 'fs_queue'
3512 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3514 my $newuser = qsearchs('access_user', {
3515 'username' => $username,
3519 $curuser = $newuser;
3521 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3524 push @search, $curuser->agentnums_sql;
3526 join(' AND ', @search );
3538 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3539 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base