2 use base qw( FS::cust_bill::Search FS::Template_Mixin
3 FS::cust_main_Mixin FS::Record
7 use vars qw( $DEBUG $me );
10 use Fcntl qw(:flock); #for spool_csv
12 use List::Util qw(min max sum);
16 use Storable qw( freeze thaw );
18 use FS::UID qw( datasrc );
19 use FS::Misc qw( send_fax do_print );
20 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;
32 use FS::cust_bill_pay;
35 use FS::cust_bill_batch;
36 use FS::cust_bill_pay_pkg;
37 use FS::cust_credit_bill_pkg;
38 use FS::discount_plan;
39 use FS::cust_bill_void;
45 $me = '[FS::cust_bill]';
49 FS::cust_bill - Object methods for cust_bill records
55 $record = new FS::cust_bill \%hash;
56 $record = new FS::cust_bill { 'column' => 'value' };
58 $error = $record->insert;
60 $error = $new_record->replace($old_record);
62 $error = $record->delete;
64 $error = $record->check;
66 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
68 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
70 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
72 @cust_pay_objects = $cust_bill->cust_pay;
74 $tax_amount = $record->tax;
76 @lines = $cust_bill->print_text;
77 @lines = $cust_bill->print_text('time' => $time);
81 An FS::cust_bill object represents an invoice; a declaration that a customer
82 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
83 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
84 following fields are currently supported:
90 =item invnum - primary key (assigned automatically for new invoices)
92 =item custnum - customer (see L<FS::cust_main>)
94 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
95 L<Time::Local> and L<Date::Parse> for conversion functions.
97 =item charged - amount of this invoice
99 =item invoice_terms - optional terms override for this specific invoice
107 =item billing_balance - the customer's balance immediately before generating
108 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
109 to determine the customer's balance at a specific time.
111 =item previous_balance - the customer's balance immediately after generating
112 the invoice before this one. DEPRECATED.
114 =item printed - formerly used to track the number of times an invoice had
115 been printed; no longer used.
123 =item closed - books closed flag, empty or `Y'
125 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
127 =item agent_invid - legacy invoice number
129 =item promised_date - customer promised payment date, for collection
131 =item pending - invoice is still being generated, empty or 'Y'
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'; }
148 sub template_conf { 'invoice_'; }
150 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
151 # (except email_subject and invnum_date_pretty)
154 $self->conf->config('notice_name') || 'Invoice'
157 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
158 sub cust_unlinked_msg {
160 "WARNING: can't find cust_main.custnum ". $self->custnum.
161 ' (cust_bill.invnum '. $self->invnum. ')';
166 Adds this invoice to the database ("Posts" the invoice). If there is an error,
167 returns the error, otherwise returns false.
173 warn "$me insert called\n" if $DEBUG;
175 local $SIG{HUP} = 'IGNORE';
176 local $SIG{INT} = 'IGNORE';
177 local $SIG{QUIT} = 'IGNORE';
178 local $SIG{TERM} = 'IGNORE';
179 local $SIG{TSTP} = 'IGNORE';
180 local $SIG{PIPE} = 'IGNORE';
182 my $oldAutoCommit = $FS::UID::AutoCommit;
183 local $FS::UID::AutoCommit = 0;
186 my $error = $self->SUPER::insert;
188 $dbh->rollback if $oldAutoCommit;
192 if ( $self->get('cust_bill_pkg') ) {
193 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
194 $cust_bill_pkg->invnum($self->invnum);
195 my $error = $cust_bill_pkg->insert;
197 $dbh->rollback if $oldAutoCommit;
198 return "can't create invoice line item: $error";
203 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
208 =item void [ REASON [ , REPROCESS_CDRS ] ]
210 Voids this invoice: deletes the invoice and adds a record of the voided invoice
211 to the FS::cust_bill_void table (and related tables starting from
212 FS::cust_bill_pkg_void).
218 my $reason = scalar(@_) ? shift : '';
219 my $reprocess_cdrs = scalar(@_) ? shift : '';
221 unless (ref($reason) || !$reason) {
222 $reason = FS::reason->new_or_existing(
224 'type' => 'Invoice void',
229 local $SIG{HUP} = 'IGNORE';
230 local $SIG{INT} = 'IGNORE';
231 local $SIG{QUIT} = 'IGNORE';
232 local $SIG{TERM} = 'IGNORE';
233 local $SIG{TSTP} = 'IGNORE';
234 local $SIG{PIPE} = 'IGNORE';
236 my $oldAutoCommit = $FS::UID::AutoCommit;
237 local $FS::UID::AutoCommit = 0;
240 my $cust_bill_void = new FS::cust_bill_void ( {
241 map { $_ => $self->get($_) } $self->fields
243 $cust_bill_void->reasonnum($reason->reasonnum) if $reason;
244 my $error = $cust_bill_void->insert;
246 $dbh->rollback if $oldAutoCommit;
250 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
251 my $error = $cust_bill_pkg->void($reason, $reprocess_cdrs);
253 $dbh->rollback if $oldAutoCommit;
258 $error = $self->delete;
260 $dbh->rollback if $oldAutoCommit;
264 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
272 DO NOT USE THIS METHOD. Instead, apply a credit against the invoice, or use
275 This is only for internal use by V<void>, which is what you should be using.
277 DO NOT USE THIS METHOD. Whatever reason you think you have is almost certainly
278 wrong. Use B<void>, that's what it is for. Really. This means you.
284 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
286 local $SIG{HUP} = 'IGNORE';
287 local $SIG{INT} = 'IGNORE';
288 local $SIG{QUIT} = 'IGNORE';
289 local $SIG{TERM} = 'IGNORE';
290 local $SIG{TSTP} = 'IGNORE';
291 local $SIG{PIPE} = 'IGNORE';
293 my $oldAutoCommit = $FS::UID::AutoCommit;
294 local $FS::UID::AutoCommit = 0;
297 foreach my $table (qw(
304 #cust_event # problematic
305 #cust_pay_batch # unnecessary
307 foreach my $linked ( $self->$table() ) {
308 my $error = $linked->delete;
310 $dbh->rollback if $oldAutoCommit;
317 my $error = $self->SUPER::delete(@_);
319 $dbh->rollback if $oldAutoCommit;
323 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
329 =item replace [ OLD_RECORD ]
331 You can, but probably shouldn't modify invoices...
333 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
334 supplied, replaces this record. If there is an error, returns the error,
335 otherwise returns false.
339 #replace can be inherited from Record.pm
341 # replace_check is now the preferred way to #implement replace data checks
342 # (so $object->replace() works without an argument)
345 my( $new, $old ) = ( shift, shift );
346 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
347 #return "Can't change _date!" unless $old->_date eq $new->_date;
348 return "Can't change _date" unless $old->_date == $new->_date;
349 return "Can't change charged" unless $old->charged == $new->charged
350 || $old->pending eq 'Y'
351 || $old->charged == 0
352 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
358 =item add_cc_surcharge
364 sub add_cc_surcharge {
365 my ($self, $pkgnum, $amount) = (shift, shift, shift);
368 my $cust_bill_pkg = new FS::cust_bill_pkg({
369 'invnum' => $self->invnum,
373 $error = $cust_bill_pkg->insert;
374 return $error if $error;
376 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
377 $self->charged($self->charged+$amount);
378 $error = $self->replace;
379 return $error if $error;
381 $self->apply_payments_and_credits;
387 Checks all fields to make sure this is a valid invoice. If there is an error,
388 returns the error, otherwise returns false. Called by the insert and replace
397 $self->ut_numbern('invnum')
398 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
399 || $self->ut_numbern('_date')
400 || $self->ut_money('charged')
401 || $self->ut_numbern('printed')
402 || $self->ut_enum('closed', [ '', 'Y' ])
403 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
404 || $self->ut_numbern('agent_invid') #varchar?
405 || $self->ut_flag('pending')
407 return $error if $error;
409 $self->_date(time) unless $self->_date;
411 $self->printed(0) if $self->printed eq '';
418 Returns the displayed invoice number for this invoice: agent_invid if
419 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
425 if ( $self->agent_invid
426 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
427 return $self->agent_invid;
429 return $self->invnum;
435 Returns the customer's last invoice before this one.
441 if ( !$self->get('previous_bill') ) {
442 $self->set('previous_bill', qsearchs({
443 'table' => 'cust_bill',
444 'hashref' => { 'custnum' => $self->custnum,
445 '_date' => { op=>'<', value=>$self->_date } },
446 'order_by' => 'ORDER BY _date DESC LIMIT 1',
449 $self->get('previous_bill');
454 Returns a list consisting of the total previous balance for this customer,
455 followed by the previous outstanding invoices (as FS::cust_bill objects also).
461 # simple memoize; we use this a lot
462 if (!$self->get('previous')) {
464 my @cust_bill = sort { $a->_date <=> $b->_date }
465 grep { $_->owed != 0 }
466 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
467 #'_date' => { op=>'<', value=>$self->_date },
468 'invnum' => { op=>'<', value=>$self->invnum },
471 foreach ( @cust_bill ) { $total += $_->owed; }
472 $self->set('previous', [$total, @cust_bill]);
474 return @{ $self->get('previous') };
477 =item enable_previous
479 Whether to show the 'Previous Charges' section when printing this invoice.
480 The negation of the 'disable_previous_balance' config setting.
484 sub enable_previous {
486 my $agentnum = $self->cust_main->agentnum;
487 !$self->conf->exists('disable_previous_balance', $agentnum);
492 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
500 'select' => 'cust_bill_pkg.*, pkg_category.categoryname',
501 'table' => 'cust_bill_pkg',
502 'addl_from' => ' LEFT JOIN cust_pkg USING ( pkgnum ) '.
503 ' LEFT JOIN part_pkg USING ( pkgpart ) '.
504 ' LEFT JOIN pkg_class USING ( classnum ) '.
505 ' LEFT JOIN pkg_category USING ( categorynum ) ',
506 'hashref' => { 'invnum' => $self->invnum },
507 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
508 # the AUTLOADED FK search. or should
509 # that default to ORDER by the pkey?
514 =item cust_bill_pkg_pkgnum PKGNUM
516 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
521 sub cust_bill_pkg_pkgnum {
522 my( $self, $pkgnum ) = @_;
524 { 'table' => 'cust_bill_pkg',
525 'hashref' => { 'invnum' => $self->invnum,
528 'order_by' => 'ORDER BY billpkgnum',
535 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
542 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
543 $self->cust_bill_pkg;
545 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
550 Returns true if any of the packages (or their definitions) corresponding to the
551 line items for this invoice have the no_auto flag set.
557 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
560 =item open_cust_bill_pkg
562 Returns the open line items for this invoice.
564 Note that cust_bill_pkg with both setup and recur fees are returned as two
565 separate line items, each with only one fee.
569 # modeled after cust_main::open_cust_bill
570 sub open_cust_bill_pkg {
573 # grep { $_->owed > 0 } $self->cust_bill_pkg
575 my %other = ( 'recur' => 'setup',
576 'setup' => 'recur', );
578 foreach my $field ( qw( recur setup )) {
579 push @open, map { $_->set( $other{$field}, 0 ); $_; }
580 grep { $_->owed($field) > 0 }
581 $self->cust_bill_pkg;
589 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
593 #false laziness w/cust_pkg.pm
597 'table' => 'cust_event',
598 'addl_from' => 'JOIN part_event USING ( eventpart )',
599 'hashref' => { 'tablenum' => $self->invnum },
600 'extra_sql' => " AND eventtable = 'cust_bill' ",
606 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
610 #false laziness w/cust_pkg.pm
614 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
615 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
616 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
617 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
618 $sth->fetchrow_arrayref->[0];
623 Returns the customer (see L<FS::cust_main>) for this invoice.
627 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice
629 Returns a list: an empty list on success or a list of errors.
636 grep { $_->suspend(@_) }
637 grep {! $_->getfield('cancel') }
642 =item cust_suspend_if_balance_over AMOUNT
644 Suspends the customer associated with this invoice if the total amount owed on
645 this invoice and all older invoices is greater than the specified amount.
647 Returns a list: an empty list on success or a list of errors.
651 sub cust_suspend_if_balance_over {
652 my( $self, $amount ) = ( shift, shift );
653 my $cust_main = $self->cust_main;
654 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
657 $cust_main->suspend(@_);
663 Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options
668 my( $self, %opt ) = @_;
670 warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
671 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
674 return ( 'Access denied' )
675 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
677 my @pkgs = $self->cust_pkg;
679 if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
681 my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
682 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
687 map { $_->cancel(%opt) }
688 grep { ! $_->getfield('cancel') }
694 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
700 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
701 sort { $a->_date <=> $b->_date }
702 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
707 =item cust_credit_bill
709 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
715 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
716 sort { $a->_date <=> $b->_date }
717 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
721 sub cust_credit_bill {
722 shift->cust_credited(@_);
725 #=item cust_bill_pay_pkgnum PKGNUM
727 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
728 #with matching pkgnum.
732 #sub cust_bill_pay_pkgnum {
733 # my( $self, $pkgnum ) = @_;
734 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
735 # sort { $a->_date <=> $b->_date }
736 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
737 # 'pkgnum' => $pkgnum,
742 =item cust_bill_pay_pkg PKGNUM
744 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
745 applied against the matching pkgnum.
749 sub cust_bill_pay_pkg {
750 my( $self, $pkgnum ) = @_;
753 'select' => 'cust_bill_pay_pkg.*',
754 'table' => 'cust_bill_pay_pkg',
755 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
756 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
757 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
758 " AND cust_bill_pkg.pkgnum = $pkgnum",
763 #=item cust_credited_pkgnum PKGNUM
765 #=item cust_credit_bill_pkgnum PKGNUM
767 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
768 #with matching pkgnum.
772 #sub cust_credited_pkgnum {
773 # my( $self, $pkgnum ) = @_;
774 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
775 # sort { $a->_date <=> $b->_date }
776 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
777 # 'pkgnum' => $pkgnum,
782 #sub cust_credit_bill_pkgnum {
783 # shift->cust_credited_pkgnum(@_);
786 =item cust_credit_bill_pkg PKGNUM
788 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
789 applied against the matching pkgnum.
793 sub cust_credit_bill_pkg {
794 my( $self, $pkgnum ) = @_;
797 'select' => 'cust_credit_bill_pkg.*',
798 'table' => 'cust_credit_bill_pkg',
799 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
800 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
801 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
802 " AND cust_bill_pkg.pkgnum = $pkgnum",
807 =item cust_bill_batch
809 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
813 sub cust_bill_batch {
815 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
820 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
821 hash keyed by term length.
827 FS::discount_plan->all($self);
832 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
839 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
841 foreach (@taxlines) { $total += $_->setup; }
847 Returns the amount owed (still outstanding) on this invoice, which is charged
848 minus all payment applications (see L<FS::cust_bill_pay>) and credit
849 applications (see L<FS::cust_credit_bill>).
855 my $balance = $self->charged;
856 $balance -= $_->amount foreach ( $self->cust_bill_pay );
857 $balance -= $_->amount foreach ( $self->cust_credited );
858 $balance = sprintf( "%.2f", $balance);
859 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
864 my( $self, $pkgnum ) = @_;
866 #my $balance = $self->charged;
868 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
870 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
871 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
873 $balance = sprintf( "%.2f", $balance);
874 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
880 Returns true if this invoice should be hidden. See the
881 selfservice-hide_invoices-taxclass configuraiton setting.
887 my $conf = $self->conf;
888 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
890 my @cust_bill_pkg = $self->cust_bill_pkg;
891 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
892 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
895 =item apply_payments_and_credits [ OPTION => VALUE ... ]
897 Applies unapplied payments and credits to this invoice.
898 Payments with the no_auto_apply flag set will not be applied.
900 A hash of optional arguments may be passed. Currently "manual" is supported.
901 If true, a payment receipt is sent instead of a statement when
902 'payment_receipt_email' configuration option is set.
904 If there is an error, returns the error, otherwise returns false.
908 sub apply_payments_and_credits {
909 my( $self, %options ) = @_;
910 my $conf = $self->conf;
912 local $SIG{HUP} = 'IGNORE';
913 local $SIG{INT} = 'IGNORE';
914 local $SIG{QUIT} = 'IGNORE';
915 local $SIG{TERM} = 'IGNORE';
916 local $SIG{TSTP} = 'IGNORE';
917 local $SIG{PIPE} = 'IGNORE';
919 my $oldAutoCommit = $FS::UID::AutoCommit;
920 local $FS::UID::AutoCommit = 0;
923 $self->select_for_update; #mutex
925 my @payments = grep { $_->unapplied > 0 }
926 grep { !$_->no_auto_apply }
927 $self->cust_main->cust_pay;
928 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
930 if ( $conf->exists('pkg-balances') ) {
931 # limit @payments & @credits to those w/ a pkgnum grepped from $self
932 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
933 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
934 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
937 while ( $self->owed > 0 and ( @payments || @credits ) ) {
940 if ( @payments && @credits ) {
942 #decide which goes first by weight of top (unapplied) line item
944 my @open_lineitems = $self->open_cust_bill_pkg;
947 max( map { $_->part_pkg->pay_weight || 0 }
952 my $max_credit_weight =
953 max( map { $_->part_pkg->credit_weight || 0 }
959 #if both are the same... payments first? it has to be something
960 if ( $max_pay_weight >= $max_credit_weight ) {
966 } elsif ( @payments ) {
968 } elsif ( @credits ) {
971 die "guru meditation #12 and 35";
975 if ( $app eq 'pay' ) {
977 my $payment = shift @payments;
978 $unapp_amount = $payment->unapplied;
979 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
980 $app->pkgnum( $payment->pkgnum )
981 if $conf->exists('pkg-balances') && $payment->pkgnum;
983 } elsif ( $app eq 'credit' ) {
985 my $credit = shift @credits;
986 $unapp_amount = $credit->credited;
987 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
988 $app->pkgnum( $credit->pkgnum )
989 if $conf->exists('pkg-balances') && $credit->pkgnum;
992 die "guru meditation #12 and 35";
996 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
997 warn "owed_pkgnum ". $app->pkgnum;
998 $owed = $self->owed_pkgnum($app->pkgnum);
1000 $owed = $self->owed;
1002 next unless $owed > 0;
1004 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1005 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1007 $app->invnum( $self->invnum );
1009 my $error = $app->insert(%options);
1011 $dbh->rollback if $oldAutoCommit;
1012 return "Error inserting ". $app->table. " record: $error";
1014 die $error if $error;
1018 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1025 Sends this invoice to the destinations configured for this customer: sends
1026 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1028 Options can be passed as a hashref. Positional parameters are no longer
1031 I<template>: a suffix for alternate invoices
1033 I<agentnum>: obsolete, now does nothing.
1035 I<from> overrides the default email invoice From: address.
1037 I<amount>: obsolete, does nothing
1039 I<notice_name> overrides "Invoice" as the name of the sent document
1040 (templates from 10/2009 or newer required).
1042 I<lpr> overrides the system 'lpr' option as the command to print a document
1043 from standard input.
1049 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1050 my $conf = $self->conf;
1052 my $cust_main = $self->cust_main;
1054 my @invoicing_list = $cust_main->invoicing_list;
1057 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1058 && ! $cust_main->invoice_noemail;
1061 if grep { $_ eq 'POST' } @invoicing_list; #postal
1063 #this has never been used post-$ORIGINAL_ISP afaik
1064 $self->fax_invoice($opt)
1065 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1073 my $opt = shift || {};
1074 if ($opt and !ref($opt)) {
1075 die ref($self). '->email called with positional parameters';
1078 my $conf = $self->conf;
1080 my $from = delete $opt->{from};
1082 # this is where we set the From: address
1083 $from ||= $self->_agent_invoice_from || #XXX should go away
1084 $conf->invoice_from_full( $self->cust_main->agentnum );
1086 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1088 if ( ! @invoicing_list ) { #no recipients
1089 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1090 die 'No recipients for customer #'. $self->custnum;
1092 #default: better to notify this person than silence
1093 @invoicing_list = ($from);
1097 $self->SUPER::email( {
1099 'to' => \@invoicing_list,
1105 #this stays here for now because its explicitly used as
1106 # FS::cust_bill::queueable_email
1107 sub queueable_email {
1110 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1111 or die "invalid invoice number: " . $opt{invnum};
1113 $self->set('mode', $opt{mode})
1116 my %args = map {$_ => $opt{$_}}
1118 qw( from notice_name no_coupon template );
1120 my $error = $self->email( \%args );
1121 die $error if $error;
1127 my $conf = $self->conf;
1129 #my $template = scalar(@_) ? shift : '';
1132 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1135 my $cust_main = $self->cust_main;
1136 my $name = $cust_main->name;
1137 my $name_short = $cust_main->name_short;
1138 my $invoice_number = $self->invnum;
1139 my $invoice_date = $self->_date_pretty;
1141 eval qq("$subject");
1146 'Invoice-'. $self->invnum. '.pdf';
1149 =item lpr_data HASHREF
1151 Returns the postscript or plaintext for this invoice as an arrayref.
1153 Options must be passed as a hashref. Positional parameters are no longer
1156 I<template>, if specified, is the name of a suffix for alternate invoices.
1158 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1164 my $conf = $self->conf;
1165 my $opt = shift || {};
1166 if ($opt and !ref($opt)) {
1167 # nobody does this anyway
1168 die "FS::cust_bill::lpr_data called with positional parameters";
1171 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1172 [ $self->$method( $opt ) ];
1177 Prints this invoice.
1179 Options must be passed as a hashref.
1181 I<template>, if specified, is the name of a suffix for alternate invoices.
1183 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1189 return if $self->hide;
1190 my $conf = $self->conf;
1191 my $opt = shift || {};
1192 if ($opt and !ref($opt)) {
1193 die "FS::cust_bill::print called with positional parameters";
1196 my $lpr = delete $opt->{lpr};
1197 if($conf->exists('invoice_print_pdf')) {
1198 # Add the invoice to the current batch.
1199 $self->batch_invoice($opt);
1203 $self->lpr_data($opt),
1204 'agentnum' => $self->cust_main->agentnum,
1210 =item fax_invoice HASHREF
1214 Options must be passed as a hashref.
1216 I<template>, if specified, is the name of a suffix for alternate invoices.
1218 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1224 return if $self->hide;
1225 my $conf = $self->conf;
1226 my $opt = shift || {};
1227 if ($opt and !ref($opt)) {
1228 die "FS::cust_bill::fax_invoice called with positional parameters";
1231 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1232 unless $conf->exists('invoice_latex');
1234 my $dialstring = $self->cust_main->getfield('fax');
1237 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1238 'dialstring' => $dialstring,
1240 die $error if $error;
1244 =item batch_invoice [ HASHREF ]
1246 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1247 isn't an open batch, one will be created.
1249 HASHREF may contain any options to be passed to C<print_pdf>.
1254 my ($self, $opt) = @_;
1255 my $bill_batch = $self->get_open_bill_batch;
1256 my $cust_bill_batch = FS::cust_bill_batch->new({
1257 batchnum => $bill_batch->batchnum,
1258 invnum => $self->invnum,
1260 if ( $self->mode ) {
1261 $opt->{mode} ||= $self->mode;
1262 $opt->{mode} = $opt->{mode}->modenum if ref $opt->{mode};
1264 return $cust_bill_batch->insert($opt);
1267 =item get_open_batch
1269 Returns the currently open batch as an FS::bill_batch object, creating a new
1270 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1275 sub get_open_bill_batch {
1277 my $conf = $self->conf;
1278 my $hashref = { status => 'O' };
1279 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1280 ? $self->cust_main->agentnum
1282 my $batch = qsearchs('bill_batch', $hashref);
1283 return $batch if $batch;
1284 $batch = FS::bill_batch->new($hashref);
1285 my $error = $batch->insert;
1286 die $error if $error;
1290 =item ftp_invoice [ TEMPLATENAME ]
1292 Sends this invoice data via FTP.
1294 TEMPLATENAME is unused?
1300 my $conf = $self->conf;
1301 my $template = scalar(@_) ? shift : '';
1304 'protocol' => 'ftp',
1305 'server' => $conf->config('cust_bill-ftpserver'),
1306 'username' => $conf->config('cust_bill-ftpusername'),
1307 'password' => $conf->config('cust_bill-ftppassword'),
1308 'dir' => $conf->config('cust_bill-ftpdir'),
1309 'format' => $conf->config('cust_bill-ftpformat'),
1313 =item spool_invoice [ TEMPLATENAME ]
1315 Spools this invoice data (see L<FS::spool_csv>)
1317 TEMPLATENAME is unused?
1323 my $conf = $self->conf;
1324 my $template = scalar(@_) ? shift : '';
1327 'format' => $conf->config('cust_bill-spoolformat'),
1328 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1332 =item send_csv OPTION => VALUE, ...
1334 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1338 protocol - currently only "ftp"
1344 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1345 and YYMMDDHHMMSS is a timestamp.
1347 See L</print_csv> for a description of the output format.
1352 my($self, %opt) = @_;
1356 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1357 mkdir $spooldir, 0700 unless -d $spooldir;
1359 # don't localize dates here, they're a defined format
1360 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1361 my $file = "$spooldir/$tracctnum.csv";
1363 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1365 open(CSV, ">$file") or die "can't open $file: $!";
1373 if ( $opt{protocol} eq 'ftp' ) {
1374 eval "use Net::FTP;";
1376 $net = Net::FTP->new($opt{server}) or die @$;
1378 die "unknown protocol: $opt{protocol}";
1381 $net->login( $opt{username}, $opt{password} )
1382 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1384 $net->binary or die "can't set binary mode";
1386 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1388 $net->put($file) or die "can't put $file: $!";
1398 Spools CSV invoice data.
1404 =item format - any of FS::Misc::::Invoicing::spool_formats
1406 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1407 customer has the corresponding invoice destinations set (see
1408 L<FS::cust_main_invoice>).
1410 =item agent_spools - if set to a true value, will spool to per-agent files
1411 rather than a single global file
1413 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1414 append to that spool. L<FS::Cron::upload> will then send the spool file to
1417 =item balanceover - if set, only spools the invoice if the total amount owed on
1418 this invoice and all older invoices is greater than the specified amount.
1420 =item time - the "current time". Controls the printing of past due messages
1428 my($self, %opt) = @_;
1430 my $time = $opt{'time'} || time;
1431 my $cust_main = $self->cust_main;
1433 if ( $opt{'dest'} ) {
1434 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1435 $cust_main->invoicing_list;
1436 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1437 || ! keys %invoicing_list;
1440 if ( $opt{'balanceover'} ) {
1442 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1445 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1446 mkdir $spooldir, 0700 unless -d $spooldir;
1448 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1451 if ( $opt{'agent_spools'} ) {
1452 $file = 'agentnum'.$cust_main->agentnum;
1457 if ( $opt{'upload_targetnum'} ) {
1458 $spooldir .= '/target'.$opt{'upload_targetnum'};
1459 mkdir $spooldir, 0700 unless -d $spooldir;
1460 } # otherwise it just goes into export.xxx/cust_bill
1462 if ( lc($opt{'format'}) eq 'billco' ) {
1466 $file = "$spooldir/$file.csv";
1468 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1470 open(CSV, ">>$file") or die "can't open $file: $!";
1471 flock(CSV, LOCK_EX);
1476 if ( lc($opt{'format'}) eq 'billco' ) {
1478 flock(CSV, LOCK_UN);
1481 $file =~ s/-header.csv$/-detail.csv/;
1483 open(CSV,">>$file") or die "can't open $file: $!";
1484 flock(CSV, LOCK_EX);
1488 print CSV $detail if defined($detail);
1490 flock(CSV, LOCK_UN);
1497 =item print_csv OPTION => VALUE, ...
1499 Returns CSV data for this invoice.
1503 format - 'default', 'billco', 'oneline', 'bridgestone'
1505 Returns a list consisting of two scalars. The first is a single line of CSV
1506 header information for this invoice. The second is one or more lines of CSV
1507 detail information for this invoice.
1509 If I<format> is not specified or "default", the fields of the CSV file are as
1512 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1513 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1517 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1519 B<record_type> is C<cust_bill> for the initial header line only. The
1520 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1521 fields are filled in.
1523 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1524 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1527 =item invnum - invoice number
1529 =item custnum - customer number
1531 =item _date - invoice date
1533 =item charged - total invoice amount
1535 =item first - customer first name
1537 =item last - customer first name
1539 =item company - company name
1541 =item address1 - address line 1
1543 =item address2 - address line 1
1553 =item pkg - line item description
1555 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1557 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1559 =item sdate - start date for recurring fee
1561 =item edate - end date for recurring fee
1565 If I<format> is "billco", the fields of the header CSV file are as follows:
1567 +-------------------------------------------------------------------+
1568 | FORMAT HEADER FILE |
1569 |-------------------------------------------------------------------|
1570 | Field | Description | Name | Type | Width |
1571 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1572 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1573 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1574 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1575 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1576 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1577 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1578 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1579 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1580 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1581 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1582 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1583 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1584 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1585 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1586 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1587 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1588 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1589 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1590 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1591 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1592 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1593 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1594 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1595 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1596 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1597 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1598 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1599 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1600 +-------+-------------------------------+------------+------+-------+
1602 If I<format> is "billco", the fields of the detail CSV file are as follows:
1604 FORMAT FOR DETAIL FILE
1606 Field | Description | Name | Type | Width
1607 1 | N/A-Leave Empty | RC | CHAR | 2
1608 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1609 3 | Account Number | TRACCTNUM | CHAR | 15
1610 4 | Invoice Number | TRINVOICE | CHAR | 15
1611 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1612 6 | Transaction Detail | DETAILS | CHAR | 100
1613 7 | Amount | AMT | NUM* | 9
1614 8 | Line Format Control** | LNCTRL | CHAR | 2
1615 9 | Grouping Code | GROUP | CHAR | 2
1616 10 | User Defined | ACCT CODE | CHAR | 15
1618 If format is 'oneline', there is no detail file. Each invoice has a
1619 header line only, with the fields:
1621 Agent number, agent name, customer number, first name, last name, address
1622 line 1, address line 2, city, state, zip, invoice date, invoice number,
1623 amount charged, amount due, previous balance, due date.
1625 and then, for each line item, three columns containing the package number,
1626 description, and amount.
1628 If format is 'bridgestone', there is no detail file. Each invoice has a
1629 header line with the following fields in a fixed-width format:
1631 Customer number (in display format), date, name (first last), company,
1632 address 1, address 2, city, state, zip.
1634 This is a mailing list format, and has no per-invoice fields. To avoid
1635 sending redundant notices, the spooling event should have a "once" or
1636 "once_percust_every" condition.
1641 my($self, %opt) = @_;
1643 eval "use Text::CSV_XS";
1646 my $cust_main = $self->cust_main;
1648 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1649 my $format = lc($opt{'format'});
1651 my $time = $opt{'time'} || time;
1653 my $tracctnum = ''; #leaking out from billco-specific sections :/
1654 if ( $format eq 'billco' ) {
1657 $self->conf->config('billco-account_num', $cust_main->agentnum);
1659 $tracctnum = $account_num eq 'display_custnum'
1660 ? $cust_main->display_custnum
1661 : $opt{'tracctnum'};
1664 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1666 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1668 my( $previous_balance, @unused ) = $self->previous; #previous balance
1670 my $pmt_cr_applied = 0;
1671 $pmt_cr_applied += $_->{'amount'}
1672 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1674 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1677 '', # 1 | N/A-Leave Empty CHAR 2
1678 '', # 2 | N/A-Leave Empty CHAR 15
1679 $tracctnum, # 3 | Transaction Account No CHAR 15
1680 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1681 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1682 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1683 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1684 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1685 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1686 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1687 '', # 10 | Ancillary Billing Information CHAR 30
1688 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1689 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1692 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1695 $duedate, # 14 | Bill Due Date CHAR 10
1697 $previous_balance, # 15 | Previous Balance NUM* 9
1698 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1699 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1700 $totaldue, # 18 | Total Amt Due NUM* 9
1701 $totaldue, # 19 | Total Amt Due NUM* 9
1702 '', # 20 | 30 Day Aging NUM* 9
1703 '', # 21 | 60 Day Aging NUM* 9
1704 '', # 22 | 90 Day Aging NUM* 9
1705 'N', # 23 | Y/N CHAR 1
1706 '', # 24 | Remittance automation CHAR 100
1707 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1708 $self->custnum, # 26 | Customer Reference Number CHAR 15
1709 '0', # 27 | Federal Tax*** NUM* 9
1710 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1711 '0', # 29 | Other Taxes & Fees*** NUM* 9
1714 } elsif ( $format eq 'oneline' ) { #name
1716 my ($previous_balance) = $self->previous;
1717 $previous_balance = sprintf('%.2f', $previous_balance);
1718 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1724 $self->_items_pkg, #_items_nontax? no sections or anything
1729 $cust_main->agentnum,
1730 $cust_main->agent->agent,
1734 $cust_main->company,
1735 $cust_main->address1,
1736 $cust_main->address2,
1742 time2str("%x", $self->_date),
1747 $self->due_date2str("%x"),
1752 } elsif ( $format eq 'bridgestone' ) {
1754 # bypass the CSV stuff and just return this
1755 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1756 my $zip = $cust_main->zip;
1758 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1762 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1764 $cust_main->display_custnum,
1766 uc(substr($cust_main->contact_firstlast,0,30)),
1767 uc(substr($cust_main->company ,0,30)),
1768 uc(substr($cust_main->address1 ,0,30)),
1769 uc(substr($cust_main->address2 ,0,30)),
1770 uc(substr($cust_main->city ,0,20)),
1771 uc($cust_main->state),
1777 } elsif ( $format eq 'ics' ) {
1779 my $bill = $cust_main->bill_location;
1780 my $zip = $bill->zip;
1784 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1789 # minor false laziness with print_generic
1790 my ($previous_balance) = $self->previous;
1791 my $balance_due = $self->owed + $previous_balance;
1792 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1793 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1796 if ( $self->due_date and $time >= $self->due_date ) {
1797 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1801 my $header = sprintf(
1802 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1803 $cust_main->display_custnum, #BID
1804 uc($cust_main->first), #FNAME
1805 uc($cust_main->last), #LNAME
1806 '00', #BATCH, should this ever be anything else?
1807 uc($cust_main->company), #COMP
1808 uc($bill->address1), #STREET1
1809 uc($bill->address2), #STREET2
1810 uc($bill->city), #CITY
1811 uc($bill->state), #STATE
1814 time2str('%Y%m%d', $self->_date), #BILL_DATE
1815 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1816 ( map {sprintf('%0.2f', $_)}
1817 $balance_due, #AMNT_DUE
1818 $previous_balance, #PREV_BAL
1819 $payment_total, #PYMT_RCVD
1820 $credit_total, #CREDITS
1821 $previous_balance, #BEG_BAL--is this correct?
1822 $self->charged, #NEW_CHRG
1825 $past_due, #PAST_MSG
1829 my %svc_class = ('' => ''); # maybe cache this more persistently?
1831 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1833 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1834 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1838 my @dates = ( $self->_date, undef );
1839 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1840 $dates[1] = $prev->sdate; #questionable
1843 # generate an 01 detail for each service
1844 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1845 foreach my $cust_svc ( @svcs ) {
1846 $show_pkgnum = ''; # hide it if we're showing svcnums
1848 my $svcpart = $cust_svc->svcpart;
1849 if (!exists($svc_class{$svcpart})) {
1850 my $classnum = $cust_svc->part_svc->classnum;
1851 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1853 $svc_class{$svcpart} = $part_svc_class ?
1854 $part_svc_class->classname :
1858 my @h_label = $cust_svc->label(@dates, 'I');
1859 push @details, sprintf('01%-9s%-20s%-47s',
1861 $svc_class{$svcpart},
1864 } #foreach $cust_svc
1867 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1868 if ($cust_bill_pkg->recur > 0) {
1869 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1870 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1872 push @details, sprintf('02%-6s%-60s%-10s',
1875 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1877 } #foreach $cust_bill_pkg
1879 # Tag this row so that we know whether this is one page (1), two pages
1880 # (2), # or "big" (B). The tag will be stripped off before uploading.
1881 if ( scalar(@details) < 12 ) {
1883 } elsif ( scalar(@details) < 58 ) {
1889 return join('', $header, @details, "\n");
1897 time2str("%x", $self->_date),
1898 sprintf("%.2f", $self->charged),
1899 ( map { $cust_main->getfield($_) }
1900 qw( first last company address1 address2 city state zip country ) ),
1902 ) or die "can't create csv";
1905 my $header = $csv->string. "\n";
1908 if ( lc($opt{'format'}) eq 'billco' ) {
1911 my %items_opt = ( format => 'template',
1912 escape_function => sub { shift } );
1913 # I don't know what characters billco actually tolerates in spool entries.
1914 # Text::CSV will take care of delimiters, though.
1916 my @items = ( $self->_items_pkg(%items_opt),
1917 $self->_items_fee(%items_opt) );
1918 foreach my $item (@items) {
1920 my $description = $item->{'description'};
1921 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1922 $description .= ': ' . $item->{ext_description}[0];
1926 '', # 1 | N/A-Leave Empty CHAR 2
1927 '', # 2 | N/A-Leave Empty CHAR 15
1928 $tracctnum, # 3 | Account Number CHAR 15
1929 $self->invnum, # 4 | Invoice Number CHAR 15
1930 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1931 $description, # 6 | Transaction Detail CHAR 100
1932 $item->{'amount'}, # 7 | Amount NUM* 9
1933 '', # 8 | Line Format Control** CHAR 2
1934 '', # 9 | Grouping Code CHAR 2
1935 '', # 10 | User Defined CHAR 15
1938 $detail .= $csv->string. "\n";
1942 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1948 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1950 my($pkg, $setup, $recur, $sdate, $edate);
1951 if ( $cust_bill_pkg->pkgnum ) {
1953 ($pkg, $setup, $recur, $sdate, $edate) = (
1954 $cust_bill_pkg->part_pkg->pkg,
1955 ( $cust_bill_pkg->setup != 0
1956 ? sprintf("%.2f", $cust_bill_pkg->setup )
1958 ( $cust_bill_pkg->recur != 0
1959 ? sprintf("%.2f", $cust_bill_pkg->recur )
1961 ( $cust_bill_pkg->sdate
1962 ? time2str("%x", $cust_bill_pkg->sdate)
1964 ($cust_bill_pkg->edate
1965 ? time2str("%x", $cust_bill_pkg->edate)
1969 } else { #pkgnum tax
1970 next unless $cust_bill_pkg->setup != 0;
1971 $pkg = $cust_bill_pkg->desc;
1972 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1973 ( $sdate, $edate ) = ( '', '' );
1979 ( map { '' } (1..11) ),
1980 ($pkg, $setup, $recur, $sdate, $edate)
1981 ) or die "can't create csv";
1983 $detail .= $csv->string. "\n";
1989 ( $header, $detail );
1994 croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
1999 Attempts to pay this invoice with a credit card payment via a
2000 Business::OnlinePayment realtime gateway. See
2001 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2002 for supported processors.
2008 $self->realtime_bop( 'CC', @_ );
2013 Attempts to pay this invoice with an electronic check (ACH) payment via a
2014 Business::OnlinePayment realtime gateway. See
2015 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2016 for supported processors.
2022 $self->realtime_bop( 'ECHECK', @_ );
2027 Attempts to pay this invoice with phone bill (LEC) payment via a
2028 Business::OnlinePayment realtime gateway. See
2029 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2030 for supported processors.
2036 $self->realtime_bop( 'LEC', @_ );
2040 my( $self, $method ) = (shift,shift);
2041 my $conf = $self->conf;
2044 my $cust_main = $self->cust_main;
2045 my $balance = $cust_main->balance;
2046 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2047 $amount = sprintf("%.2f", $amount);
2048 return "not run (balance $balance)" unless $amount > 0;
2050 my $description = 'Internet Services';
2051 if ( $conf->exists('business-onlinepayment-description') ) {
2052 my $dtempl = $conf->config('business-onlinepayment-description');
2054 my $agent_obj = $cust_main->agent
2055 or die "can't retreive agent for $cust_main (agentnum ".
2056 $cust_main->agentnum. ")";
2057 my $agent = $agent_obj->agent;
2058 my $pkgs = join(', ',
2059 map { $_->part_pkg->pkg }
2060 grep { $_->pkgnum } $self->cust_bill_pkg
2062 $description = eval qq("$dtempl");
2065 $cust_main->realtime_bop($method, $amount,
2066 'description' => $description,
2067 'invnum' => $self->invnum,
2068 #this didn't do what we want, it just calls apply_payments_and_credits
2070 'apply_to_invoice' => 1,
2073 #this changes application behavior: auto payments
2074 #triggered against a specific invoice are now applied
2075 #to that invoice instead of oldest open.
2081 =item batch_card OPTION => VALUE...
2083 Adds a payment for this invoice to the pending credit card batch (see
2084 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2085 runs the payment using a realtime gateway.
2090 my ($self, %options) = @_;
2091 my $cust_main = $self->cust_main;
2093 $options{invnum} = $self->invnum;
2095 $cust_main->batch_card(%options);
2098 sub _agent_template {
2100 $self->cust_main->agent_template;
2103 sub _agent_invoice_from {
2105 $self->cust_main->agent_invoice_from;
2108 =item invoice_barcode DIR_OR_FALSE
2110 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2111 it is taken as the temp directory where the PNG file will be generated and the
2112 PNG file name is returned. Otherwise, the PNG image itself is returned.
2116 sub invoice_barcode {
2117 my ($self, $dir) = (shift,shift);
2119 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2120 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2121 my $gd = $gdbar->plot(Height => 30);
2124 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2128 ) or die "can't open temp file: $!\n";
2129 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2130 my $png_file = $bh->filename;
2137 =item invnum_date_pretty
2139 Returns a string with the invoice number and date, for example:
2140 "Invoice #54 (3/20/2008)".
2142 Intended for back-end context, with regard to translation and date formatting.
2146 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2147 # for backend use (and also does the wrong thing, localizing for end customer
2148 # instead of backoffice configured date format)
2149 sub invnum_date_pretty {
2151 #$self->mt('Invoice #').
2152 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2153 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2156 #sub _items_extra_usage_sections {
2158 # my $escape = shift;
2160 # my %sections = ();
2162 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2163 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2165 # next unless $cust_bill_pkg->pkgnum > 0;
2167 # foreach my $section ( keys %usage_class ) {
2169 # my $usage = $cust_bill_pkg->usage($section);
2171 # next unless $usage && $usage > 0;
2173 # $sections{$section} ||= 0;
2174 # $sections{$section} += $usage;
2180 # map { { 'description' => &{$escape}($_),
2181 # 'subtotal' => $sections{$_},
2182 # 'summarized' => '',
2183 # 'tax_section' => '',
2186 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2190 sub _items_extra_usage_sections {
2192 my $conf = $self->conf;
2200 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2202 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2203 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2204 next unless $cust_bill_pkg->pkgnum > 0;
2206 foreach my $classnum ( keys %usage_class ) {
2207 my $section = $usage_class{$classnum}->classname;
2208 $classnums{$section} = $classnum;
2210 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2211 my $amount = $detail->amount;
2212 next unless $amount && $amount > 0;
2214 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2215 $sections{$section}{amount} += $amount; #subtotal
2216 $sections{$section}{calls}++;
2217 $sections{$section}{duration} += $detail->duration;
2219 my $desc = $detail->regionname;
2220 my $description = $desc;
2221 $description = substr($desc, 0, $maxlength). '...'
2222 if $format eq 'latex' && length($desc) > $maxlength;
2224 $lines{$section}{$desc} ||= {
2225 description => &{$escape}($description),
2226 #pkgpart => $part_pkg->pkgpart,
2227 pkgnum => $cust_bill_pkg->pkgnum,
2232 #unit_amount => $cust_bill_pkg->unitrecur,
2233 quantity => $cust_bill_pkg->quantity,
2234 product_code => 'N/A',
2235 ext_description => [],
2238 $lines{$section}{$desc}{amount} += $amount;
2239 $lines{$section}{$desc}{calls}++;
2240 $lines{$section}{$desc}{duration} += $detail->duration;
2246 my %sectionmap = ();
2247 foreach (keys %sections) {
2248 my $usage_class = $usage_class{$classnums{$_}};
2249 $sectionmap{$_} = { 'description' => &{$escape}($_),
2250 'amount' => $sections{$_}{amount}, #subtotal
2251 'calls' => $sections{$_}{calls},
2252 'duration' => $sections{$_}{duration},
2254 'tax_section' => '',
2255 'sort_weight' => $usage_class->weight,
2256 ( $usage_class->format
2257 ? ( map { $_ => $usage_class->$_($format) }
2258 qw( description_generator header_generator total_generator total_line_generator )
2265 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2269 foreach my $section ( keys %lines ) {
2270 foreach my $line ( keys %{$lines{$section}} ) {
2271 my $l = $lines{$section}{$line};
2272 $l->{section} = $sectionmap{$section};
2273 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2274 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2279 return(\@sections, \@lines);
2285 my $end = $self->_date;
2287 # start at date of previous invoice + 1 second or 0 if no previous invoice
2288 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2289 $start = 0 if !$start;
2292 my $cust_main = $self->cust_main;
2293 my @pkgs = $cust_main->all_pkgs;
2294 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2297 foreach my $pkg ( @pkgs ) {
2298 my @h_cust_svc = $pkg->h_cust_svc($end);
2299 foreach my $h_cust_svc ( @h_cust_svc ) {
2300 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2301 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2303 my $inserted = $h_cust_svc->date_inserted;
2304 my $deleted = $h_cust_svc->date_deleted;
2305 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2307 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2309 # DID either activated or ported in; cannot be both for same DID simultaneously
2310 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2311 && (!$phone_inserted->lnp_status
2312 || $phone_inserted->lnp_status eq ''
2313 || $phone_inserted->lnp_status eq 'native')) {
2316 else { # this one not so clean, should probably move to (h_)svc_phone
2317 local($FS::Record::qsearch_qualify_columns) = 0;
2318 my $phone_portedin = qsearchs( 'h_svc_phone',
2319 { 'svcnum' => $h_cust_svc->svcnum,
2320 'lnp_status' => 'portedin' },
2321 FS::h_svc_phone->sql_h_searchs($end),
2323 $num_portedin++ if $phone_portedin;
2326 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2327 if($deleted >= $start && $deleted <= $end && $phone_deleted
2328 && (!$phone_deleted->lnp_status
2329 || $phone_deleted->lnp_status ne 'portingout')) {
2332 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2333 && $phone_deleted->lnp_status
2334 && $phone_deleted->lnp_status eq 'portingout') {
2338 # increment usage minutes
2339 if ( $phone_inserted ) {
2340 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2341 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2344 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2347 # don't look at this service again
2348 push @seen, $h_cust_svc->svcnum;
2352 $minutes = sprintf("%d", $minutes);
2353 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2354 . "$num_deactivated Ported-Out: $num_portedout ",
2355 "Total Minutes: $minutes");
2358 sub _items_accountcode_cdr {
2363 my $section = { 'amount' => 0,
2366 'sort_weight' => '',
2368 'description' => 'Usage by Account Code',
2374 my %accountcodes = ();
2376 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2377 next unless $cust_bill_pkg->pkgnum > 0;
2379 my @header = $cust_bill_pkg->details_header;
2380 next unless scalar(@header);
2381 $section->{'header'} = join(',',@header);
2383 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2385 $section->{'header'} = $detail->formatted('format' => $format)
2386 if($detail->detail eq $section->{'header'});
2388 my $accountcode = $detail->accountcode;
2389 next unless $accountcode;
2391 my $amount = $detail->amount;
2392 next unless $amount && $amount > 0;
2394 $accountcodes{$accountcode} ||= {
2395 description => $accountcode,
2402 product_code => 'N/A',
2403 section => $section,
2404 ext_description => [ $section->{'header'} ],
2408 $section->{'amount'} += $amount;
2409 $accountcodes{$accountcode}{'amount'} += $amount;
2410 $accountcodes{$accountcode}{calls}++;
2411 $accountcodes{$accountcode}{duration} += $detail->duration;
2412 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2416 foreach my $l ( values %accountcodes ) {
2417 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2418 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2419 foreach my $sorted_detail ( @sorted_detail ) {
2420 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2422 delete $l->{detail_temp};
2426 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2428 return ($section,\@sorted_lines);
2431 sub _items_svc_phone_sections {
2433 my $conf = $self->conf;
2441 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2443 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2444 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2446 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2447 next unless $cust_bill_pkg->pkgnum > 0;
2449 my @header = $cust_bill_pkg->details_header;
2450 next unless scalar(@header);
2452 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2454 my $phonenum = $detail->phonenum;
2455 next unless $phonenum;
2457 my $amount = $detail->amount;
2458 next unless $amount && $amount > 0;
2460 $sections{$phonenum} ||= { 'amount' => 0,
2463 'sort_weight' => -1,
2464 'phonenum' => $phonenum,
2466 $sections{$phonenum}{amount} += $amount; #subtotal
2467 $sections{$phonenum}{calls}++;
2468 $sections{$phonenum}{duration} += $detail->duration;
2470 my $desc = $detail->regionname;
2471 my $description = $desc;
2472 $description = substr($desc, 0, $maxlength). '...'
2473 if $format eq 'latex' && length($desc) > $maxlength;
2475 $lines{$phonenum}{$desc} ||= {
2476 description => &{$escape}($description),
2477 #pkgpart => $part_pkg->pkgpart,
2485 product_code => 'N/A',
2486 ext_description => [],
2489 $lines{$phonenum}{$desc}{amount} += $amount;
2490 $lines{$phonenum}{$desc}{calls}++;
2491 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2493 my $line = $usage_class{$detail->classnum}->classname;
2494 $sections{"$phonenum $line"} ||=
2498 'sort_weight' => $usage_class{$detail->classnum}->weight,
2499 'phonenum' => $phonenum,
2500 'header' => [ @header ],
2502 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2503 $sections{"$phonenum $line"}{calls}++;
2504 $sections{"$phonenum $line"}{duration} += $detail->duration;
2506 $lines{"$phonenum $line"}{$desc} ||= {
2507 description => &{$escape}($description),
2508 #pkgpart => $part_pkg->pkgpart,
2516 product_code => 'N/A',
2517 ext_description => [],
2520 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2521 $lines{"$phonenum $line"}{$desc}{calls}++;
2522 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2523 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2524 $detail->formatted('format' => $format);
2529 my %sectionmap = ();
2530 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2531 foreach ( keys %sections ) {
2532 my @header = @{ $sections{$_}{header} || [] };
2534 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2535 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2536 my $usage_class = $summary ? $simple : $usage_simple;
2537 my $ending = $summary ? ' usage charges' : '';
2540 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2542 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2543 'amount' => $sections{$_}{amount}, #subtotal
2544 'calls' => $sections{$_}{calls},
2545 'duration' => $sections{$_}{duration},
2547 'tax_section' => '',
2548 'phonenum' => $sections{$_}{phonenum},
2549 'sort_weight' => $sections{$_}{sort_weight},
2550 'post_total' => $summary, #inspire pagebreak
2552 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2553 qw( description_generator
2556 total_line_generator
2563 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2564 $a->{sort_weight} <=> $b->{sort_weight}
2569 foreach my $section ( keys %lines ) {
2570 foreach my $line ( keys %{$lines{$section}} ) {
2571 my $l = $lines{$section}{$line};
2572 $l->{section} = $sectionmap{$section};
2573 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2574 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2579 if($conf->exists('phone_usage_class_summary')) {
2580 # this only works with Latex
2584 # after this, we'll have only two sections per DID:
2585 # Calls Summary and Calls Detail
2586 foreach my $section ( @sections ) {
2587 if($section->{'post_total'}) {
2588 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2589 $section->{'total_line_generator'} = sub { '' };
2590 $section->{'total_generator'} = sub { '' };
2591 $section->{'header_generator'} = sub { '' };
2592 $section->{'description_generator'} = '';
2593 push @newsections, $section;
2594 my %calls_detail = %$section;
2595 $calls_detail{'post_total'} = '';
2596 $calls_detail{'sort_weight'} = '';
2597 $calls_detail{'description_generator'} = sub { '' };
2598 $calls_detail{'header_generator'} = sub {
2599 return ' & Date/Time & Called Number & Duration & Price'
2600 if $format eq 'latex';
2603 $calls_detail{'description'} = 'Calls Detail: '
2604 . $section->{'phonenum'};
2605 push @newsections, \%calls_detail;
2609 # after this, each usage class is collapsed/summarized into a single
2610 # line under the Calls Summary section
2611 foreach my $newsection ( @newsections ) {
2612 if($newsection->{'post_total'}) { # this means Calls Summary
2613 foreach my $section ( @sections ) {
2614 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2615 && !$section->{'post_total'});
2616 my $newdesc = $section->{'description'};
2617 my $tn = $section->{'phonenum'};
2618 $newdesc =~ s/$tn//g;
2619 my $line = { ext_description => [],
2623 calls => $section->{'calls'},
2624 section => $newsection,
2625 duration => $section->{'duration'},
2626 description => $newdesc,
2627 amount => sprintf("%.2f",$section->{'amount'}),
2628 product_code => 'N/A',
2630 push @newlines, $line;
2635 # after this, Calls Details is populated with all CDRs
2636 foreach my $newsection ( @newsections ) {
2637 if(!$newsection->{'post_total'}) { # this means Calls Details
2638 foreach my $line ( @lines ) {
2639 next unless (scalar(@{$line->{'ext_description'}}) &&
2640 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2642 my @extdesc = @{$line->{'ext_description'}};
2644 foreach my $extdesc ( @extdesc ) {
2645 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2646 push @newextdesc, $extdesc;
2648 $line->{'ext_description'} = \@newextdesc;
2649 $line->{'section'} = $newsection;
2650 push @newlines, $line;
2655 return(\@newsections, \@newlines);
2658 return(\@sections, \@lines);
2662 =sub _items_usage_class_summary OPTIONS
2664 Returns a list of detail items summarizing the usage charges on this
2665 invoice. Each one will have 'amount', 'description' (the usage charge name),
2666 and 'usage_classnum'.
2668 OPTIONS can include 'escape' (a function to escape the descriptions).
2672 sub _items_usage_class_summary {
2676 my $escape = $opt{escape} || sub { $_[0] };
2677 my $money_char = $opt{money_char};
2678 my $invnum = $self->invnum;
2679 my @classes = qsearch({
2680 'table' => 'usage_class',
2681 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2682 ' COUNT(*) AS calls, SUM(duration) AS duration',
2683 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2684 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2685 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2686 ' GROUP BY classnum, classname, weight'.
2687 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2688 ' ORDER BY weight ASC',
2692 description => &{$escape}($self->mt('Usage Summary')),
2696 foreach my $class (@classes) {
2697 $section->{subtotal} += $class->get('amount');
2699 'description' => &{$escape}($class->classname),
2700 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2701 'quantity' => $class->get('calls'),
2702 'duration' => $class->get('duration'),
2703 'usage_classnum' => $class->classnum,
2704 'section' => $section,
2707 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2711 sub _items_previous {
2713 my $conf = $self->conf;
2714 my $cust_main = $self->cust_main;
2715 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2717 foreach ( @pr_cust_bill ) {
2718 my $date = $conf->exists('invoice_show_prior_due_date')
2719 ? 'due '. $_->due_date2str('short')
2720 : $self->time2str_local('short', $_->_date);
2722 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2723 #'pkgpart' => 'N/A',
2725 'amount' => sprintf("%.2f", $_->owed),
2731 # 'description' => 'Previous Balance',
2732 # #'pkgpart' => 'N/A',
2733 # 'pkgnum' => 'N/A',
2734 # 'amount' => sprintf("%10.2f", $pr_total ),
2735 # 'ext_description' => [ map {
2736 # "Invoice ". $_->invnum.
2737 # " (". time2str("%x",$_->_date). ") ".
2738 # sprintf("%10.2f", $_->owed)
2739 # } @pr_cust_bill ],
2744 sub _items_credits {
2745 my( $self, %opt ) = @_;
2746 my $trim_len = $opt{'trim_len'} || 40;
2751 if ( $self->conf->exists('previous_balance-payments_since') ) {
2752 if ( $opt{'template'} eq 'statement' ) {
2753 # then the current bill is a "statement" (i.e. an invoice sent as
2754 # a payment receipt)
2755 # and in that case we want to see payments on or after THIS invoice
2756 @objects = qsearch('cust_credit', {
2757 'custnum' => $self->custnum,
2758 '_date' => {op => '>=', value => $self->_date},
2762 $date = $self->previous_bill->_date if $self->previous_bill;
2763 @objects = qsearch('cust_credit', {
2764 'custnum' => $self->custnum,
2765 '_date' => {op => '>=', value => $date},
2769 @objects = $self->cust_credited;
2772 foreach my $obj ( @objects ) {
2773 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2775 my $reason = substr($cust_credit->reason, 0, $trim_len);
2776 $reason .= '...' if length($reason) < length($cust_credit->reason);
2777 $reason = " ($reason) " if $reason;
2780 #'description' => 'Credit ref\#'. $_->crednum.
2781 # " (". time2str("%x",$_->cust_credit->_date) .")".
2783 'description' => $self->mt('Credit applied').' '.
2784 $self->time2str_local('short', $obj->_date). $reason,
2785 'amount' => sprintf("%.2f",$obj->amount),
2793 sub _items_payments {
2798 my $detailed = $self->conf->exists('invoice_payment_details');
2800 if ( $self->conf->exists('previous_balance-payments_since') ) {
2801 # then show payments dated on/after the previous bill...
2802 if ( $opt{'template'} eq 'statement' ) {
2803 # then the current bill is a "statement" (i.e. an invoice sent as
2804 # a payment receipt)
2805 # and in that case we want to see payments on or after THIS invoice
2806 @objects = qsearch('cust_pay', {
2807 'custnum' => $self->custnum,
2808 '_date' => {op => '>=', value => $self->_date},
2811 # the normal case: payments on or after the previous invoice
2813 $date = $self->previous_bill->_date if $self->previous_bill;
2814 @objects = qsearch('cust_pay', {
2815 'custnum' => $self->custnum,
2816 '_date' => {op => '>=', value => $date},
2818 # and before the current bill...
2819 @objects = grep { $_->_date < $self->_date } @objects;
2822 @objects = $self->cust_bill_pay;
2825 foreach my $obj (@objects) {
2826 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2827 my $desc = $self->mt('Payment received').' '.
2828 $self->time2str_local('short', $cust_pay->_date );
2829 $desc .= $self->mt(' via ') .
2830 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2834 'description' => $desc,
2835 'amount' => sprintf("%.2f", $obj->amount )
2845 my $conf = $self->conf;
2848 my ($pr_total) = $self->previous;
2849 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2851 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2852 # if enabled, specifically add a line for the previous balance total
2853 $previous_charges_desc = $self->mt(
2854 $conf->config('previous_balance-text') || 'Previous Balance'
2857 # then return separate lines for previous balance and total new charges
2860 { total_item => $previous_charges_desc,
2861 total_amount => sprintf('%.2f',$pr_total)
2866 if ( $conf->exists('previous_balance-exclude_from_total')
2867 or !$self->enable_previous ) {
2868 # show new charges only
2870 $new_charges_desc = $self->mt(
2871 $conf->config('previous_balance-text-total_new_charges')
2872 || 'Total New Charges'
2875 $new_charges_amount = $self->charged;
2878 # show new charges + previous invoice total
2880 $new_charges_desc = $self->mt('Total Charges');
2881 if ( $self->enable_previous ) {
2882 $new_charges_amount = sprintf('%.2f', $self->charged + $pr_total);
2884 $new_charges_amount = sprintf('%.2f', $self->charged);
2889 if ( $conf->exists('invoice_show_prior_due_date') ) {
2890 # then the due date should be shown with Total New Charges,
2891 # and should NOT be shown with the Balance Due message.
2892 if ( $self->due_date ) {
2893 # localize the "Please pay by" message and the date itself
2894 # (grammar issues with this, yeah)
2895 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2896 $self->due_date2str('short');
2897 } elsif ( $self->terms ) {
2898 # phrases like "due on receipt" should be localized
2899 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2904 { total_item => $new_charges_desc,
2905 total_amount => $new_charges_amount,
2913 =item has_call_details
2915 Returns true if this invoice has call details.
2919 sub has_call_details {
2922 SELECT 1 FROM cust_bill_pkg_detail
2923 LEFT JOIN cust_bill_pkg USING (billpkgnum)
2924 WHERE cust_bill_pkg_detail.format = 'C'
2925 AND cust_bill_pkg.invnum = ?
2930 =item call_details [ OPTION => VALUE ... ]
2932 Returns an array of CSV strings representing the call details for this invoice
2933 The only option available is the boolean prepend_billed_number
2938 my ($self, %opt) = @_;
2940 my $format_function = sub { shift };
2942 if ($opt{prepend_billed_number}) {
2943 $format_function = sub {
2947 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2952 my @details = map { $_->details( 'format_function' => $format_function,
2953 'escape_function' => sub{ return() },
2957 $self->cust_bill_pkg;
2958 my $header = $details[0];
2959 ( $header, grep { $_ ne $header } @details );
2962 =item cust_pay_batch
2964 Returns all L<FS::cust_pay_batch> records linked to this invoice. Deprecated,
2969 sub cust_pay_batch {
2970 carp "FS::cust_bill->cust_pay_batch is deprecated";
2972 qsearch('cust_pay_batch', { 'invnum' => $self->invnum });
2981 =item process_reprint
2985 sub process_reprint {
2986 process_re_X('print', @_);
2989 =item process_reemail
2993 sub process_reemail {
2994 process_re_X('email', @_);
3002 process_re_X('fax', @_);
3010 process_re_X('ftp', @_);
3017 sub process_respool {
3018 process_re_X('spool', @_);
3023 my( $method, $job ) = ( shift, shift );
3024 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3027 warn Dumper($param) if $DEBUG;
3037 # this is called from search/cust_bill.html and given all its search
3038 # parameters, so it needs to perform the same search.
3041 # spool_invoice ftp_invoice fax_invoice print_invoice
3042 my($method, $job, %param ) = @_;
3044 warn "re_X $method for job $job with param:\n".
3045 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3048 #some false laziness w/search/cust_bill.html
3049 $param{'order_by'} = 'cust_bill._date';
3051 my $query = FS::cust_bill->search(\%param);
3052 delete $query->{'count_query'};
3053 delete $query->{'count_addl'};
3055 $query->{debug} = 1; # was in here before, is obviously useful
3057 my @cust_bill = qsearch( $query );
3059 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3061 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3064 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3065 foreach my $cust_bill ( @cust_bill ) {
3066 $cust_bill->$method();
3068 if ( $job ) { #progressbar foo
3070 if ( time - $min_sec > $last ) {
3071 my $error = $job->update_statustext(
3072 int( 100 * $num / scalar(@cust_bill) )
3074 die $error if $error;
3085 +{ ( map { $_=>$self->$_ } $self->fields ),
3086 'owed' => $self->owed,
3087 #XXX last payment applied date
3093 =head1 CLASS METHODS
3099 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3104 my ($class, $start, $end) = @_;
3106 $class->paid_sql($start, $end). ' - '.
3107 $class->credited_sql($start, $end);
3112 Returns an SQL fragment to retreive the net amount (charged minus credited).
3117 my ($class, $start, $end) = @_;
3118 'charged - '. $class->credited_sql($start, $end);
3123 Returns an SQL fragment to retreive the amount paid against this invoice.
3128 my ($class, $start, $end) = @_;
3129 $start &&= "AND cust_bill_pay._date <= $start";
3130 $end &&= "AND cust_bill_pay._date > $end";
3131 $start = '' unless defined($start);
3132 $end = '' unless defined($end);
3133 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3134 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3139 Returns an SQL fragment to retreive the amount credited against this invoice.
3144 my ($class, $start, $end) = @_;
3145 $start &&= "AND cust_credit_bill._date <= $start";
3146 $end &&= "AND cust_credit_bill._date > $end";
3147 $start = '' unless defined($start);
3148 $end = '' unless defined($end);
3149 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3150 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3155 Returns an SQL fragment to retrieve the due date of an invoice.
3156 Currently only supported on PostgreSQL.
3161 die "don't use: doesn't account for agent-specific invoice_default_terms";
3163 #we're passed a $conf but not a specific customer (that's in the query), so
3164 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3165 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3168 my $conf = new FS::Conf;
3172 cust_bill.invoice_terms,
3173 cust_main.invoice_terms,
3174 \''.($conf->config('invoice_default_terms') || '').'\'
3175 ), E\'Net (\\\\d+)\'
3177 ) * 86400 + cust_bill._date'
3188 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3189 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base