2 use base qw( FS::cust_bill::Search FS::Template_Mixin
3 FS::cust_main_Mixin FS::Record
7 use vars qw( $DEBUG $me );
9 use Fcntl qw(:flock); #for spool_csv
11 use List::Util qw(min max sum);
15 use Storable qw( freeze thaw );
17 use FS::UID qw( datasrc );
18 use FS::Misc qw( send_fax do_print );
19 use FS::Record qw( qsearch qsearchs dbh );
21 use FS::cust_statement;
22 use FS::cust_bill_pkg;
23 use FS::cust_bill_pkg_display;
24 use FS::cust_bill_pkg_detail;
28 use FS::cust_credit_bill;
30 use FS::cust_pay_batch;
31 use FS::cust_bill_event;
34 use FS::cust_bill_pay;
35 use FS::cust_bill_pay_batch;
36 use FS::part_bill_event;
39 use FS::cust_bill_batch;
40 use FS::cust_bill_pay_pkg;
41 use FS::cust_credit_bill_pkg;
42 use FS::discount_plan;
43 use FS::cust_bill_void;
47 $me = '[FS::cust_bill]';
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
109 =item billing_balance - the customer's balance immediately before generating
110 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
111 to determine the customer's balance at a specific time.
113 =item previous_balance - the customer's balance immediately after generating
114 the invoice before this one. DEPRECATED.
116 =item printed - formerly used to track the number of times an invoice had
117 been printed; no longer used.
125 =item closed - books closed flag, empty or `Y'
127 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
129 =item agent_invid - legacy invoice number
131 =item promised_date - customer promised payment date, for collection
141 Creates a new invoice. To add the invoice to the database, see L<"insert">.
142 Invoices are normally created by calling the bill method of a customer object
143 (see L<FS::cust_main>).
147 sub table { 'cust_bill'; }
149 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
150 # (except email_subject and invnum_date_pretty)
153 $self->conf->config('notice_name') || 'Invoice'
156 sub cust_linked { $_[0]->cust_main_custnum; }
157 sub cust_unlinked_msg {
159 "WARNING: can't find cust_main.custnum ". $self->custnum.
160 ' (cust_bill.invnum '. $self->invnum. ')';
165 Adds this invoice to the database ("Posts" the invoice). If there is an error,
166 returns the error, otherwise returns false.
172 warn "$me insert called\n" if $DEBUG;
174 local $SIG{HUP} = 'IGNORE';
175 local $SIG{INT} = 'IGNORE';
176 local $SIG{QUIT} = 'IGNORE';
177 local $SIG{TERM} = 'IGNORE';
178 local $SIG{TSTP} = 'IGNORE';
179 local $SIG{PIPE} = 'IGNORE';
181 my $oldAutoCommit = $FS::UID::AutoCommit;
182 local $FS::UID::AutoCommit = 0;
185 my $error = $self->SUPER::insert;
187 $dbh->rollback if $oldAutoCommit;
191 if ( $self->get('cust_bill_pkg') ) {
192 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
193 $cust_bill_pkg->invnum($self->invnum);
194 my $error = $cust_bill_pkg->insert;
196 $dbh->rollback if $oldAutoCommit;
197 return "can't create invoice line item: $error";
202 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
209 Voids this invoice: deletes the invoice and adds a record of the voided invoice
210 to the FS::cust_bill_void table (and related tables starting from
211 FS::cust_bill_pkg_void).
217 my $reason = scalar(@_) ? shift : '';
218 my $reprocess_cdrs = scalar(@_) ? shift : '';
220 local $SIG{HUP} = 'IGNORE';
221 local $SIG{INT} = 'IGNORE';
222 local $SIG{QUIT} = 'IGNORE';
223 local $SIG{TERM} = 'IGNORE';
224 local $SIG{TSTP} = 'IGNORE';
225 local $SIG{PIPE} = 'IGNORE';
227 my $oldAutoCommit = $FS::UID::AutoCommit;
228 local $FS::UID::AutoCommit = 0;
231 my $cust_bill_void = new FS::cust_bill_void ( {
232 map { $_ => $self->get($_) } $self->fields
234 $cust_bill_void->reason($reason);
235 my $error = $cust_bill_void->insert;
237 $dbh->rollback if $oldAutoCommit;
241 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
242 my $error = $cust_bill_pkg->void($reason, $reprocess_cdrs);
244 $dbh->rollback if $oldAutoCommit;
249 $error = $self->delete;
251 $dbh->rollback if $oldAutoCommit;
255 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
263 This method now works but you probably shouldn't use it. Instead, apply a
264 credit against the invoice, or use the new void method.
266 Using this method to delete invoices outright is really, really bad. There
267 would be no record you ever posted this invoice, and there are no check to
268 make sure charged = 0 or that there are no associated cust_bill_pkg records.
270 Really, don't use it.
276 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
278 local $SIG{HUP} = 'IGNORE';
279 local $SIG{INT} = 'IGNORE';
280 local $SIG{QUIT} = 'IGNORE';
281 local $SIG{TERM} = 'IGNORE';
282 local $SIG{TSTP} = 'IGNORE';
283 local $SIG{PIPE} = 'IGNORE';
285 my $oldAutoCommit = $FS::UID::AutoCommit;
286 local $FS::UID::AutoCommit = 0;
289 foreach my $table (qw(
300 foreach my $linked ( $self->$table() ) {
301 my $error = $linked->delete;
303 $dbh->rollback if $oldAutoCommit;
310 my $error = $self->SUPER::delete(@_);
312 $dbh->rollback if $oldAutoCommit;
316 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
322 =item replace [ OLD_RECORD ]
324 You can, but probably shouldn't modify invoices...
326 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
327 supplied, replaces this record. If there is an error, returns the error,
328 otherwise returns false.
332 #replace can be inherited from Record.pm
334 # replace_check is now the preferred way to #implement replace data checks
335 # (so $object->replace() works without an argument)
338 my( $new, $old ) = ( shift, shift );
339 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
340 #return "Can't change _date!" unless $old->_date eq $new->_date;
341 return "Can't change _date" unless $old->_date == $new->_date;
342 return "Can't change charged" unless $old->charged == $new->charged
343 || $old->charged == 0
344 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
350 =item add_cc_surcharge
356 sub add_cc_surcharge {
357 my ($self, $pkgnum, $amount) = (shift, shift, shift);
360 my $cust_bill_pkg = new FS::cust_bill_pkg({
361 'invnum' => $self->invnum,
365 $error = $cust_bill_pkg->insert;
366 return $error if $error;
368 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
369 $self->charged($self->charged+$amount);
370 $error = $self->replace;
371 return $error if $error;
373 $self->apply_payments_and_credits;
379 Checks all fields to make sure this is a valid invoice. If there is an error,
380 returns the error, otherwise returns false. Called by the insert and replace
389 $self->ut_numbern('invnum')
390 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
391 || $self->ut_numbern('_date')
392 || $self->ut_money('charged')
393 || $self->ut_numbern('printed')
394 || $self->ut_enum('closed', [ '', 'Y' ])
395 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
396 || $self->ut_numbern('agent_invid') #varchar?
398 return $error if $error;
400 $self->_date(time) unless $self->_date;
402 $self->printed(0) if $self->printed eq '';
409 Returns the displayed invoice number for this invoice: agent_invid if
410 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
416 if ( $self->agent_invid
417 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
418 return $self->agent_invid;
420 return $self->invnum;
426 Returns the customer's last invoice before this one.
432 if ( !$self->get('previous_bill') ) {
433 $self->set('previous_bill', qsearchs({
434 'table' => 'cust_bill',
435 'hashref' => { 'custnum' => $self->custnum,
436 '_date' => { op=>'<', value=>$self->_date } },
437 'order_by' => 'ORDER BY _date DESC LIMIT 1',
440 $self->get('previous_bill');
445 Returns a list consisting of the total previous balance for this customer,
446 followed by the previous outstanding invoices (as FS::cust_bill objects also).
452 # simple memoize; we use this a lot
453 if (!$self->get('previous')) {
455 my @cust_bill = sort { $a->_date <=> $b->_date }
456 grep { $_->owed != 0 }
457 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
458 #'_date' => { op=>'<', value=>$self->_date },
459 'invnum' => { op=>'<', value=>$self->invnum },
462 foreach ( @cust_bill ) { $total += $_->owed; }
463 $self->set('previous', [$total, @cust_bill]);
465 return @{ $self->get('previous') };
468 =item enable_previous
470 Whether to show the 'Previous Charges' section when printing this invoice.
471 The negation of the 'disable_previous_balance' config setting.
475 sub enable_previous {
477 my $agentnum = $self->cust_main->agentnum;
478 !$self->conf->exists('disable_previous_balance', $agentnum);
483 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
490 { 'table' => 'cust_bill_pkg',
491 'hashref' => { 'invnum' => $self->invnum },
492 'order_by' => 'ORDER BY billpkgnum',
497 =item cust_bill_pkg_pkgnum PKGNUM
499 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
504 sub cust_bill_pkg_pkgnum {
505 my( $self, $pkgnum ) = @_;
507 { 'table' => 'cust_bill_pkg',
508 'hashref' => { 'invnum' => $self->invnum,
511 'order_by' => 'ORDER BY billpkgnum',
518 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
525 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
526 $self->cust_bill_pkg;
528 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
533 Returns true if any of the packages (or their definitions) corresponding to the
534 line items for this invoice have the no_auto flag set.
540 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
543 =item open_cust_bill_pkg
545 Returns the open line items for this invoice.
547 Note that cust_bill_pkg with both setup and recur fees are returned as two
548 separate line items, each with only one fee.
552 # modeled after cust_main::open_cust_bill
553 sub open_cust_bill_pkg {
556 # grep { $_->owed > 0 } $self->cust_bill_pkg
558 my %other = ( 'recur' => 'setup',
559 'setup' => 'recur', );
561 foreach my $field ( qw( recur setup )) {
562 push @open, map { $_->set( $other{$field}, 0 ); $_; }
563 grep { $_->owed($field) > 0 }
564 $self->cust_bill_pkg;
570 =item cust_bill_event
572 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
576 sub cust_bill_event {
578 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
581 =item num_cust_bill_event
583 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
587 sub num_cust_bill_event {
590 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
591 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
592 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
593 $sth->fetchrow_arrayref->[0];
598 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
602 #false laziness w/cust_pkg.pm
606 'table' => 'cust_event',
607 'addl_from' => 'JOIN part_event USING ( eventpart )',
608 'hashref' => { 'tablenum' => $self->invnum },
609 'extra_sql' => " AND eventtable = 'cust_bill' ",
615 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
619 #false laziness w/cust_pkg.pm
623 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
624 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
625 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
626 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
627 $sth->fetchrow_arrayref->[0];
632 Returns the customer (see L<FS::cust_main>) for this invoice.
638 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
641 =item cust_suspend_if_balance_over AMOUNT
643 Suspends the customer associated with this invoice if the total amount owed on
644 this invoice and all older invoices is greater than the specified amount.
646 Returns a list: an empty list on success or a list of errors.
650 sub cust_suspend_if_balance_over {
651 my( $self, $amount ) = ( shift, shift );
652 my $cust_main = $self->cust_main;
653 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
656 $cust_main->suspend(@_);
662 Depreciated. See the cust_credited method.
664 #Returns a list consisting of the total previous credited (see
665 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
666 #outstanding credits (FS::cust_credit objects).
672 croak "FS::cust_bill->cust_credit depreciated; see ".
673 "FS::cust_bill->cust_credit_bill";
676 #my @cust_credit = sort { $a->_date <=> $b->_date }
677 # grep { $_->credited != 0 && $_->_date < $self->_date }
678 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
680 #foreach (@cust_credit) { $total += $_->credited; }
681 #$total, @cust_credit;
686 Depreciated. See the cust_bill_pay method.
688 #Returns all payments (see L<FS::cust_pay>) for this invoice.
694 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
696 #sort { $a->_date <=> $b->_date }
697 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
703 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
706 sub cust_bill_pay_batch {
708 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
713 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
719 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
720 sort { $a->_date <=> $b->_date }
721 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
726 =item cust_credit_bill
728 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
734 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
735 sort { $a->_date <=> $b->_date }
736 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
740 sub cust_credit_bill {
741 shift->cust_credited(@_);
744 #=item cust_bill_pay_pkgnum PKGNUM
746 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
747 #with matching pkgnum.
751 #sub cust_bill_pay_pkgnum {
752 # my( $self, $pkgnum ) = @_;
753 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
754 # sort { $a->_date <=> $b->_date }
755 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
756 # 'pkgnum' => $pkgnum,
761 =item cust_bill_pay_pkg PKGNUM
763 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
764 applied against the matching pkgnum.
768 sub cust_bill_pay_pkg {
769 my( $self, $pkgnum ) = @_;
772 'select' => 'cust_bill_pay_pkg.*',
773 'table' => 'cust_bill_pay_pkg',
774 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
775 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
776 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
777 " AND cust_bill_pkg.pkgnum = $pkgnum",
782 #=item cust_credited_pkgnum PKGNUM
784 #=item cust_credit_bill_pkgnum PKGNUM
786 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
787 #with matching pkgnum.
791 #sub cust_credited_pkgnum {
792 # my( $self, $pkgnum ) = @_;
793 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
794 # sort { $a->_date <=> $b->_date }
795 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
796 # 'pkgnum' => $pkgnum,
801 #sub cust_credit_bill_pkgnum {
802 # shift->cust_credited_pkgnum(@_);
805 =item cust_credit_bill_pkg PKGNUM
807 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
808 applied against the matching pkgnum.
812 sub cust_credit_bill_pkg {
813 my( $self, $pkgnum ) = @_;
816 'select' => 'cust_credit_bill_pkg.*',
817 'table' => 'cust_credit_bill_pkg',
818 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
819 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
820 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
821 " AND cust_bill_pkg.pkgnum = $pkgnum",
826 =item cust_bill_batch
828 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
832 sub cust_bill_batch {
834 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
839 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
840 hash keyed by term length.
846 FS::discount_plan->all($self);
851 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
858 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
860 foreach (@taxlines) { $total += $_->setup; }
866 Returns the amount owed (still outstanding) on this invoice, which is charged
867 minus all payment applications (see L<FS::cust_bill_pay>) and credit
868 applications (see L<FS::cust_credit_bill>).
874 my $balance = $self->charged;
875 $balance -= $_->amount foreach ( $self->cust_bill_pay );
876 $balance -= $_->amount foreach ( $self->cust_credited );
877 $balance = sprintf( "%.2f", $balance);
878 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
883 my( $self, $pkgnum ) = @_;
885 #my $balance = $self->charged;
887 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
889 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
890 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
892 $balance = sprintf( "%.2f", $balance);
893 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
899 Returns true if this invoice should be hidden. See the
900 selfservice-hide_invoices-taxclass configuraiton setting.
906 my $conf = $self->conf;
907 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
909 my @cust_bill_pkg = $self->cust_bill_pkg;
910 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
911 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
914 =item apply_payments_and_credits [ OPTION => VALUE ... ]
916 Applies unapplied payments and credits to this invoice.
917 Payments with the no_auto_apply flag set will not be applied.
919 A hash of optional arguments may be passed. Currently "manual" is supported.
920 If true, a payment receipt is sent instead of a statement when
921 'payment_receipt_email' configuration option is set.
923 If there is an error, returns the error, otherwise returns false.
927 sub apply_payments_and_credits {
928 my( $self, %options ) = @_;
929 my $conf = $self->conf;
931 local $SIG{HUP} = 'IGNORE';
932 local $SIG{INT} = 'IGNORE';
933 local $SIG{QUIT} = 'IGNORE';
934 local $SIG{TERM} = 'IGNORE';
935 local $SIG{TSTP} = 'IGNORE';
936 local $SIG{PIPE} = 'IGNORE';
938 my $oldAutoCommit = $FS::UID::AutoCommit;
939 local $FS::UID::AutoCommit = 0;
942 $self->select_for_update; #mutex
944 my @payments = grep { $_->unapplied > 0 }
945 grep { !$_->no_auto_apply }
946 $self->cust_main->cust_pay;
947 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
949 if ( $conf->exists('pkg-balances') ) {
950 # limit @payments & @credits to those w/ a pkgnum grepped from $self
951 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
952 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
953 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
956 while ( $self->owed > 0 and ( @payments || @credits ) ) {
959 if ( @payments && @credits ) {
961 #decide which goes first by weight of top (unapplied) line item
963 my @open_lineitems = $self->open_cust_bill_pkg;
966 max( map { $_->part_pkg->pay_weight || 0 }
971 my $max_credit_weight =
972 max( map { $_->part_pkg->credit_weight || 0 }
978 #if both are the same... payments first? it has to be something
979 if ( $max_pay_weight >= $max_credit_weight ) {
985 } elsif ( @payments ) {
987 } elsif ( @credits ) {
990 die "guru meditation #12 and 35";
994 if ( $app eq 'pay' ) {
996 my $payment = shift @payments;
997 $unapp_amount = $payment->unapplied;
998 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
999 $app->pkgnum( $payment->pkgnum )
1000 if $conf->exists('pkg-balances') && $payment->pkgnum;
1002 } elsif ( $app eq 'credit' ) {
1004 my $credit = shift @credits;
1005 $unapp_amount = $credit->credited;
1006 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1007 $app->pkgnum( $credit->pkgnum )
1008 if $conf->exists('pkg-balances') && $credit->pkgnum;
1011 die "guru meditation #12 and 35";
1015 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1016 warn "owed_pkgnum ". $app->pkgnum;
1017 $owed = $self->owed_pkgnum($app->pkgnum);
1019 $owed = $self->owed;
1021 next unless $owed > 0;
1023 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1024 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1026 $app->invnum( $self->invnum );
1028 my $error = $app->insert(%options);
1030 $dbh->rollback if $oldAutoCommit;
1031 return "Error inserting ". $app->table. " record: $error";
1033 die $error if $error;
1037 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1044 Sends this invoice to the destinations configured for this customer: sends
1045 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1047 Options can be passed as a hashref. Positional parameters are no longer
1050 I<template>: a suffix for alternate invoices
1052 I<agentnum>: obsolete, now does nothing.
1054 I<from> overrides the default email invoice From: address.
1056 I<amount>: obsolete, does nothing
1058 I<notice_name> overrides "Invoice" as the name of the sent document
1059 (templates from 10/2009 or newer required).
1061 I<lpr> overrides the system 'lpr' option as the command to print a document
1062 from standard input.
1068 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1069 my $conf = $self->conf;
1071 my $cust_main = $self->cust_main;
1073 my @invoicing_list = $cust_main->invoicing_list;
1076 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1077 && ! $cust_main->invoice_noemail;
1080 if grep { $_ eq 'POST' } @invoicing_list; #postal
1082 #this has never been used post-$ORIGINAL_ISP afaik
1083 $self->fax_invoice($opt)
1084 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1092 my $opt = shift || {};
1093 if ($opt and !ref($opt)) {
1094 die ref($self). '->email called with positional parameters';
1097 my $conf = $self->conf;
1099 my $from = delete $opt->{from};
1101 # this is where we set the From: address
1102 $from ||= $self->_agent_invoice_from || #XXX should go away
1103 $conf->invoice_from_full( $self->cust_main->agentnum );
1105 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1107 if ( ! @invoicing_list ) { #no recipients
1108 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1109 die 'No recipients for customer #'. $self->custnum;
1111 #default: better to notify this person than silence
1112 @invoicing_list = ($from);
1116 $self->SUPER::email( {
1118 'to' => \@invoicing_list,
1124 #this stays here for now because its explicitly used as
1125 # FS::cust_bill::queueable_email
1126 sub queueable_email {
1129 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1130 or die "invalid invoice number: " . $opt{invnum};
1132 $self->set('mode', $opt{mode})
1135 my %args = map {$_ => $opt{$_}}
1137 qw( from notice_name no_coupon template );
1139 my $error = $self->email( \%args );
1140 die $error if $error;
1146 my $conf = $self->conf;
1148 #my $template = scalar(@_) ? shift : '';
1151 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1154 my $cust_main = $self->cust_main;
1155 my $name = $cust_main->name;
1156 my $name_short = $cust_main->name_short;
1157 my $invoice_number = $self->invnum;
1158 my $invoice_date = $self->_date_pretty;
1160 eval qq("$subject");
1163 =item lpr_data HASHREF
1165 Returns the postscript or plaintext for this invoice as an arrayref.
1167 Options must be passed as a hashref. Positional parameters are no longer
1170 I<template>, if specified, is the name of a suffix for alternate invoices.
1172 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1178 my $conf = $self->conf;
1179 my $opt = shift || {};
1180 if ($opt and !ref($opt)) {
1181 # nobody does this anyway
1182 die "FS::cust_bill::lpr_data called with positional parameters";
1185 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1186 [ $self->$method( $opt ) ];
1191 Prints this invoice.
1193 Options must be passed as a hashref.
1195 I<template>, if specified, is the name of a suffix for alternate invoices.
1197 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1203 return if $self->hide;
1204 my $conf = $self->conf;
1205 my $opt = shift || {};
1206 if ($opt and !ref($opt)) {
1207 die "FS::cust_bill::print called with positional parameters";
1210 my $lpr = delete $opt->{lpr};
1211 if($conf->exists('invoice_print_pdf')) {
1212 # Add the invoice to the current batch.
1213 $self->batch_invoice($opt);
1217 $self->lpr_data($opt),
1218 'agentnum' => $self->cust_main->agentnum,
1224 =item fax_invoice HASHREF
1228 Options must be passed as a hashref.
1230 I<template>, if specified, is the name of a suffix for alternate invoices.
1232 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1238 return if $self->hide;
1239 my $conf = $self->conf;
1240 my $opt = shift || {};
1241 if ($opt and !ref($opt)) {
1242 die "FS::cust_bill::fax_invoice called with positional parameters";
1245 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1246 unless $conf->exists('invoice_latex');
1248 my $dialstring = $self->cust_main->getfield('fax');
1251 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1252 'dialstring' => $dialstring,
1254 die $error if $error;
1258 =item batch_invoice [ HASHREF ]
1260 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1261 isn't an open batch, one will be created.
1263 HASHREF may contain any options to be passed to C<print_pdf>.
1268 my ($self, $opt) = @_;
1269 my $bill_batch = $self->get_open_bill_batch;
1270 my $cust_bill_batch = FS::cust_bill_batch->new({
1271 batchnum => $bill_batch->batchnum,
1272 invnum => $self->invnum,
1274 if ( $self->mode ) {
1275 $opt->{mode} ||= $self->mode;
1276 $opt->{mode} = $opt->{mode}->modenum if ref $opt->{mode};
1278 return $cust_bill_batch->insert($opt);
1281 =item get_open_batch
1283 Returns the currently open batch as an FS::bill_batch object, creating a new
1284 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1289 sub get_open_bill_batch {
1291 my $conf = $self->conf;
1292 my $hashref = { status => 'O' };
1293 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1294 ? $self->cust_main->agentnum
1296 my $batch = qsearchs('bill_batch', $hashref);
1297 return $batch if $batch;
1298 $batch = FS::bill_batch->new($hashref);
1299 my $error = $batch->insert;
1300 die $error if $error;
1304 =item ftp_invoice [ TEMPLATENAME ]
1306 Sends this invoice data via FTP.
1308 TEMPLATENAME is unused?
1314 my $conf = $self->conf;
1315 my $template = scalar(@_) ? shift : '';
1318 'protocol' => 'ftp',
1319 'server' => $conf->config('cust_bill-ftpserver'),
1320 'username' => $conf->config('cust_bill-ftpusername'),
1321 'password' => $conf->config('cust_bill-ftppassword'),
1322 'dir' => $conf->config('cust_bill-ftpdir'),
1323 'format' => $conf->config('cust_bill-ftpformat'),
1327 =item spool_invoice [ TEMPLATENAME ]
1329 Spools this invoice data (see L<FS::spool_csv>)
1331 TEMPLATENAME is unused?
1337 my $conf = $self->conf;
1338 my $template = scalar(@_) ? shift : '';
1341 'format' => $conf->config('cust_bill-spoolformat'),
1342 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1346 =item send_csv OPTION => VALUE, ...
1348 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1352 protocol - currently only "ftp"
1358 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1359 and YYMMDDHHMMSS is a timestamp.
1361 See L</print_csv> for a description of the output format.
1366 my($self, %opt) = @_;
1370 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1371 mkdir $spooldir, 0700 unless -d $spooldir;
1373 # don't localize dates here, they're a defined format
1374 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1375 my $file = "$spooldir/$tracctnum.csv";
1377 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1379 open(CSV, ">$file") or die "can't open $file: $!";
1387 if ( $opt{protocol} eq 'ftp' ) {
1388 eval "use Net::FTP;";
1390 $net = Net::FTP->new($opt{server}) or die @$;
1392 die "unknown protocol: $opt{protocol}";
1395 $net->login( $opt{username}, $opt{password} )
1396 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1398 $net->binary or die "can't set binary mode";
1400 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1402 $net->put($file) or die "can't put $file: $!";
1412 Spools CSV invoice data.
1418 =item format - any of FS::Misc::::Invoicing::spool_formats
1420 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1421 customer has the corresponding invoice destinations set (see
1422 L<FS::cust_main_invoice>).
1424 =item agent_spools - if set to a true value, will spool to per-agent files
1425 rather than a single global file
1427 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1428 append to that spool. L<FS::Cron::upload> will then send the spool file to
1431 =item balanceover - if set, only spools the invoice if the total amount owed on
1432 this invoice and all older invoices is greater than the specified amount.
1434 =item time - the "current time". Controls the printing of past due messages
1442 my($self, %opt) = @_;
1444 my $time = $opt{'time'} || time;
1445 my $cust_main = $self->cust_main;
1447 if ( $opt{'dest'} ) {
1448 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1449 $cust_main->invoicing_list;
1450 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1451 || ! keys %invoicing_list;
1454 if ( $opt{'balanceover'} ) {
1456 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1459 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1460 mkdir $spooldir, 0700 unless -d $spooldir;
1462 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1465 if ( $opt{'agent_spools'} ) {
1466 $file = 'agentnum'.$cust_main->agentnum;
1471 if ( $opt{'upload_targetnum'} ) {
1472 $spooldir .= '/target'.$opt{'upload_targetnum'};
1473 mkdir $spooldir, 0700 unless -d $spooldir;
1474 } # otherwise it just goes into export.xxx/cust_bill
1476 if ( lc($opt{'format'}) eq 'billco' ) {
1480 $file = "$spooldir/$file.csv";
1482 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1484 open(CSV, ">>$file") or die "can't open $file: $!";
1485 flock(CSV, LOCK_EX);
1490 if ( lc($opt{'format'}) eq 'billco' ) {
1492 flock(CSV, LOCK_UN);
1495 $file =~ s/-header.csv$/-detail.csv/;
1497 open(CSV,">>$file") or die "can't open $file: $!";
1498 flock(CSV, LOCK_EX);
1502 print CSV $detail if defined($detail);
1504 flock(CSV, LOCK_UN);
1511 =item print_csv OPTION => VALUE, ...
1513 Returns CSV data for this invoice.
1517 format - 'default', 'billco', 'oneline', 'bridgestone'
1519 Returns a list consisting of two scalars. The first is a single line of CSV
1520 header information for this invoice. The second is one or more lines of CSV
1521 detail information for this invoice.
1523 If I<format> is not specified or "default", the fields of the CSV file are as
1526 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1527 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1531 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1533 B<record_type> is C<cust_bill> for the initial header line only. The
1534 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1535 fields are filled in.
1537 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1538 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1541 =item invnum - invoice number
1543 =item custnum - customer number
1545 =item _date - invoice date
1547 =item charged - total invoice amount
1549 =item first - customer first name
1551 =item last - customer first name
1553 =item company - company name
1555 =item address1 - address line 1
1557 =item address2 - address line 1
1567 =item pkg - line item description
1569 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1571 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1573 =item sdate - start date for recurring fee
1575 =item edate - end date for recurring fee
1579 If I<format> is "billco", the fields of the header CSV file are as follows:
1581 +-------------------------------------------------------------------+
1582 | FORMAT HEADER FILE |
1583 |-------------------------------------------------------------------|
1584 | Field | Description | Name | Type | Width |
1585 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1586 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1587 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1588 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1589 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1590 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1591 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1592 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1593 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1594 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1595 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1596 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1597 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1598 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1599 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1600 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1601 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1602 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1603 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1604 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1605 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1606 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1607 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1608 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1609 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1610 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1611 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1612 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1613 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1614 +-------+-------------------------------+------------+------+-------+
1616 If I<format> is "billco", the fields of the detail CSV file are as follows:
1618 FORMAT FOR DETAIL FILE
1620 Field | Description | Name | Type | Width
1621 1 | N/A-Leave Empty | RC | CHAR | 2
1622 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1623 3 | Account Number | TRACCTNUM | CHAR | 15
1624 4 | Invoice Number | TRINVOICE | CHAR | 15
1625 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1626 6 | Transaction Detail | DETAILS | CHAR | 100
1627 7 | Amount | AMT | NUM* | 9
1628 8 | Line Format Control** | LNCTRL | CHAR | 2
1629 9 | Grouping Code | GROUP | CHAR | 2
1630 10 | User Defined | ACCT CODE | CHAR | 15
1632 If format is 'oneline', there is no detail file. Each invoice has a
1633 header line only, with the fields:
1635 Agent number, agent name, customer number, first name, last name, address
1636 line 1, address line 2, city, state, zip, invoice date, invoice number,
1637 amount charged, amount due, previous balance, due date.
1639 and then, for each line item, three columns containing the package number,
1640 description, and amount.
1642 If format is 'bridgestone', there is no detail file. Each invoice has a
1643 header line with the following fields in a fixed-width format:
1645 Customer number (in display format), date, name (first last), company,
1646 address 1, address 2, city, state, zip.
1648 This is a mailing list format, and has no per-invoice fields. To avoid
1649 sending redundant notices, the spooling event should have a "once" or
1650 "once_percust_every" condition.
1655 my($self, %opt) = @_;
1657 eval "use Text::CSV_XS";
1660 my $cust_main = $self->cust_main;
1662 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1663 my $format = lc($opt{'format'});
1665 my $time = $opt{'time'} || time;
1667 my $tracctnum = ''; #leaking out from billco-specific sections :/
1668 if ( $format eq 'billco' ) {
1671 $self->conf->config('billco-account_num', $cust_main->agentnum);
1673 $tracctnum = $account_num eq 'display_custnum'
1674 ? $cust_main->display_custnum
1675 : $opt{'tracctnum'};
1678 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1680 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1682 my( $previous_balance, @unused ) = $self->previous; #previous balance
1684 my $pmt_cr_applied = 0;
1685 $pmt_cr_applied += $_->{'amount'}
1686 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1688 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1691 '', # 1 | N/A-Leave Empty CHAR 2
1692 '', # 2 | N/A-Leave Empty CHAR 15
1693 $tracctnum, # 3 | Transaction Account No CHAR 15
1694 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1695 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1696 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1697 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1698 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1699 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1700 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1701 '', # 10 | Ancillary Billing Information CHAR 30
1702 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1703 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1706 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1709 $duedate, # 14 | Bill Due Date CHAR 10
1711 $previous_balance, # 15 | Previous Balance NUM* 9
1712 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1713 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1714 $totaldue, # 18 | Total Amt Due NUM* 9
1715 $totaldue, # 19 | Total Amt Due NUM* 9
1716 '', # 20 | 30 Day Aging NUM* 9
1717 '', # 21 | 60 Day Aging NUM* 9
1718 '', # 22 | 90 Day Aging NUM* 9
1719 'N', # 23 | Y/N CHAR 1
1720 '', # 24 | Remittance automation CHAR 100
1721 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1722 $self->custnum, # 26 | Customer Reference Number CHAR 15
1723 '0', # 27 | Federal Tax*** NUM* 9
1724 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1725 '0', # 29 | Other Taxes & Fees*** NUM* 9
1728 } elsif ( $format eq 'oneline' ) { #name
1730 my ($previous_balance) = $self->previous;
1731 $previous_balance = sprintf('%.2f', $previous_balance);
1732 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1738 $self->_items_pkg, #_items_nontax? no sections or anything
1743 $cust_main->agentnum,
1744 $cust_main->agent->agent,
1748 $cust_main->company,
1749 $cust_main->address1,
1750 $cust_main->address2,
1756 time2str("%x", $self->_date),
1761 $self->due_date2str("%x"),
1766 } elsif ( $format eq 'bridgestone' ) {
1768 # bypass the CSV stuff and just return this
1769 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1770 my $zip = $cust_main->zip;
1772 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1776 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1778 $cust_main->display_custnum,
1780 uc(substr($cust_main->contact_firstlast,0,30)),
1781 uc(substr($cust_main->company ,0,30)),
1782 uc(substr($cust_main->address1 ,0,30)),
1783 uc(substr($cust_main->address2 ,0,30)),
1784 uc(substr($cust_main->city ,0,20)),
1785 uc($cust_main->state),
1791 } elsif ( $format eq 'ics' ) {
1793 my $bill = $cust_main->bill_location;
1794 my $zip = $bill->zip;
1798 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1803 # minor false laziness with print_generic
1804 my ($previous_balance) = $self->previous;
1805 my $balance_due = $self->owed + $previous_balance;
1806 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1807 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1810 if ( $self->due_date and $time >= $self->due_date ) {
1811 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1815 my $header = sprintf(
1816 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1817 $cust_main->display_custnum, #BID
1818 uc($cust_main->first), #FNAME
1819 uc($cust_main->last), #LNAME
1820 '00', #BATCH, should this ever be anything else?
1821 uc($cust_main->company), #COMP
1822 uc($bill->address1), #STREET1
1823 uc($bill->address2), #STREET2
1824 uc($bill->city), #CITY
1825 uc($bill->state), #STATE
1828 time2str('%Y%m%d', $self->_date), #BILL_DATE
1829 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1830 ( map {sprintf('%0.2f', $_)}
1831 $balance_due, #AMNT_DUE
1832 $previous_balance, #PREV_BAL
1833 $payment_total, #PYMT_RCVD
1834 $credit_total, #CREDITS
1835 $previous_balance, #BEG_BAL--is this correct?
1836 $self->charged, #NEW_CHRG
1839 $past_due, #PAST_MSG
1843 my %svc_class = ('' => ''); # maybe cache this more persistently?
1845 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1847 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1848 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1852 my @dates = ( $self->_date, undef );
1853 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1854 $dates[1] = $prev->sdate; #questionable
1857 # generate an 01 detail for each service
1858 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1859 foreach my $cust_svc ( @svcs ) {
1860 $show_pkgnum = ''; # hide it if we're showing svcnums
1862 my $svcpart = $cust_svc->svcpart;
1863 if (!exists($svc_class{$svcpart})) {
1864 my $classnum = $cust_svc->part_svc->classnum;
1865 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1867 $svc_class{$svcpart} = $part_svc_class ?
1868 $part_svc_class->classname :
1872 my @h_label = $cust_svc->label(@dates, 'I');
1873 push @details, sprintf('01%-9s%-20s%-47s',
1875 $svc_class{$svcpart},
1878 } #foreach $cust_svc
1881 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1882 if ($cust_bill_pkg->recur > 0) {
1883 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1884 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1886 push @details, sprintf('02%-6s%-60s%-10s',
1889 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1891 } #foreach $cust_bill_pkg
1893 # Tag this row so that we know whether this is one page (1), two pages
1894 # (2), # or "big" (B). The tag will be stripped off before uploading.
1895 if ( scalar(@details) < 12 ) {
1897 } elsif ( scalar(@details) < 58 ) {
1903 return join('', $header, @details, "\n");
1911 time2str("%x", $self->_date),
1912 sprintf("%.2f", $self->charged),
1913 ( map { $cust_main->getfield($_) }
1914 qw( first last company address1 address2 city state zip country ) ),
1916 ) or die "can't create csv";
1919 my $header = $csv->string. "\n";
1922 if ( lc($opt{'format'}) eq 'billco' ) {
1925 my %items_opt = ( format => 'template',
1926 escape_function => sub { shift } );
1927 # I don't know what characters billco actually tolerates in spool entries.
1928 # Text::CSV will take care of delimiters, though.
1930 my @items = ( $self->_items_pkg(%items_opt),
1931 $self->_items_fee(%items_opt) );
1932 foreach my $item (@items) {
1934 my $description = $item->{'description'};
1935 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1936 $description .= ': ' . $item->{ext_description}[0];
1940 '', # 1 | N/A-Leave Empty CHAR 2
1941 '', # 2 | N/A-Leave Empty CHAR 15
1942 $tracctnum, # 3 | Account Number CHAR 15
1943 $self->invnum, # 4 | Invoice Number CHAR 15
1944 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1945 $description, # 6 | Transaction Detail CHAR 100
1946 $item->{'amount'}, # 7 | Amount NUM* 9
1947 '', # 8 | Line Format Control** CHAR 2
1948 '', # 9 | Grouping Code CHAR 2
1949 '', # 10 | User Defined CHAR 15
1952 $detail .= $csv->string. "\n";
1956 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1962 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1964 my($pkg, $setup, $recur, $sdate, $edate);
1965 if ( $cust_bill_pkg->pkgnum ) {
1967 ($pkg, $setup, $recur, $sdate, $edate) = (
1968 $cust_bill_pkg->part_pkg->pkg,
1969 ( $cust_bill_pkg->setup != 0
1970 ? sprintf("%.2f", $cust_bill_pkg->setup )
1972 ( $cust_bill_pkg->recur != 0
1973 ? sprintf("%.2f", $cust_bill_pkg->recur )
1975 ( $cust_bill_pkg->sdate
1976 ? time2str("%x", $cust_bill_pkg->sdate)
1978 ($cust_bill_pkg->edate
1979 ? time2str("%x", $cust_bill_pkg->edate)
1983 } else { #pkgnum tax
1984 next unless $cust_bill_pkg->setup != 0;
1985 $pkg = $cust_bill_pkg->desc;
1986 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1987 ( $sdate, $edate ) = ( '', '' );
1993 ( map { '' } (1..11) ),
1994 ($pkg, $setup, $recur, $sdate, $edate)
1995 ) or die "can't create csv";
1997 $detail .= $csv->string. "\n";
2003 ( $header, $detail );
2009 Pays this invoice with a compliemntary payment. If there is an error,
2010 returns the error, otherwise returns false.
2016 my $cust_pay = new FS::cust_pay ( {
2017 'invnum' => $self->invnum,
2018 'paid' => $self->owed,
2021 'payinfo' => $self->cust_main->payinfo,
2029 Attempts to pay this invoice with a credit card payment via a
2030 Business::OnlinePayment realtime gateway. See
2031 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2032 for supported processors.
2038 $self->realtime_bop( 'CC', @_ );
2043 Attempts to pay this invoice with an electronic check (ACH) payment via a
2044 Business::OnlinePayment realtime gateway. See
2045 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2046 for supported processors.
2052 $self->realtime_bop( 'ECHECK', @_ );
2057 Attempts to pay this invoice with phone bill (LEC) payment via a
2058 Business::OnlinePayment realtime gateway. See
2059 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2060 for supported processors.
2066 $self->realtime_bop( 'LEC', @_ );
2070 my( $self, $method ) = (shift,shift);
2071 my $conf = $self->conf;
2074 my $cust_main = $self->cust_main;
2075 my $balance = $cust_main->balance;
2076 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2077 $amount = sprintf("%.2f", $amount);
2078 return "not run (balance $balance)" unless $amount > 0;
2080 my $description = 'Internet Services';
2081 if ( $conf->exists('business-onlinepayment-description') ) {
2082 my $dtempl = $conf->config('business-onlinepayment-description');
2084 my $agent_obj = $cust_main->agent
2085 or die "can't retreive agent for $cust_main (agentnum ".
2086 $cust_main->agentnum. ")";
2087 my $agent = $agent_obj->agent;
2088 my $pkgs = join(', ',
2089 map { $_->part_pkg->pkg }
2090 grep { $_->pkgnum } $self->cust_bill_pkg
2092 $description = eval qq("$dtempl");
2095 $cust_main->realtime_bop($method, $amount,
2096 'description' => $description,
2097 'invnum' => $self->invnum,
2098 #this didn't do what we want, it just calls apply_payments_and_credits
2100 'apply_to_invoice' => 1,
2103 #this changes application behavior: auto payments
2104 #triggered against a specific invoice are now applied
2105 #to that invoice instead of oldest open.
2111 =item batch_card OPTION => VALUE...
2113 Adds a payment for this invoice to the pending credit card batch (see
2114 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2115 runs the payment using a realtime gateway.
2120 my ($self, %options) = @_;
2121 my $cust_main = $self->cust_main;
2123 $options{invnum} = $self->invnum;
2125 $cust_main->batch_card(%options);
2128 sub _agent_template {
2130 $self->cust_main->agent_template;
2133 sub _agent_invoice_from {
2135 $self->cust_main->agent_invoice_from;
2138 =item invoice_barcode DIR_OR_FALSE
2140 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2141 it is taken as the temp directory where the PNG file will be generated and the
2142 PNG file name is returned. Otherwise, the PNG image itself is returned.
2146 sub invoice_barcode {
2147 my ($self, $dir) = (shift,shift);
2149 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2150 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2151 my $gd = $gdbar->plot(Height => 30);
2154 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2158 ) or die "can't open temp file: $!\n";
2159 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2160 my $png_file = $bh->filename;
2167 =item invnum_date_pretty
2169 Returns a string with the invoice number and date, for example:
2170 "Invoice #54 (3/20/2008)".
2172 Intended for back-end context, with regard to translation and date formatting.
2176 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2177 # for backend use (and also does the wrong thing, localizing for end customer
2178 # instead of backoffice configured date format)
2179 sub invnum_date_pretty {
2181 #$self->mt('Invoice #').
2182 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2183 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2186 #sub _items_extra_usage_sections {
2188 # my $escape = shift;
2190 # my %sections = ();
2192 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2193 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2195 # next unless $cust_bill_pkg->pkgnum > 0;
2197 # foreach my $section ( keys %usage_class ) {
2199 # my $usage = $cust_bill_pkg->usage($section);
2201 # next unless $usage && $usage > 0;
2203 # $sections{$section} ||= 0;
2204 # $sections{$section} += $usage;
2210 # map { { 'description' => &{$escape}($_),
2211 # 'subtotal' => $sections{$_},
2212 # 'summarized' => '',
2213 # 'tax_section' => '',
2216 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2220 sub _items_extra_usage_sections {
2222 my $conf = $self->conf;
2230 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2232 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2233 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2234 next unless $cust_bill_pkg->pkgnum > 0;
2236 foreach my $classnum ( keys %usage_class ) {
2237 my $section = $usage_class{$classnum}->classname;
2238 $classnums{$section} = $classnum;
2240 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2241 my $amount = $detail->amount;
2242 next unless $amount && $amount > 0;
2244 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2245 $sections{$section}{amount} += $amount; #subtotal
2246 $sections{$section}{calls}++;
2247 $sections{$section}{duration} += $detail->duration;
2249 my $desc = $detail->regionname;
2250 my $description = $desc;
2251 $description = substr($desc, 0, $maxlength). '...'
2252 if $format eq 'latex' && length($desc) > $maxlength;
2254 $lines{$section}{$desc} ||= {
2255 description => &{$escape}($description),
2256 #pkgpart => $part_pkg->pkgpart,
2257 pkgnum => $cust_bill_pkg->pkgnum,
2262 #unit_amount => $cust_bill_pkg->unitrecur,
2263 quantity => $cust_bill_pkg->quantity,
2264 product_code => 'N/A',
2265 ext_description => [],
2268 $lines{$section}{$desc}{amount} += $amount;
2269 $lines{$section}{$desc}{calls}++;
2270 $lines{$section}{$desc}{duration} += $detail->duration;
2276 my %sectionmap = ();
2277 foreach (keys %sections) {
2278 my $usage_class = $usage_class{$classnums{$_}};
2279 $sectionmap{$_} = { 'description' => &{$escape}($_),
2280 'amount' => $sections{$_}{amount}, #subtotal
2281 'calls' => $sections{$_}{calls},
2282 'duration' => $sections{$_}{duration},
2284 'tax_section' => '',
2285 'sort_weight' => $usage_class->weight,
2286 ( $usage_class->format
2287 ? ( map { $_ => $usage_class->$_($format) }
2288 qw( description_generator header_generator total_generator total_line_generator )
2295 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2299 foreach my $section ( keys %lines ) {
2300 foreach my $line ( keys %{$lines{$section}} ) {
2301 my $l = $lines{$section}{$line};
2302 $l->{section} = $sectionmap{$section};
2303 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2304 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2309 return(\@sections, \@lines);
2315 my $end = $self->_date;
2317 # start at date of previous invoice + 1 second or 0 if no previous invoice
2318 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2319 $start = 0 if !$start;
2322 my $cust_main = $self->cust_main;
2323 my @pkgs = $cust_main->all_pkgs;
2324 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2327 foreach my $pkg ( @pkgs ) {
2328 my @h_cust_svc = $pkg->h_cust_svc($end);
2329 foreach my $h_cust_svc ( @h_cust_svc ) {
2330 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2331 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2333 my $inserted = $h_cust_svc->date_inserted;
2334 my $deleted = $h_cust_svc->date_deleted;
2335 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2337 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2339 # DID either activated or ported in; cannot be both for same DID simultaneously
2340 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2341 && (!$phone_inserted->lnp_status
2342 || $phone_inserted->lnp_status eq ''
2343 || $phone_inserted->lnp_status eq 'native')) {
2346 else { # this one not so clean, should probably move to (h_)svc_phone
2347 my $phone_portedin = qsearchs( 'h_svc_phone',
2348 { 'svcnum' => $h_cust_svc->svcnum,
2349 'lnp_status' => 'portedin' },
2350 FS::h_svc_phone->sql_h_searchs($end),
2352 $num_portedin++ if $phone_portedin;
2355 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2356 if($deleted >= $start && $deleted <= $end && $phone_deleted
2357 && (!$phone_deleted->lnp_status
2358 || $phone_deleted->lnp_status ne 'portingout')) {
2361 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2362 && $phone_deleted->lnp_status
2363 && $phone_deleted->lnp_status eq 'portingout') {
2367 # increment usage minutes
2368 if ( $phone_inserted ) {
2369 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2370 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2373 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2376 # don't look at this service again
2377 push @seen, $h_cust_svc->svcnum;
2381 $minutes = sprintf("%d", $minutes);
2382 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2383 . "$num_deactivated Ported-Out: $num_portedout ",
2384 "Total Minutes: $minutes");
2387 sub _items_accountcode_cdr {
2392 my $section = { 'amount' => 0,
2395 'sort_weight' => '',
2397 'description' => 'Usage by Account Code',
2403 my %accountcodes = ();
2405 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2406 next unless $cust_bill_pkg->pkgnum > 0;
2408 my @header = $cust_bill_pkg->details_header;
2409 next unless scalar(@header);
2410 $section->{'header'} = join(',',@header);
2412 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2414 $section->{'header'} = $detail->formatted('format' => $format)
2415 if($detail->detail eq $section->{'header'});
2417 my $accountcode = $detail->accountcode;
2418 next unless $accountcode;
2420 my $amount = $detail->amount;
2421 next unless $amount && $amount > 0;
2423 $accountcodes{$accountcode} ||= {
2424 description => $accountcode,
2431 product_code => 'N/A',
2432 section => $section,
2433 ext_description => [ $section->{'header'} ],
2437 $section->{'amount'} += $amount;
2438 $accountcodes{$accountcode}{'amount'} += $amount;
2439 $accountcodes{$accountcode}{calls}++;
2440 $accountcodes{$accountcode}{duration} += $detail->duration;
2441 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2445 foreach my $l ( values %accountcodes ) {
2446 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2447 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2448 foreach my $sorted_detail ( @sorted_detail ) {
2449 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2451 delete $l->{detail_temp};
2455 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2457 return ($section,\@sorted_lines);
2460 sub _items_svc_phone_sections {
2462 my $conf = $self->conf;
2470 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2472 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2473 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2475 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2476 next unless $cust_bill_pkg->pkgnum > 0;
2478 my @header = $cust_bill_pkg->details_header;
2479 next unless scalar(@header);
2481 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2483 my $phonenum = $detail->phonenum;
2484 next unless $phonenum;
2486 my $amount = $detail->amount;
2487 next unless $amount && $amount > 0;
2489 $sections{$phonenum} ||= { 'amount' => 0,
2492 'sort_weight' => -1,
2493 'phonenum' => $phonenum,
2495 $sections{$phonenum}{amount} += $amount; #subtotal
2496 $sections{$phonenum}{calls}++;
2497 $sections{$phonenum}{duration} += $detail->duration;
2499 my $desc = $detail->regionname;
2500 my $description = $desc;
2501 $description = substr($desc, 0, $maxlength). '...'
2502 if $format eq 'latex' && length($desc) > $maxlength;
2504 $lines{$phonenum}{$desc} ||= {
2505 description => &{$escape}($description),
2506 #pkgpart => $part_pkg->pkgpart,
2514 product_code => 'N/A',
2515 ext_description => [],
2518 $lines{$phonenum}{$desc}{amount} += $amount;
2519 $lines{$phonenum}{$desc}{calls}++;
2520 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2522 my $line = $usage_class{$detail->classnum}->classname;
2523 $sections{"$phonenum $line"} ||=
2527 'sort_weight' => $usage_class{$detail->classnum}->weight,
2528 'phonenum' => $phonenum,
2529 'header' => [ @header ],
2531 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2532 $sections{"$phonenum $line"}{calls}++;
2533 $sections{"$phonenum $line"}{duration} += $detail->duration;
2535 $lines{"$phonenum $line"}{$desc} ||= {
2536 description => &{$escape}($description),
2537 #pkgpart => $part_pkg->pkgpart,
2545 product_code => 'N/A',
2546 ext_description => [],
2549 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2550 $lines{"$phonenum $line"}{$desc}{calls}++;
2551 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2552 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2553 $detail->formatted('format' => $format);
2558 my %sectionmap = ();
2559 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2560 foreach ( keys %sections ) {
2561 my @header = @{ $sections{$_}{header} || [] };
2563 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2564 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2565 my $usage_class = $summary ? $simple : $usage_simple;
2566 my $ending = $summary ? ' usage charges' : '';
2569 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2571 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2572 'amount' => $sections{$_}{amount}, #subtotal
2573 'calls' => $sections{$_}{calls},
2574 'duration' => $sections{$_}{duration},
2576 'tax_section' => '',
2577 'phonenum' => $sections{$_}{phonenum},
2578 'sort_weight' => $sections{$_}{sort_weight},
2579 'post_total' => $summary, #inspire pagebreak
2581 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2582 qw( description_generator
2585 total_line_generator
2592 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2593 $a->{sort_weight} <=> $b->{sort_weight}
2598 foreach my $section ( keys %lines ) {
2599 foreach my $line ( keys %{$lines{$section}} ) {
2600 my $l = $lines{$section}{$line};
2601 $l->{section} = $sectionmap{$section};
2602 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2603 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2608 if($conf->exists('phone_usage_class_summary')) {
2609 # this only works with Latex
2613 # after this, we'll have only two sections per DID:
2614 # Calls Summary and Calls Detail
2615 foreach my $section ( @sections ) {
2616 if($section->{'post_total'}) {
2617 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2618 $section->{'total_line_generator'} = sub { '' };
2619 $section->{'total_generator'} = sub { '' };
2620 $section->{'header_generator'} = sub { '' };
2621 $section->{'description_generator'} = '';
2622 push @newsections, $section;
2623 my %calls_detail = %$section;
2624 $calls_detail{'post_total'} = '';
2625 $calls_detail{'sort_weight'} = '';
2626 $calls_detail{'description_generator'} = sub { '' };
2627 $calls_detail{'header_generator'} = sub {
2628 return ' & Date/Time & Called Number & Duration & Price'
2629 if $format eq 'latex';
2632 $calls_detail{'description'} = 'Calls Detail: '
2633 . $section->{'phonenum'};
2634 push @newsections, \%calls_detail;
2638 # after this, each usage class is collapsed/summarized into a single
2639 # line under the Calls Summary section
2640 foreach my $newsection ( @newsections ) {
2641 if($newsection->{'post_total'}) { # this means Calls Summary
2642 foreach my $section ( @sections ) {
2643 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2644 && !$section->{'post_total'});
2645 my $newdesc = $section->{'description'};
2646 my $tn = $section->{'phonenum'};
2647 $newdesc =~ s/$tn//g;
2648 my $line = { ext_description => [],
2652 calls => $section->{'calls'},
2653 section => $newsection,
2654 duration => $section->{'duration'},
2655 description => $newdesc,
2656 amount => sprintf("%.2f",$section->{'amount'}),
2657 product_code => 'N/A',
2659 push @newlines, $line;
2664 # after this, Calls Details is populated with all CDRs
2665 foreach my $newsection ( @newsections ) {
2666 if(!$newsection->{'post_total'}) { # this means Calls Details
2667 foreach my $line ( @lines ) {
2668 next unless (scalar(@{$line->{'ext_description'}}) &&
2669 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2671 my @extdesc = @{$line->{'ext_description'}};
2673 foreach my $extdesc ( @extdesc ) {
2674 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2675 push @newextdesc, $extdesc;
2677 $line->{'ext_description'} = \@newextdesc;
2678 $line->{'section'} = $newsection;
2679 push @newlines, $line;
2684 return(\@newsections, \@newlines);
2687 return(\@sections, \@lines);
2691 =sub _items_usage_class_summary OPTIONS
2693 Returns a list of detail items summarizing the usage charges on this
2694 invoice. Each one will have 'amount', 'description' (the usage charge name),
2695 and 'usage_classnum'.
2697 OPTIONS can include 'escape' (a function to escape the descriptions).
2701 sub _items_usage_class_summary {
2705 my $escape = $opt{escape} || sub { $_[0] };
2706 my $money_char = $opt{money_char};
2707 my $invnum = $self->invnum;
2708 my @classes = qsearch({
2709 'table' => 'usage_class',
2710 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2711 ' COUNT(*) AS calls, SUM(duration) AS duration',
2712 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2713 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2714 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2715 ' GROUP BY classnum, classname, weight'.
2716 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2717 ' ORDER BY weight ASC',
2721 description => &{$escape}($self->mt('Usage Summary')),
2725 foreach my $class (@classes) {
2726 $section->{subtotal} += $class->get('amount');
2728 'description' => &{$escape}($class->classname),
2729 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2730 'quantity' => $class->get('calls'),
2731 'duration' => $class->get('duration'),
2732 'usage_classnum' => $class->classnum,
2733 'section' => $section,
2736 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2740 sub _items_previous {
2742 my $conf = $self->conf;
2743 my $cust_main = $self->cust_main;
2744 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2746 foreach ( @pr_cust_bill ) {
2747 my $date = $conf->exists('invoice_show_prior_due_date')
2748 ? 'due '. $_->due_date2str('short')
2749 : $self->time2str_local('short', $_->_date);
2751 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2752 #'pkgpart' => 'N/A',
2754 'amount' => sprintf("%.2f", $_->owed),
2760 # 'description' => 'Previous Balance',
2761 # #'pkgpart' => 'N/A',
2762 # 'pkgnum' => 'N/A',
2763 # 'amount' => sprintf("%10.2f", $pr_total ),
2764 # 'ext_description' => [ map {
2765 # "Invoice ". $_->invnum.
2766 # " (". time2str("%x",$_->_date). ") ".
2767 # sprintf("%10.2f", $_->owed)
2768 # } @pr_cust_bill ],
2773 sub _items_credits {
2774 my( $self, %opt ) = @_;
2775 my $trim_len = $opt{'trim_len'} || 40;
2780 if ( $self->conf->exists('previous_balance-payments_since') ) {
2781 if ( $opt{'template'} eq 'statement' ) {
2782 # then the current bill is a "statement" (i.e. an invoice sent as
2783 # a payment receipt)
2784 # and in that case we want to see payments on or after THIS invoice
2785 @objects = qsearch('cust_credit', {
2786 'custnum' => $self->custnum,
2787 '_date' => {op => '>=', value => $self->_date},
2791 $date = $self->previous_bill->_date if $self->previous_bill;
2792 @objects = qsearch('cust_credit', {
2793 'custnum' => $self->custnum,
2794 '_date' => {op => '>=', value => $date},
2798 @objects = $self->cust_credited;
2801 foreach my $obj ( @objects ) {
2802 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2804 my $reason = substr($cust_credit->reason, 0, $trim_len);
2805 $reason .= '...' if length($reason) < length($cust_credit->reason);
2806 $reason = " ($reason) " if $reason;
2809 #'description' => 'Credit ref\#'. $_->crednum.
2810 # " (". time2str("%x",$_->cust_credit->_date) .")".
2812 'description' => $self->mt('Credit applied').' '.
2813 $self->time2str_local('short', $obj->_date). $reason,
2814 'amount' => sprintf("%.2f",$obj->amount),
2822 sub _items_payments {
2827 my $detailed = $self->conf->exists('invoice_payment_details');
2829 if ( $self->conf->exists('previous_balance-payments_since') ) {
2830 # then show payments dated on/after the previous bill...
2831 if ( $opt{'template'} eq 'statement' ) {
2832 # then the current bill is a "statement" (i.e. an invoice sent as
2833 # a payment receipt)
2834 # and in that case we want to see payments on or after THIS invoice
2835 @objects = qsearch('cust_pay', {
2836 'custnum' => $self->custnum,
2837 '_date' => {op => '>=', value => $self->_date},
2840 # the normal case: payments on or after the previous invoice
2842 $date = $self->previous_bill->_date if $self->previous_bill;
2843 @objects = qsearch('cust_pay', {
2844 'custnum' => $self->custnum,
2845 '_date' => {op => '>=', value => $date},
2847 # and before the current bill...
2848 @objects = grep { $_->_date < $self->_date } @objects;
2851 @objects = $self->cust_bill_pay;
2854 foreach my $obj (@objects) {
2855 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2856 my $desc = $self->mt('Payment received').' '.
2857 $self->time2str_local('short', $cust_pay->_date );
2858 $desc .= $self->mt(' via ') .
2859 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2863 'description' => $desc,
2864 'amount' => sprintf("%.2f", $obj->amount )
2874 my $conf = $self->conf;
2877 my ($pr_total) = $self->previous;
2878 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2880 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2881 # if enabled, specifically add a line for the previous balance total
2882 $previous_charges_desc = $self->mt(
2883 $conf->config('previous_balance-text') || 'Previous Balance'
2886 # then return separate lines for previous balance and total new charges
2889 { total_item => $previous_charges_desc,
2890 total_amount => sprintf('%.2f',$pr_total)
2895 if ( $conf->exists('previous_balance-exclude_from_total')
2896 or !$self->enable_previous ) {
2897 # show new charges only
2899 $new_charges_desc = $self->mt(
2900 $conf->config('previous_balance-text-total_new_charges')
2901 || 'Total New Charges'
2904 $new_charges_amount = $self->charged;
2907 # show new charges + previous invoice total
2909 $new_charges_desc = $self->mt('Total Charges');
2910 if ( $self->enable_previous ) {
2911 $new_charges_amount = sprintf('%.2f', $self->charged + $pr_total);
2913 $new_charges_amount = sprintf('%.2f', $self->charged);
2918 if ( $conf->exists('invoice_show_prior_due_date') ) {
2919 # then the due date should be shown with Total New Charges,
2920 # and should NOT be shown with the Balance Due message.
2921 if ( $self->due_date ) {
2922 # localize the "Please pay by" message and the date itself
2923 # (grammar issues with this, yeah)
2924 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2925 $self->due_date2str('short');
2926 } elsif ( $self->terms ) {
2927 # phrases like "due on receipt" should be localized
2928 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2933 { total_item => $new_charges_desc,
2934 total_amount => $new_charges_amount,
2942 =item has_call_details
2944 Returns true if this invoice has call details.
2948 sub has_call_details {
2951 SELECT 1 FROM cust_bill_pkg_detail
2952 LEFT JOIN cust_bill_pkg USING (billpkgnum)
2953 WHERE cust_bill_pkg_detail.format = 'C'
2954 AND cust_bill_pkg.invnum = ?
2959 =item call_details [ OPTION => VALUE ... ]
2961 Returns an array of CSV strings representing the call details for this invoice
2962 The only option available is the boolean prepend_billed_number
2967 my ($self, %opt) = @_;
2969 my $format_function = sub { shift };
2971 if ($opt{prepend_billed_number}) {
2972 $format_function = sub {
2976 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2981 my @details = map { $_->details( 'format_function' => $format_function,
2982 'escape_function' => sub{ return() },
2986 $self->cust_bill_pkg;
2987 my $header = $details[0];
2988 ( $header, grep { $_ ne $header } @details );
2998 =item process_reprint
3002 sub process_reprint {
3003 process_re_X('print', @_);
3006 =item process_reemail
3010 sub process_reemail {
3011 process_re_X('email', @_);
3019 process_re_X('fax', @_);
3027 process_re_X('ftp', @_);
3034 sub process_respool {
3035 process_re_X('spool', @_);
3038 use Storable qw(thaw);
3042 my( $method, $job ) = ( shift, shift );
3043 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3045 my $param = thaw(decode_base64(shift));
3046 warn Dumper($param) if $DEBUG;
3056 # this is called from search/cust_bill.html and given all its search
3057 # parameters, so it needs to perform the same search.
3060 # spool_invoice ftp_invoice fax_invoice print_invoice
3061 my($method, $job, %param ) = @_;
3063 warn "re_X $method for job $job with param:\n".
3064 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3067 #some false laziness w/search/cust_bill.html
3068 $param{'order_by'} = 'cust_bill._date';
3070 my $query = FS::cust_bill->search(\%param);
3071 delete $query->{'count_query'};
3072 delete $query->{'count_addl'};
3074 $query->{debug} = 1; # was in here before, is obviously useful
3076 my @cust_bill = qsearch( $query );
3078 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3080 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3083 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3084 foreach my $cust_bill ( @cust_bill ) {
3085 $cust_bill->$method();
3087 if ( $job ) { #progressbar foo
3089 if ( time - $min_sec > $last ) {
3090 my $error = $job->update_statustext(
3091 int( 100 * $num / scalar(@cust_bill) )
3093 die $error if $error;
3104 =head1 CLASS METHODS
3110 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3115 my ($class, $start, $end) = @_;
3117 $class->paid_sql($start, $end). ' - '.
3118 $class->credited_sql($start, $end);
3123 Returns an SQL fragment to retreive the net amount (charged minus credited).
3128 my ($class, $start, $end) = @_;
3129 'charged - '. $class->credited_sql($start, $end);
3134 Returns an SQL fragment to retreive the amount paid against this invoice.
3139 my ($class, $start, $end) = @_;
3140 $start &&= "AND cust_bill_pay._date <= $start";
3141 $end &&= "AND cust_bill_pay._date > $end";
3142 $start = '' unless defined($start);
3143 $end = '' unless defined($end);
3144 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3145 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3150 Returns an SQL fragment to retreive the amount credited against this invoice.
3155 my ($class, $start, $end) = @_;
3156 $start &&= "AND cust_credit_bill._date <= $start";
3157 $end &&= "AND cust_credit_bill._date > $end";
3158 $start = '' unless defined($start);
3159 $end = '' unless defined($end);
3160 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3161 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3166 Returns an SQL fragment to retrieve the due date of an invoice.
3167 Currently only supported on PostgreSQL.
3172 die "don't use: doesn't account for agent-specific invoice_default_terms";
3174 #we're passed a $conf but not a specific customer (that's in the query), so
3175 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3176 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3179 my $conf = new FS::Conf;
3183 cust_bill.invoice_terms,
3184 cust_main.invoice_terms,
3185 \''.($conf->config('invoice_default_terms') || '').'\'
3186 ), E\'Net (\\\\d+)\'
3188 ) * 86400 + cust_bill._date'
3199 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3200 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base