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_'; }
152 my $agentnum = $self->cust_main->agentnum;
153 my $tc = $self->template_conf;
155 $self->conf->exists($tc.'sections', $agentnum) ||
156 $self->conf->exists($tc.'sections_by_location', $agentnum);
159 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
160 # (except email_subject and invnum_date_pretty)
163 $self->conf->config('notice_name') || 'Invoice'
166 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
167 sub cust_unlinked_msg {
169 "WARNING: can't find cust_main.custnum ". $self->custnum.
170 ' (cust_bill.invnum '. $self->invnum. ')';
175 Adds this invoice to the database ("Posts" the invoice). If there is an error,
176 returns the error, otherwise returns false.
182 warn "$me insert called\n" if $DEBUG;
184 local $SIG{HUP} = 'IGNORE';
185 local $SIG{INT} = 'IGNORE';
186 local $SIG{QUIT} = 'IGNORE';
187 local $SIG{TERM} = 'IGNORE';
188 local $SIG{TSTP} = 'IGNORE';
189 local $SIG{PIPE} = 'IGNORE';
191 my $oldAutoCommit = $FS::UID::AutoCommit;
192 local $FS::UID::AutoCommit = 0;
195 my $error = $self->SUPER::insert;
197 $dbh->rollback if $oldAutoCommit;
201 if ( $self->get('cust_bill_pkg') ) {
202 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
203 $cust_bill_pkg->invnum($self->invnum);
204 my $error = $cust_bill_pkg->insert;
206 $dbh->rollback if $oldAutoCommit;
207 return "can't create invoice line item: $error";
212 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
217 =item void [ REASON ]
219 Voids this invoice: deletes the invoice and adds a record of the voided invoice
220 to the FS::cust_bill_void table (and related tables starting from
221 FS::cust_bill_pkg_void).
227 my $reason = scalar(@_) ? shift : '';
229 unless (ref($reason) || !$reason) {
230 $reason = FS::reason->new_or_existing(
232 'type' => 'Invoice void',
237 local $SIG{HUP} = 'IGNORE';
238 local $SIG{INT} = 'IGNORE';
239 local $SIG{QUIT} = 'IGNORE';
240 local $SIG{TERM} = 'IGNORE';
241 local $SIG{TSTP} = 'IGNORE';
242 local $SIG{PIPE} = 'IGNORE';
244 my $oldAutoCommit = $FS::UID::AutoCommit;
245 local $FS::UID::AutoCommit = 0;
248 my $cust_bill_void = new FS::cust_bill_void ( {
249 map { $_ => $self->get($_) } $self->fields
251 $cust_bill_void->reasonnum($reason->reasonnum) if $reason;
252 my $error = $cust_bill_void->insert;
254 $dbh->rollback if $oldAutoCommit;
258 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
259 my $error = $cust_bill_pkg->void($reason);
261 $dbh->rollback if $oldAutoCommit;
266 $error = $self->_delete;
268 $dbh->rollback if $oldAutoCommit;
272 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
278 # removed docs entirely and renamed method to _delete to further indicate it is
279 # internal-only and discourage use
283 # DO NOT USE THIS METHOD. Instead, apply a credit against the invoice, or use
284 # the B<void> method.
286 # This is only for internal use by V<void>, which is what you should be using.
288 # DO NOT USE THIS METHOD. Whatever reason you think you have is almost certainly
289 # wrong. Use B<void>, that's what it is for. Really. This means you.
295 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
297 local $SIG{HUP} = 'IGNORE';
298 local $SIG{INT} = 'IGNORE';
299 local $SIG{QUIT} = 'IGNORE';
300 local $SIG{TERM} = 'IGNORE';
301 local $SIG{TSTP} = 'IGNORE';
302 local $SIG{PIPE} = 'IGNORE';
304 my $oldAutoCommit = $FS::UID::AutoCommit;
305 local $FS::UID::AutoCommit = 0;
308 foreach my $table (qw(
315 #cust_event # problematic
316 #cust_pay_batch # unnecessary
318 foreach my $linked ( $self->$table() ) {
319 my $error = $linked->delete;
321 $dbh->rollback if $oldAutoCommit;
328 my $error = $self->SUPER::delete(@_);
330 $dbh->rollback if $oldAutoCommit;
334 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
340 =item replace [ OLD_RECORD ]
342 You can, but probably shouldn't modify invoices...
344 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
345 supplied, replaces this record. If there is an error, returns the error,
346 otherwise returns false.
350 #replace can be inherited from Record.pm
352 # replace_check is now the preferred way to #implement replace data checks
353 # (so $object->replace() works without an argument)
356 my( $new, $old ) = ( shift, shift );
357 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
358 #return "Can't change _date!" unless $old->_date eq $new->_date;
359 return "Can't change _date" unless $old->_date == $new->_date;
360 return "Can't change charged" unless $old->charged == $new->charged
361 || $old->pending eq 'Y'
362 || $old->charged == 0
363 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
369 =item add_cc_surcharge
375 sub add_cc_surcharge {
376 my ($self, $pkgnum, $amount) = (shift, shift, shift);
379 my $cust_bill_pkg = new FS::cust_bill_pkg({
380 'invnum' => $self->invnum,
384 $error = $cust_bill_pkg->insert;
385 return $error if $error;
387 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
388 $self->charged($self->charged+$amount);
389 $error = $self->replace;
390 return $error if $error;
392 $self->apply_payments_and_credits;
398 Checks all fields to make sure this is a valid invoice. If there is an error,
399 returns the error, otherwise returns false. Called by the insert and replace
408 $self->ut_numbern('invnum')
409 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
410 || $self->ut_numbern('_date')
411 || $self->ut_money('charged')
412 || $self->ut_numbern('printed')
413 || $self->ut_enum('closed', [ '', 'Y' ])
414 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
415 || $self->ut_numbern('agent_invid') #varchar?
416 || $self->ut_flag('pending')
418 return $error if $error;
420 $self->_date(time) unless $self->_date;
422 $self->printed(0) if $self->printed eq '';
429 Returns the displayed invoice number for this invoice: agent_invid if
430 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
436 if ( $self->agent_invid
437 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
438 return $self->agent_invid;
440 return $self->invnum;
446 Returns the customer's last invoice before this one.
452 if ( !$self->get('previous_bill') ) {
453 $self->set('previous_bill', qsearchs({
454 'table' => 'cust_bill',
455 'hashref' => { 'custnum' => $self->custnum,
456 '_date' => { op=>'<', value=>$self->_date } },
457 'order_by' => 'ORDER BY _date DESC LIMIT 1',
460 $self->get('previous_bill');
465 Returns a list consisting of the total previous balance for this customer,
466 followed by the previous outstanding invoices (as FS::cust_bill objects also).
472 # simple memoize; we use this a lot
473 if (!$self->get('previous')) {
475 my @cust_bill = sort { $a->_date <=> $b->_date }
476 grep { $_->owed != 0 }
477 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
478 #'_date' => { op=>'<', value=>$self->_date },
479 'invnum' => { op=>'<', value=>$self->invnum },
482 foreach ( @cust_bill ) { $total += $_->owed; }
483 $self->set('previous', [$total, @cust_bill]);
485 return @{ $self->get('previous') };
488 =item enable_previous
490 Whether to show the 'Previous Charges' section when printing this invoice.
491 The negation of the 'disable_previous_balance' config setting.
495 sub enable_previous {
497 my $agentnum = $self->cust_main->agentnum;
498 !$self->conf->exists('disable_previous_balance', $agentnum);
503 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
510 { 'table' => 'cust_bill_pkg',
511 'hashref' => { 'invnum' => $self->invnum },
512 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
513 # the AUTLOADED FK search. or should
514 # that default to ORDER by the pkey?
519 =item cust_bill_pkg_pkgnum PKGNUM
521 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
526 sub cust_bill_pkg_pkgnum {
527 my( $self, $pkgnum ) = @_;
529 { 'table' => 'cust_bill_pkg',
530 'hashref' => { 'invnum' => $self->invnum,
533 'order_by' => 'ORDER BY billpkgnum',
540 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
547 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
548 $self->cust_bill_pkg;
550 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
555 Returns true if any of the packages (or their definitions) corresponding to the
556 line items for this invoice have the no_auto flag set.
562 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
565 =item open_cust_bill_pkg
567 Returns the open line items for this invoice.
569 Note that cust_bill_pkg with both setup and recur fees are returned as two
570 separate line items, each with only one fee.
574 # modeled after cust_main::open_cust_bill
575 sub open_cust_bill_pkg {
578 # grep { $_->owed > 0 } $self->cust_bill_pkg
580 my %other = ( 'recur' => 'setup',
581 'setup' => 'recur', );
583 foreach my $field ( qw( recur setup )) {
584 push @open, map { $_->set( $other{$field}, 0 ); $_; }
585 grep { $_->owed($field) > 0 }
586 $self->cust_bill_pkg;
594 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
598 #false laziness w/cust_pkg.pm
602 'table' => 'cust_event',
603 'addl_from' => 'JOIN part_event USING ( eventpart )',
604 'hashref' => { 'tablenum' => $self->invnum },
605 'extra_sql' => " AND eventtable = 'cust_bill' ",
611 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
615 #false laziness w/cust_pkg.pm
619 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
620 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
621 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
622 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
623 $sth->fetchrow_arrayref->[0];
628 Returns the customer (see L<FS::cust_main>) for this invoice.
632 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice
634 Returns a list: an empty list on success or a list of errors.
641 grep { $_->suspend(@_) }
642 grep {! $_->getfield('cancel') }
647 =item cust_suspend_if_balance_over AMOUNT
649 Suspends the customer associated with this invoice if the total amount owed on
650 this invoice and all older invoices is greater than the specified amount.
652 Returns a list: an empty list on success or a list of errors.
656 sub cust_suspend_if_balance_over {
657 my( $self, $amount ) = ( shift, shift );
658 my $cust_main = $self->cust_main;
659 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
662 $cust_main->suspend(@_);
668 Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options
673 my( $self, %opt ) = @_;
675 warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
676 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
679 return ( 'Access denied' )
680 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
682 my @pkgs = $self->cust_pkg;
684 if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
686 my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
687 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
692 map { $_->cancel(%opt) }
693 grep { ! $_->getfield('cancel') }
699 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
705 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
706 sort { $a->_date <=> $b->_date }
707 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
712 =item cust_credit_bill
714 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
720 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
721 sort { $a->_date <=> $b->_date }
722 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
726 sub cust_credit_bill {
727 shift->cust_credited(@_);
730 #=item cust_bill_pay_pkgnum PKGNUM
732 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
733 #with matching pkgnum.
737 #sub cust_bill_pay_pkgnum {
738 # my( $self, $pkgnum ) = @_;
739 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
740 # sort { $a->_date <=> $b->_date }
741 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
742 # 'pkgnum' => $pkgnum,
747 =item cust_bill_pay_pkg PKGNUM
749 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
750 applied against the matching pkgnum.
754 sub cust_bill_pay_pkg {
755 my( $self, $pkgnum ) = @_;
758 'select' => 'cust_bill_pay_pkg.*',
759 'table' => 'cust_bill_pay_pkg',
760 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
761 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
762 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
763 " AND cust_bill_pkg.pkgnum = $pkgnum",
768 #=item cust_credited_pkgnum PKGNUM
770 #=item cust_credit_bill_pkgnum PKGNUM
772 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
773 #with matching pkgnum.
777 #sub cust_credited_pkgnum {
778 # my( $self, $pkgnum ) = @_;
779 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
780 # sort { $a->_date <=> $b->_date }
781 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
782 # 'pkgnum' => $pkgnum,
787 #sub cust_credit_bill_pkgnum {
788 # shift->cust_credited_pkgnum(@_);
791 =item cust_credit_bill_pkg PKGNUM
793 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
794 applied against the matching pkgnum.
798 sub cust_credit_bill_pkg {
799 my( $self, $pkgnum ) = @_;
802 'select' => 'cust_credit_bill_pkg.*',
803 'table' => 'cust_credit_bill_pkg',
804 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
805 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
806 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
807 " AND cust_bill_pkg.pkgnum = $pkgnum",
812 =item cust_bill_batch
814 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
818 sub cust_bill_batch {
820 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
825 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
826 hash keyed by term length.
832 FS::discount_plan->all($self);
837 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
844 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
846 foreach (@taxlines) { $total += $_->setup; }
852 Returns the amount owed (still outstanding) on this invoice, which is charged
853 minus all payment applications (see L<FS::cust_bill_pay>) and credit
854 applications (see L<FS::cust_credit_bill>).
860 my $balance = $self->charged;
861 $balance -= $_->amount foreach ( $self->cust_bill_pay );
862 $balance -= $_->amount foreach ( $self->cust_credited );
863 $balance = sprintf( "%.2f", $balance);
864 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
869 my( $self, $pkgnum ) = @_;
871 #my $balance = $self->charged;
873 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
875 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
876 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
878 $balance = sprintf( "%.2f", $balance);
879 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
885 Returns true if this invoice should be hidden. See the
886 selfservice-hide_invoices-taxclass configuraiton setting.
892 my $conf = $self->conf;
893 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
895 my @cust_bill_pkg = $self->cust_bill_pkg;
896 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
897 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
900 =item apply_payments_and_credits [ OPTION => VALUE ... ]
902 Applies unapplied payments and credits to this invoice.
903 Payments with the no_auto_apply flag set will not be applied.
905 A hash of optional arguments may be passed. Currently "manual" is supported.
906 If true, a payment receipt is sent instead of a statement when
907 'payment_receipt_email' configuration option is set.
909 If there is an error, returns the error, otherwise returns false.
913 sub apply_payments_and_credits {
914 my( $self, %options ) = @_;
915 my $conf = $self->conf;
917 local $SIG{HUP} = 'IGNORE';
918 local $SIG{INT} = 'IGNORE';
919 local $SIG{QUIT} = 'IGNORE';
920 local $SIG{TERM} = 'IGNORE';
921 local $SIG{TSTP} = 'IGNORE';
922 local $SIG{PIPE} = 'IGNORE';
924 my $oldAutoCommit = $FS::UID::AutoCommit;
925 local $FS::UID::AutoCommit = 0;
928 $self->select_for_update; #mutex
930 my @payments = grep { $_->unapplied > 0 }
931 grep { !$_->no_auto_apply }
932 $self->cust_main->cust_pay;
933 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
935 if ( $conf->exists('pkg-balances') ) {
936 # limit @payments & @credits to those w/ a pkgnum grepped from $self
937 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
938 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
939 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
942 while ( $self->owed > 0 and ( @payments || @credits ) ) {
945 if ( @payments && @credits ) {
947 #decide which goes first by weight of top (unapplied) line item
949 my @open_lineitems = $self->open_cust_bill_pkg;
952 max( map { $_->part_pkg->pay_weight || 0 }
957 my $max_credit_weight =
958 max( map { $_->part_pkg->credit_weight || 0 }
964 #if both are the same... payments first? it has to be something
965 if ( $max_pay_weight >= $max_credit_weight ) {
971 } elsif ( @payments ) {
973 } elsif ( @credits ) {
976 die "guru meditation #12 and 35";
980 if ( $app eq 'pay' ) {
982 my $payment = shift @payments;
983 $unapp_amount = $payment->unapplied;
984 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
985 $app->pkgnum( $payment->pkgnum )
986 if $conf->exists('pkg-balances') && $payment->pkgnum;
988 } elsif ( $app eq 'credit' ) {
990 my $credit = shift @credits;
991 $unapp_amount = $credit->credited;
992 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
993 $app->pkgnum( $credit->pkgnum )
994 if $conf->exists('pkg-balances') && $credit->pkgnum;
997 die "guru meditation #12 and 35";
1001 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1002 warn "owed_pkgnum ". $app->pkgnum;
1003 $owed = $self->owed_pkgnum($app->pkgnum);
1005 $owed = $self->owed;
1007 next unless $owed > 0;
1009 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1010 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1012 $app->invnum( $self->invnum );
1014 my $error = $app->insert(%options);
1016 $dbh->rollback if $oldAutoCommit;
1017 return "Error inserting ". $app->table. " record: $error";
1019 die $error if $error;
1023 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1030 Sends this invoice to the destinations configured for this customer: sends
1031 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1033 Options can be passed as a hashref. Positional parameters are no longer
1036 I<template>: a suffix for alternate invoices
1038 I<agentnum>: obsolete, now does nothing.
1040 I<from> overrides the default email invoice From: address.
1042 I<amount>: obsolete, does nothing
1044 I<notice_name> overrides "Invoice" as the name of the sent document
1045 (templates from 10/2009 or newer required).
1047 I<lpr> overrides the system 'lpr' option as the command to print a document
1048 from standard input.
1054 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1055 my $conf = $self->conf;
1057 my $cust_main = $self->cust_main;
1059 my @invoicing_list = $cust_main->invoicing_list;
1062 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1063 && ! $cust_main->invoice_noemail;
1066 if grep { $_ eq 'POST' } @invoicing_list; #postal
1068 #this has never been used post-$ORIGINAL_ISP afaik
1069 $self->fax_invoice($opt)
1070 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1078 my $opt = shift || {};
1079 if ($opt and !ref($opt)) {
1080 die ref($self). '->email called with positional parameters';
1083 my $conf = $self->conf;
1085 my $from = delete $opt->{from};
1087 # this is where we set the From: address
1088 $from ||= $self->_agent_invoice_from || #XXX should go away
1089 $conf->invoice_from_full( $self->cust_main->agentnum );
1091 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1093 if ( ! @invoicing_list ) { #no recipients
1094 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1095 die 'No recipients for customer #'. $self->custnum;
1097 #default: better to notify this person than silence
1098 @invoicing_list = ($from);
1102 $self->SUPER::email( {
1104 'to' => \@invoicing_list,
1110 #this stays here for now because its explicitly used as
1111 # FS::cust_bill::queueable_email
1112 sub queueable_email {
1115 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1116 or die "invalid invoice number: " . $opt{invnum};
1118 $self->set('mode', $opt{mode})
1121 my %args = map {$_ => $opt{$_}}
1123 qw( from notice_name no_coupon template );
1125 my $error = $self->email( \%args );
1126 die $error if $error;
1132 my $conf = $self->conf;
1134 #my $template = scalar(@_) ? shift : '';
1137 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1140 my $cust_main = $self->cust_main;
1141 my $name = $cust_main->name;
1142 my $name_short = $cust_main->name_short;
1143 my $invoice_number = $self->invnum;
1144 my $invoice_date = $self->_date_pretty;
1146 eval qq("$subject");
1151 'Invoice-'. $self->invnum. '.pdf';
1154 =item lpr_data HASHREF
1156 Returns the postscript or plaintext for this invoice as an arrayref.
1158 Options must be passed as a hashref. Positional parameters are no longer
1161 I<template>, if specified, is the name of a suffix for alternate invoices.
1163 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1169 my $conf = $self->conf;
1170 my $opt = shift || {};
1171 if ($opt and !ref($opt)) {
1172 # nobody does this anyway
1173 die "FS::cust_bill::lpr_data called with positional parameters";
1176 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1177 [ $self->$method( $opt ) ];
1182 Prints this invoice.
1184 Options must be passed as a hashref.
1186 I<template>, if specified, is the name of a suffix for alternate invoices.
1188 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1194 return if $self->hide;
1195 my $conf = $self->conf;
1196 my $opt = shift || {};
1197 if ($opt and !ref($opt)) {
1198 die "FS::cust_bill::print called with positional parameters";
1201 my $lpr = delete $opt->{lpr};
1202 if($conf->exists('invoice_print_pdf')) {
1203 # Add the invoice to the current batch.
1204 $self->batch_invoice($opt);
1208 $self->lpr_data($opt),
1209 'agentnum' => $self->cust_main->agentnum,
1215 =item fax_invoice HASHREF
1219 Options must be passed as a hashref.
1221 I<template>, if specified, is the name of a suffix for alternate invoices.
1223 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1229 return if $self->hide;
1230 my $conf = $self->conf;
1231 my $opt = shift || {};
1232 if ($opt and !ref($opt)) {
1233 die "FS::cust_bill::fax_invoice called with positional parameters";
1236 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1237 unless $conf->exists('invoice_latex');
1239 my $dialstring = $self->cust_main->getfield('fax');
1242 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1243 'dialstring' => $dialstring,
1245 die $error if $error;
1249 =item batch_invoice [ HASHREF ]
1251 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1252 isn't an open batch, one will be created.
1254 HASHREF may contain any options to be passed to C<print_pdf>.
1259 my ($self, $opt) = @_;
1260 my $bill_batch = $self->get_open_bill_batch;
1261 my $cust_bill_batch = FS::cust_bill_batch->new({
1262 batchnum => $bill_batch->batchnum,
1263 invnum => $self->invnum,
1265 if ( $self->mode ) {
1266 $opt->{mode} ||= $self->mode;
1267 $opt->{mode} = $opt->{mode}->modenum if ref $opt->{mode};
1269 return $cust_bill_batch->insert($opt);
1272 =item get_open_batch
1274 Returns the currently open batch as an FS::bill_batch object, creating a new
1275 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1280 sub get_open_bill_batch {
1282 my $conf = $self->conf;
1283 my $hashref = { status => 'O' };
1284 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1285 ? $self->cust_main->agentnum
1287 my $batch = qsearchs('bill_batch', $hashref);
1288 return $batch if $batch;
1289 $batch = FS::bill_batch->new($hashref);
1290 my $error = $batch->insert;
1291 die $error if $error;
1295 =item ftp_invoice [ TEMPLATENAME ]
1297 Sends this invoice data via FTP.
1299 TEMPLATENAME is unused?
1305 my $conf = $self->conf;
1306 my $template = scalar(@_) ? shift : '';
1309 'protocol' => 'ftp',
1310 'server' => $conf->config('cust_bill-ftpserver'),
1311 'username' => $conf->config('cust_bill-ftpusername'),
1312 'password' => $conf->config('cust_bill-ftppassword'),
1313 'dir' => $conf->config('cust_bill-ftpdir'),
1314 'format' => $conf->config('cust_bill-ftpformat'),
1318 =item spool_invoice [ TEMPLATENAME ]
1320 Spools this invoice data (see L<FS::spool_csv>)
1322 TEMPLATENAME is unused?
1328 my $conf = $self->conf;
1329 my $template = scalar(@_) ? shift : '';
1332 'format' => $conf->config('cust_bill-spoolformat'),
1333 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1337 =item send_csv OPTION => VALUE, ...
1339 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1343 protocol - currently only "ftp"
1349 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1350 and YYMMDDHHMMSS is a timestamp.
1352 See L</print_csv> for a description of the output format.
1357 my($self, %opt) = @_;
1361 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1362 mkdir $spooldir, 0700 unless -d $spooldir;
1364 # don't localize dates here, they're a defined format
1365 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1366 my $file = "$spooldir/$tracctnum.csv";
1368 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1370 open(CSV, ">$file") or die "can't open $file: $!";
1378 if ( $opt{protocol} eq 'ftp' ) {
1379 eval "use Net::FTP;";
1381 $net = Net::FTP->new($opt{server}) or die @$;
1383 die "unknown protocol: $opt{protocol}";
1386 $net->login( $opt{username}, $opt{password} )
1387 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1389 $net->binary or die "can't set binary mode";
1391 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1393 $net->put($file) or die "can't put $file: $!";
1403 Spools CSV invoice data.
1409 =item format - any of FS::Misc::::Invoicing::spool_formats
1411 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1412 customer has the corresponding invoice destinations set (see
1413 L<FS::cust_main_invoice>).
1415 =item agent_spools - if set to a true value, will spool to per-agent files
1416 rather than a single global file
1418 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1419 append to that spool. L<FS::Cron::upload> will then send the spool file to
1422 =item balanceover - if set, only spools the invoice if the total amount owed on
1423 this invoice and all older invoices is greater than the specified amount.
1425 =item time - the "current time". Controls the printing of past due messages
1433 my($self, %opt) = @_;
1435 my $time = $opt{'time'} || time;
1436 my $cust_main = $self->cust_main;
1438 if ( $opt{'dest'} ) {
1439 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1440 $cust_main->invoicing_list;
1441 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1442 || ! keys %invoicing_list;
1445 if ( $opt{'balanceover'} ) {
1447 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1450 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1451 mkdir $spooldir, 0700 unless -d $spooldir;
1453 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1456 if ( $opt{'agent_spools'} ) {
1457 $file = 'agentnum'.$cust_main->agentnum;
1462 if ( $opt{'upload_targetnum'} ) {
1463 $spooldir .= '/target'.$opt{'upload_targetnum'};
1464 mkdir $spooldir, 0700 unless -d $spooldir;
1465 } # otherwise it just goes into export.xxx/cust_bill
1467 if ( lc($opt{'format'}) eq 'billco' ) {
1471 $file = "$spooldir/$file.csv";
1473 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1475 open(CSV, ">>$file") or die "can't open $file: $!";
1476 flock(CSV, LOCK_EX);
1481 if ( lc($opt{'format'}) eq 'billco' ) {
1483 flock(CSV, LOCK_UN);
1486 $file =~ s/-header.csv$/-detail.csv/;
1488 open(CSV,">>$file") or die "can't open $file: $!";
1489 flock(CSV, LOCK_EX);
1493 print CSV $detail if defined($detail);
1495 flock(CSV, LOCK_UN);
1502 =item print_csv OPTION => VALUE, ...
1504 Returns CSV data for this invoice.
1508 format - 'default', 'billco', 'oneline', 'bridgestone'
1510 Returns a list consisting of two scalars. The first is a single line of CSV
1511 header information for this invoice. The second is one or more lines of CSV
1512 detail information for this invoice.
1514 If I<format> is not specified or "default", the fields of the CSV file are as
1517 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1518 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1522 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1524 B<record_type> is C<cust_bill> for the initial header line only. The
1525 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1526 fields are filled in.
1528 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1529 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1532 =item invnum - invoice number
1534 =item custnum - customer number
1536 =item _date - invoice date
1538 =item charged - total invoice amount
1540 =item first - customer first name
1542 =item last - customer first name
1544 =item company - company name
1546 =item address1 - address line 1
1548 =item address2 - address line 1
1558 =item pkg - line item description
1560 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1562 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1564 =item sdate - start date for recurring fee
1566 =item edate - end date for recurring fee
1570 If I<format> is "billco", the fields of the header CSV file are as follows:
1572 +-------------------------------------------------------------------+
1573 | FORMAT HEADER FILE |
1574 |-------------------------------------------------------------------|
1575 | Field | Description | Name | Type | Width |
1576 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1577 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1578 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1579 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1580 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1581 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1582 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1583 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1584 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1585 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1586 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1587 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1588 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1589 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1590 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1591 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1592 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1593 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1594 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1595 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1596 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1597 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1598 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1599 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1600 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1601 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1602 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1603 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1604 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1605 +-------+-------------------------------+------------+------+-------+
1607 If I<format> is "billco", the fields of the detail CSV file are as follows:
1609 FORMAT FOR DETAIL FILE
1611 Field | Description | Name | Type | Width
1612 1 | N/A-Leave Empty | RC | CHAR | 2
1613 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1614 3 | Account Number | TRACCTNUM | CHAR | 15
1615 4 | Invoice Number | TRINVOICE | CHAR | 15
1616 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1617 6 | Transaction Detail | DETAILS | CHAR | 100
1618 7 | Amount | AMT | NUM* | 9
1619 8 | Line Format Control** | LNCTRL | CHAR | 2
1620 9 | Grouping Code | GROUP | CHAR | 2
1621 10 | User Defined | ACCT CODE | CHAR | 15
1623 If format is 'oneline', there is no detail file. Each invoice has a
1624 header line only, with the fields:
1626 Agent number, agent name, customer number, first name, last name, address
1627 line 1, address line 2, city, state, zip, invoice date, invoice number,
1628 amount charged, amount due, previous balance, due date.
1630 and then, for each line item, three columns containing the package number,
1631 description, and amount.
1633 If format is 'bridgestone', there is no detail file. Each invoice has a
1634 header line with the following fields in a fixed-width format:
1636 Customer number (in display format), date, name (first last), company,
1637 address 1, address 2, city, state, zip.
1639 This is a mailing list format, and has no per-invoice fields. To avoid
1640 sending redundant notices, the spooling event should have a "once" or
1641 "once_percust_every" condition.
1646 my($self, %opt) = @_;
1648 eval "use Text::CSV_XS";
1651 my $cust_main = $self->cust_main;
1653 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1654 my $format = lc($opt{'format'});
1656 my $time = $opt{'time'} || time;
1658 my $tracctnum = ''; #leaking out from billco-specific sections :/
1659 if ( $format eq 'billco' ) {
1662 $self->conf->config('billco-account_num', $cust_main->agentnum);
1664 $tracctnum = $account_num eq 'display_custnum'
1665 ? $cust_main->display_custnum
1666 : $opt{'tracctnum'};
1669 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1671 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1673 my( $previous_balance, @unused ) = $self->previous; #previous balance
1675 my $pmt_cr_applied = 0;
1676 $pmt_cr_applied += $_->{'amount'}
1677 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1679 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1682 '', # 1 | N/A-Leave Empty CHAR 2
1683 '', # 2 | N/A-Leave Empty CHAR 15
1684 $tracctnum, # 3 | Transaction Account No CHAR 15
1685 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1686 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1687 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1688 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1689 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1690 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1691 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1692 '', # 10 | Ancillary Billing Information CHAR 30
1693 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1694 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1697 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1700 $duedate, # 14 | Bill Due Date CHAR 10
1702 $previous_balance, # 15 | Previous Balance NUM* 9
1703 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1704 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1705 $totaldue, # 18 | Total Amt Due NUM* 9
1706 $totaldue, # 19 | Total Amt Due NUM* 9
1707 '', # 20 | 30 Day Aging NUM* 9
1708 '', # 21 | 60 Day Aging NUM* 9
1709 '', # 22 | 90 Day Aging NUM* 9
1710 'N', # 23 | Y/N CHAR 1
1711 '', # 24 | Remittance automation CHAR 100
1712 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1713 $self->custnum, # 26 | Customer Reference Number CHAR 15
1714 '0', # 27 | Federal Tax*** NUM* 9
1715 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1716 '0', # 29 | Other Taxes & Fees*** NUM* 9
1719 } elsif ( $format eq 'oneline' ) { #name
1721 my ($previous_balance) = $self->previous;
1722 $previous_balance = sprintf('%.2f', $previous_balance);
1723 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1729 $self->_items_pkg, #_items_nontax? no sections or anything
1734 $cust_main->agentnum,
1735 $cust_main->agent->agent,
1739 $cust_main->company,
1740 $cust_main->address1,
1741 $cust_main->address2,
1747 time2str("%x", $self->_date),
1752 $self->due_date2str("%x"),
1757 } elsif ( $format eq 'bridgestone' ) {
1759 # bypass the CSV stuff and just return this
1760 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1761 my $zip = $cust_main->zip;
1763 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1767 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1769 $cust_main->display_custnum,
1771 uc(substr($cust_main->contact_firstlast,0,30)),
1772 uc(substr($cust_main->company ,0,30)),
1773 uc(substr($cust_main->address1 ,0,30)),
1774 uc(substr($cust_main->address2 ,0,30)),
1775 uc(substr($cust_main->city ,0,20)),
1776 uc($cust_main->state),
1782 } elsif ( $format eq 'ics' ) {
1784 my $bill = $cust_main->bill_location;
1785 my $zip = $bill->zip;
1789 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1794 # minor false laziness with print_generic
1795 my ($previous_balance) = $self->previous;
1796 my $balance_due = $self->owed + $previous_balance;
1797 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1798 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1801 if ( $self->due_date and $time >= $self->due_date ) {
1802 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1806 my $header = sprintf(
1807 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1808 $cust_main->display_custnum, #BID
1809 uc($cust_main->first), #FNAME
1810 uc($cust_main->last), #LNAME
1811 '00', #BATCH, should this ever be anything else?
1812 uc($cust_main->company), #COMP
1813 uc($bill->address1), #STREET1
1814 uc($bill->address2), #STREET2
1815 uc($bill->city), #CITY
1816 uc($bill->state), #STATE
1819 time2str('%Y%m%d', $self->_date), #BILL_DATE
1820 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1821 ( map {sprintf('%0.2f', $_)}
1822 $balance_due, #AMNT_DUE
1823 $previous_balance, #PREV_BAL
1824 $payment_total, #PYMT_RCVD
1825 $credit_total, #CREDITS
1826 $previous_balance, #BEG_BAL--is this correct?
1827 $self->charged, #NEW_CHRG
1830 $past_due, #PAST_MSG
1834 my %svc_class = ('' => ''); # maybe cache this more persistently?
1836 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1838 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1839 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1843 my @dates = ( $self->_date, undef );
1844 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1845 $dates[1] = $prev->sdate; #questionable
1848 # generate an 01 detail for each service
1849 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1850 foreach my $cust_svc ( @svcs ) {
1851 $show_pkgnum = ''; # hide it if we're showing svcnums
1853 my $svcpart = $cust_svc->svcpart;
1854 if (!exists($svc_class{$svcpart})) {
1855 my $classnum = $cust_svc->part_svc->classnum;
1856 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1858 $svc_class{$svcpart} = $part_svc_class ?
1859 $part_svc_class->classname :
1863 my @h_label = $cust_svc->label(@dates, 'I');
1864 push @details, sprintf('01%-9s%-20s%-47s',
1866 $svc_class{$svcpart},
1869 } #foreach $cust_svc
1872 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1873 if ($cust_bill_pkg->recur > 0) {
1874 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1875 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1877 push @details, sprintf('02%-6s%-60s%-10s',
1880 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1882 } #foreach $cust_bill_pkg
1884 # Tag this row so that we know whether this is one page (1), two pages
1885 # (2), # or "big" (B). The tag will be stripped off before uploading.
1886 if ( scalar(@details) < 12 ) {
1888 } elsif ( scalar(@details) < 58 ) {
1894 return join('', $header, @details, "\n");
1902 time2str("%x", $self->_date),
1903 sprintf("%.2f", $self->charged),
1904 ( map { $cust_main->getfield($_) }
1905 qw( first last company address1 address2 city state zip country ) ),
1907 ) or die "can't create csv";
1910 my $header = $csv->string. "\n";
1913 if ( lc($opt{'format'}) eq 'billco' ) {
1916 my %items_opt = ( format => 'template',
1917 escape_function => sub { shift } );
1918 # I don't know what characters billco actually tolerates in spool entries.
1919 # Text::CSV will take care of delimiters, though.
1921 my @items = ( $self->_items_pkg(%items_opt),
1922 $self->_items_fee(%items_opt) );
1923 foreach my $item (@items) {
1925 my $description = $item->{'description'};
1926 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1927 $description .= ': ' . $item->{ext_description}[0];
1931 '', # 1 | N/A-Leave Empty CHAR 2
1932 '', # 2 | N/A-Leave Empty CHAR 15
1933 $tracctnum, # 3 | Account Number CHAR 15
1934 $self->invnum, # 4 | Invoice Number CHAR 15
1935 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1936 $description, # 6 | Transaction Detail CHAR 100
1937 $item->{'amount'}, # 7 | Amount NUM* 9
1938 '', # 8 | Line Format Control** CHAR 2
1939 '', # 9 | Grouping Code CHAR 2
1940 '', # 10 | User Defined CHAR 15
1943 $detail .= $csv->string. "\n";
1947 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1953 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1955 my($pkg, $setup, $recur, $sdate, $edate);
1956 if ( $cust_bill_pkg->pkgnum ) {
1958 ($pkg, $setup, $recur, $sdate, $edate) = (
1959 $cust_bill_pkg->part_pkg->pkg,
1960 ( $cust_bill_pkg->setup != 0
1961 ? sprintf("%.2f", $cust_bill_pkg->setup )
1963 ( $cust_bill_pkg->recur != 0
1964 ? sprintf("%.2f", $cust_bill_pkg->recur )
1966 ( $cust_bill_pkg->sdate
1967 ? time2str("%x", $cust_bill_pkg->sdate)
1969 ($cust_bill_pkg->edate
1970 ? time2str("%x", $cust_bill_pkg->edate)
1974 } else { #pkgnum tax
1975 next unless $cust_bill_pkg->setup != 0;
1976 $pkg = $cust_bill_pkg->desc;
1977 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1978 ( $sdate, $edate ) = ( '', '' );
1984 ( map { '' } (1..11) ),
1985 ($pkg, $setup, $recur, $sdate, $edate)
1986 ) or die "can't create csv";
1988 $detail .= $csv->string. "\n";
1994 ( $header, $detail );
1999 croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
2004 Attempts to pay this invoice with a credit card payment via a
2005 Business::OnlinePayment realtime gateway. See
2006 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2007 for supported processors.
2013 $self->realtime_bop( 'CC', @_ );
2018 Attempts to pay this invoice with an electronic check (ACH) payment via a
2019 Business::OnlinePayment realtime gateway. See
2020 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2021 for supported processors.
2027 $self->realtime_bop( 'ECHECK', @_ );
2032 Attempts to pay this invoice with phone bill (LEC) payment via a
2033 Business::OnlinePayment realtime gateway. See
2034 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2035 for supported processors.
2041 $self->realtime_bop( 'LEC', @_ );
2045 my( $self, $method ) = (shift,shift);
2046 my $conf = $self->conf;
2049 my $cust_main = $self->cust_main;
2050 my $balance = $cust_main->balance;
2051 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2052 $amount = sprintf("%.2f", $amount);
2053 return "not run (balance $balance)" unless $amount > 0;
2055 my $description = 'Internet Services';
2056 if ( $conf->exists('business-onlinepayment-description') ) {
2057 my $dtempl = $conf->config('business-onlinepayment-description');
2059 my $agent_obj = $cust_main->agent
2060 or die "can't retreive agent for $cust_main (agentnum ".
2061 $cust_main->agentnum. ")";
2062 my $agent = $agent_obj->agent;
2063 my $pkgs = join(', ',
2064 map { $_->part_pkg->pkg }
2065 grep { $_->pkgnum } $self->cust_bill_pkg
2067 $description = eval qq("$dtempl");
2070 $cust_main->realtime_bop($method, $amount,
2071 'description' => $description,
2072 'invnum' => $self->invnum,
2073 #this didn't do what we want, it just calls apply_payments_and_credits
2075 'apply_to_invoice' => 1,
2078 #this changes application behavior: auto payments
2079 #triggered against a specific invoice are now applied
2080 #to that invoice instead of oldest open.
2086 =item batch_card OPTION => VALUE...
2088 Adds a payment for this invoice to the pending credit card batch (see
2089 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2090 runs the payment using a realtime gateway.
2095 my ($self, %options) = @_;
2096 my $cust_main = $self->cust_main;
2098 $options{invnum} = $self->invnum;
2100 $cust_main->batch_card(%options);
2103 sub _agent_template {
2105 $self->cust_main->agent_template;
2108 sub _agent_invoice_from {
2110 $self->cust_main->agent_invoice_from;
2113 =item invoice_barcode DIR_OR_FALSE
2115 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2116 it is taken as the temp directory where the PNG file will be generated and the
2117 PNG file name is returned. Otherwise, the PNG image itself is returned.
2121 sub invoice_barcode {
2122 my ($self, $dir) = (shift,shift);
2124 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2125 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2126 my $gd = $gdbar->plot(Height => 30);
2129 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2133 ) or die "can't open temp file: $!\n";
2134 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2135 my $png_file = $bh->filename;
2142 =item invnum_date_pretty
2144 Returns a string with the invoice number and date, for example:
2145 "Invoice #54 (3/20/2008)".
2147 Intended for back-end context, with regard to translation and date formatting.
2151 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2152 # for backend use (and also does the wrong thing, localizing for end customer
2153 # instead of backoffice configured date format)
2154 sub invnum_date_pretty {
2156 #$self->mt('Invoice #').
2157 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2158 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2161 #sub _items_extra_usage_sections {
2163 # my $escape = shift;
2165 # my %sections = ();
2167 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2168 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2170 # next unless $cust_bill_pkg->pkgnum > 0;
2172 # foreach my $section ( keys %usage_class ) {
2174 # my $usage = $cust_bill_pkg->usage($section);
2176 # next unless $usage && $usage > 0;
2178 # $sections{$section} ||= 0;
2179 # $sections{$section} += $usage;
2185 # map { { 'description' => &{$escape}($_),
2186 # 'subtotal' => $sections{$_},
2187 # 'summarized' => '',
2188 # 'tax_section' => '',
2191 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2195 sub _items_extra_usage_sections {
2197 my $conf = $self->conf;
2205 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2207 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2208 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2209 next unless $cust_bill_pkg->pkgnum > 0;
2211 foreach my $classnum ( keys %usage_class ) {
2212 my $section = $usage_class{$classnum}->classname;
2213 $classnums{$section} = $classnum;
2215 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2216 my $amount = $detail->amount;
2217 next unless $amount && $amount > 0;
2219 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2220 $sections{$section}{amount} += $amount; #subtotal
2221 $sections{$section}{calls}++;
2222 $sections{$section}{duration} += $detail->duration;
2224 my $desc = $detail->regionname;
2225 my $description = $desc;
2226 $description = substr($desc, 0, $maxlength). '...'
2227 if $format eq 'latex' && length($desc) > $maxlength;
2229 $lines{$section}{$desc} ||= {
2230 description => &{$escape}($description),
2231 #pkgpart => $part_pkg->pkgpart,
2232 pkgnum => $cust_bill_pkg->pkgnum,
2237 #unit_amount => $cust_bill_pkg->unitrecur,
2238 quantity => $cust_bill_pkg->quantity,
2239 product_code => 'N/A',
2240 ext_description => [],
2243 $lines{$section}{$desc}{amount} += $amount;
2244 $lines{$section}{$desc}{calls}++;
2245 $lines{$section}{$desc}{duration} += $detail->duration;
2251 my %sectionmap = ();
2252 foreach (keys %sections) {
2253 my $usage_class = $usage_class{$classnums{$_}};
2254 $sectionmap{$_} = { 'description' => &{$escape}($_),
2255 'amount' => $sections{$_}{amount}, #subtotal
2256 'calls' => $sections{$_}{calls},
2257 'duration' => $sections{$_}{duration},
2259 'tax_section' => '',
2260 'sort_weight' => $usage_class->weight,
2261 ( $usage_class->format
2262 ? ( map { $_ => $usage_class->$_($format) }
2263 qw( description_generator header_generator total_generator total_line_generator )
2270 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2274 foreach my $section ( keys %lines ) {
2275 foreach my $line ( keys %{$lines{$section}} ) {
2276 my $l = $lines{$section}{$line};
2277 $l->{section} = $sectionmap{$section};
2278 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2279 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2284 return(\@sections, \@lines);
2290 my $end = $self->_date;
2292 # start at date of previous invoice + 1 second or 0 if no previous invoice
2293 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2294 $start = 0 if !$start;
2297 my $cust_main = $self->cust_main;
2298 my @pkgs = $cust_main->all_pkgs;
2299 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2302 foreach my $pkg ( @pkgs ) {
2303 my @h_cust_svc = $pkg->h_cust_svc($end);
2304 foreach my $h_cust_svc ( @h_cust_svc ) {
2305 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2306 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2308 my $inserted = $h_cust_svc->date_inserted;
2309 my $deleted = $h_cust_svc->date_deleted;
2310 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2312 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2314 # DID either activated or ported in; cannot be both for same DID simultaneously
2315 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2316 && (!$phone_inserted->lnp_status
2317 || $phone_inserted->lnp_status eq ''
2318 || $phone_inserted->lnp_status eq 'native')) {
2321 else { # this one not so clean, should probably move to (h_)svc_phone
2322 local($FS::Record::qsearch_qualify_columns) = 0;
2323 my $phone_portedin = qsearchs( 'h_svc_phone',
2324 { 'svcnum' => $h_cust_svc->svcnum,
2325 'lnp_status' => 'portedin' },
2326 FS::h_svc_phone->sql_h_searchs($end),
2328 $num_portedin++ if $phone_portedin;
2331 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2332 if($deleted >= $start && $deleted <= $end && $phone_deleted
2333 && (!$phone_deleted->lnp_status
2334 || $phone_deleted->lnp_status ne 'portingout')) {
2337 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2338 && $phone_deleted->lnp_status
2339 && $phone_deleted->lnp_status eq 'portingout') {
2343 # increment usage minutes
2344 if ( $phone_inserted ) {
2345 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2346 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2349 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2352 # don't look at this service again
2353 push @seen, $h_cust_svc->svcnum;
2357 $minutes = sprintf("%d", $minutes);
2358 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2359 . "$num_deactivated Ported-Out: $num_portedout ",
2360 "Total Minutes: $minutes");
2363 sub _items_accountcode_cdr {
2368 my $section = { 'amount' => 0,
2371 'sort_weight' => '',
2373 'description' => 'Usage by Account Code',
2379 my %accountcodes = ();
2381 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2382 next unless $cust_bill_pkg->pkgnum > 0;
2384 my @header = $cust_bill_pkg->details_header;
2385 next unless scalar(@header);
2386 $section->{'header'} = join(',',@header);
2388 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2390 $section->{'header'} = $detail->formatted('format' => $format)
2391 if($detail->detail eq $section->{'header'});
2393 my $accountcode = $detail->accountcode;
2394 next unless $accountcode;
2396 my $amount = $detail->amount;
2397 next unless $amount && $amount > 0;
2399 $accountcodes{$accountcode} ||= {
2400 description => $accountcode,
2407 product_code => 'N/A',
2408 section => $section,
2409 ext_description => [ $section->{'header'} ],
2413 $section->{'amount'} += $amount;
2414 $accountcodes{$accountcode}{'amount'} += $amount;
2415 $accountcodes{$accountcode}{calls}++;
2416 $accountcodes{$accountcode}{duration} += $detail->duration;
2417 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2421 foreach my $l ( values %accountcodes ) {
2422 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2423 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2424 foreach my $sorted_detail ( @sorted_detail ) {
2425 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2427 delete $l->{detail_temp};
2431 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2433 return ($section,\@sorted_lines);
2436 sub _items_svc_phone_sections {
2438 my $conf = $self->conf;
2446 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2448 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2449 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2451 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2452 next unless $cust_bill_pkg->pkgnum > 0;
2454 my @header = $cust_bill_pkg->details_header;
2455 next unless scalar(@header);
2457 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2459 my $phonenum = $detail->phonenum;
2460 next unless $phonenum;
2462 my $amount = $detail->amount;
2463 next unless $amount && $amount > 0;
2465 $sections{$phonenum} ||= { 'amount' => 0,
2468 'sort_weight' => -1,
2469 'phonenum' => $phonenum,
2471 $sections{$phonenum}{amount} += $amount; #subtotal
2472 $sections{$phonenum}{calls}++;
2473 $sections{$phonenum}{duration} += $detail->duration;
2475 my $desc = $detail->regionname;
2476 my $description = $desc;
2477 $description = substr($desc, 0, $maxlength). '...'
2478 if $format eq 'latex' && length($desc) > $maxlength;
2480 $lines{$phonenum}{$desc} ||= {
2481 description => &{$escape}($description),
2482 #pkgpart => $part_pkg->pkgpart,
2490 product_code => 'N/A',
2491 ext_description => [],
2494 $lines{$phonenum}{$desc}{amount} += $amount;
2495 $lines{$phonenum}{$desc}{calls}++;
2496 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2498 my $line = $usage_class{$detail->classnum}->classname;
2499 $sections{"$phonenum $line"} ||=
2503 'sort_weight' => $usage_class{$detail->classnum}->weight,
2504 'phonenum' => $phonenum,
2505 'header' => [ @header ],
2507 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2508 $sections{"$phonenum $line"}{calls}++;
2509 $sections{"$phonenum $line"}{duration} += $detail->duration;
2511 $lines{"$phonenum $line"}{$desc} ||= {
2512 description => &{$escape}($description),
2513 #pkgpart => $part_pkg->pkgpart,
2521 product_code => 'N/A',
2522 ext_description => [],
2525 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2526 $lines{"$phonenum $line"}{$desc}{calls}++;
2527 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2528 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2529 $detail->formatted('format' => $format);
2534 my %sectionmap = ();
2535 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2536 foreach ( keys %sections ) {
2537 my @header = @{ $sections{$_}{header} || [] };
2539 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2540 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2541 my $usage_class = $summary ? $simple : $usage_simple;
2542 my $ending = $summary ? ' usage charges' : '';
2545 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2547 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2548 'amount' => $sections{$_}{amount}, #subtotal
2549 'calls' => $sections{$_}{calls},
2550 'duration' => $sections{$_}{duration},
2552 'tax_section' => '',
2553 'phonenum' => $sections{$_}{phonenum},
2554 'sort_weight' => $sections{$_}{sort_weight},
2555 'post_total' => $summary, #inspire pagebreak
2557 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2558 qw( description_generator
2561 total_line_generator
2568 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2569 $a->{sort_weight} <=> $b->{sort_weight}
2574 foreach my $section ( keys %lines ) {
2575 foreach my $line ( keys %{$lines{$section}} ) {
2576 my $l = $lines{$section}{$line};
2577 $l->{section} = $sectionmap{$section};
2578 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2579 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2584 if($conf->exists('phone_usage_class_summary')) {
2585 # this only works with Latex
2589 # after this, we'll have only two sections per DID:
2590 # Calls Summary and Calls Detail
2591 foreach my $section ( @sections ) {
2592 if($section->{'post_total'}) {
2593 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2594 $section->{'total_line_generator'} = sub { '' };
2595 $section->{'total_generator'} = sub { '' };
2596 $section->{'header_generator'} = sub { '' };
2597 $section->{'description_generator'} = '';
2598 push @newsections, $section;
2599 my %calls_detail = %$section;
2600 $calls_detail{'post_total'} = '';
2601 $calls_detail{'sort_weight'} = '';
2602 $calls_detail{'description_generator'} = sub { '' };
2603 $calls_detail{'header_generator'} = sub {
2604 return ' & Date/Time & Called Number & Duration & Price'
2605 if $format eq 'latex';
2608 $calls_detail{'description'} = 'Calls Detail: '
2609 . $section->{'phonenum'};
2610 push @newsections, \%calls_detail;
2614 # after this, each usage class is collapsed/summarized into a single
2615 # line under the Calls Summary section
2616 foreach my $newsection ( @newsections ) {
2617 if($newsection->{'post_total'}) { # this means Calls Summary
2618 foreach my $section ( @sections ) {
2619 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2620 && !$section->{'post_total'});
2621 my $newdesc = $section->{'description'};
2622 my $tn = $section->{'phonenum'};
2623 $newdesc =~ s/$tn//g;
2624 my $line = { ext_description => [],
2628 calls => $section->{'calls'},
2629 section => $newsection,
2630 duration => $section->{'duration'},
2631 description => $newdesc,
2632 amount => sprintf("%.2f",$section->{'amount'}),
2633 product_code => 'N/A',
2635 push @newlines, $line;
2640 # after this, Calls Details is populated with all CDRs
2641 foreach my $newsection ( @newsections ) {
2642 if(!$newsection->{'post_total'}) { # this means Calls Details
2643 foreach my $line ( @lines ) {
2644 next unless (scalar(@{$line->{'ext_description'}}) &&
2645 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2647 my @extdesc = @{$line->{'ext_description'}};
2649 foreach my $extdesc ( @extdesc ) {
2650 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2651 push @newextdesc, $extdesc;
2653 $line->{'ext_description'} = \@newextdesc;
2654 $line->{'section'} = $newsection;
2655 push @newlines, $line;
2660 return(\@newsections, \@newlines);
2663 return(\@sections, \@lines);
2667 =sub _items_usage_class_summary OPTIONS
2669 Returns a list of detail items summarizing the usage charges on this
2670 invoice. Each one will have 'amount', 'description' (the usage charge name),
2671 and 'usage_classnum'.
2673 OPTIONS can include 'escape' (a function to escape the descriptions).
2677 sub _items_usage_class_summary {
2681 my $escape = $opt{escape} || sub { $_[0] };
2682 my $money_char = $opt{money_char};
2683 my $invnum = $self->invnum;
2684 my @classes = qsearch({
2685 'table' => 'usage_class',
2686 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2687 ' COUNT(*) AS calls, SUM(duration) AS duration',
2688 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2689 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2690 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2691 ' GROUP BY classnum, classname, weight'.
2692 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2693 ' ORDER BY weight ASC',
2697 description => &{$escape}($self->mt('Usage Summary')),
2701 foreach my $class (@classes) {
2702 $section->{subtotal} += $class->get('amount');
2704 'description' => &{$escape}($class->classname),
2705 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2706 'quantity' => $class->get('calls'),
2707 'duration' => $class->get('duration'),
2708 'usage_classnum' => $class->classnum,
2709 'section' => $section,
2712 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2716 sub _items_previous {
2718 my $conf = $self->conf;
2719 my $cust_main = $self->cust_main;
2720 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2722 foreach ( @pr_cust_bill ) {
2723 my $date = $conf->exists('invoice_show_prior_due_date')
2724 ? 'due '. $_->due_date2str('short')
2725 : $self->time2str_local('short', $_->_date);
2727 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2728 #'pkgpart' => 'N/A',
2730 'amount' => sprintf("%.2f", $_->owed),
2736 # 'description' => 'Previous Balance',
2737 # #'pkgpart' => 'N/A',
2738 # 'pkgnum' => 'N/A',
2739 # 'amount' => sprintf("%10.2f", $pr_total ),
2740 # 'ext_description' => [ map {
2741 # "Invoice ". $_->invnum.
2742 # " (". time2str("%x",$_->_date). ") ".
2743 # sprintf("%10.2f", $_->owed)
2744 # } @pr_cust_bill ],
2749 sub _items_credits {
2750 my( $self, %opt ) = @_;
2751 my $trim_len = $opt{'trim_len'} || 40;
2756 if ( $self->conf->exists('previous_balance-payments_since') ) {
2757 if ( $opt{'template'} eq 'statement' ) {
2758 # then the current bill is a "statement" (i.e. an invoice sent as
2759 # a payment receipt)
2760 # and in that case we want to see payments on or after THIS invoice
2761 @objects = qsearch('cust_credit', {
2762 'custnum' => $self->custnum,
2763 '_date' => {op => '>=', value => $self->_date},
2767 $date = $self->previous_bill->_date if $self->previous_bill;
2768 @objects = qsearch('cust_credit', {
2769 'custnum' => $self->custnum,
2770 '_date' => {op => '>=', value => $date},
2774 @objects = $self->cust_credited;
2777 foreach my $obj ( @objects ) {
2778 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2780 my $reason = substr($cust_credit->reason, 0, $trim_len);
2781 $reason .= '...' if length($reason) < length($cust_credit->reason);
2782 $reason = " ($reason) " if $reason;
2785 #'description' => 'Credit ref\#'. $_->crednum.
2786 # " (". time2str("%x",$_->cust_credit->_date) .")".
2788 'description' => $self->mt('Credit applied').' '.
2789 $self->time2str_local('short', $obj->_date). $reason,
2790 'amount' => sprintf("%.2f",$obj->amount),
2798 sub _items_payments {
2803 my $detailed = $self->conf->exists('invoice_payment_details');
2805 if ( $self->conf->exists('previous_balance-payments_since') ) {
2806 # then show payments dated on/after the previous bill...
2807 if ( $opt{'template'} eq 'statement' ) {
2808 # then the current bill is a "statement" (i.e. an invoice sent as
2809 # a payment receipt)
2810 # and in that case we want to see payments on or after THIS invoice
2811 @objects = qsearch('cust_pay', {
2812 'custnum' => $self->custnum,
2813 '_date' => {op => '>=', value => $self->_date},
2816 # the normal case: payments on or after the previous invoice
2818 $date = $self->previous_bill->_date if $self->previous_bill;
2819 @objects = qsearch('cust_pay', {
2820 'custnum' => $self->custnum,
2821 '_date' => {op => '>=', value => $date},
2823 # and before the current bill...
2824 @objects = grep { $_->_date < $self->_date } @objects;
2827 @objects = $self->cust_bill_pay;
2830 foreach my $obj (@objects) {
2831 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2832 my $desc = $self->mt('Payment received').' '.
2833 $self->time2str_local('short', $cust_pay->_date );
2834 $desc .= $self->mt(' via ') .
2835 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2839 'description' => $desc,
2840 'amount' => sprintf("%.2f", $obj->amount )
2850 my $conf = $self->conf;
2853 my ($pr_total) = $self->previous;
2854 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2856 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2857 # if enabled, specifically add a line for the previous balance total
2858 $previous_charges_desc = $self->mt(
2859 $conf->config('previous_balance-text') || 'Previous Balance'
2862 # then return separate lines for previous balance and total new charges
2865 { total_item => $previous_charges_desc,
2866 total_amount => sprintf('%.2f',$pr_total)
2871 if ( $conf->exists('previous_balance-exclude_from_total')
2872 or !$self->enable_previous ) {
2873 # show new charges only
2875 $new_charges_desc = $self->mt(
2876 $conf->config('previous_balance-text-total_new_charges')
2877 || 'Total New Charges'
2880 $new_charges_amount = $self->charged;
2883 # show new charges + previous invoice total
2885 $new_charges_desc = $self->mt('Total Charges');
2886 if ( $self->enable_previous ) {
2887 $new_charges_amount = sprintf('%.2f', $self->charged + $pr_total);
2889 $new_charges_amount = sprintf('%.2f', $self->charged);
2894 if ( $conf->exists('invoice_show_prior_due_date') ) {
2895 # then the due date should be shown with Total New Charges,
2896 # and should NOT be shown with the Balance Due message.
2897 if ( $self->due_date ) {
2898 # localize the "Please pay by" message and the date itself
2899 # (grammar issues with this, yeah)
2900 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2901 $self->due_date2str('short');
2902 } elsif ( $self->terms ) {
2903 # phrases like "due on receipt" should be localized
2904 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2909 { total_item => $new_charges_desc,
2910 total_amount => $new_charges_amount,
2918 =item call_details [ OPTION => VALUE ... ]
2920 Returns an array of CSV strings representing the call details for this invoice
2921 The only option available is the boolean prepend_billed_number
2926 my ($self, %opt) = @_;
2928 my $format_function = sub { shift };
2930 if ($opt{prepend_billed_number}) {
2931 $format_function = sub {
2935 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2940 my @details = map { $_->details( 'format_function' => $format_function,
2941 'escape_function' => sub{ return() },
2945 $self->cust_bill_pkg;
2946 my $header = $details[0];
2947 ( $header, grep { $_ ne $header } @details );
2950 =item cust_pay_batch
2952 Returns all L<FS::cust_pay_batch> records linked to this invoice. Deprecated,
2957 sub cust_pay_batch {
2958 carp "FS::cust_bill->cust_pay_batch is deprecated";
2960 qsearch('cust_pay_batch', { 'invnum' => $self->invnum });
2969 =item process_reprint
2973 sub process_reprint {
2974 process_re_X('print', @_);
2977 =item process_reemail
2981 sub process_reemail {
2982 process_re_X('email', @_);
2990 process_re_X('fax', @_);
2998 process_re_X('ftp', @_);
3005 sub process_respool {
3006 process_re_X('spool', @_);
3011 my( $method, $job ) = ( shift, shift );
3012 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3015 warn Dumper($param) if $DEBUG;
3025 # this is called from search/cust_bill.html and given all its search
3026 # parameters, so it needs to perform the same search.
3029 # spool_invoice ftp_invoice fax_invoice print_invoice
3030 my($method, $job, %param ) = @_;
3032 warn "re_X $method for job $job with param:\n".
3033 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3036 #some false laziness w/search/cust_bill.html
3037 $param{'order_by'} = 'cust_bill._date';
3039 my $query = FS::cust_bill->search(\%param);
3040 delete $query->{'count_query'};
3041 delete $query->{'count_addl'};
3043 $query->{debug} = 1; # was in here before, is obviously useful
3045 my @cust_bill = qsearch( $query );
3047 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3049 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3052 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3053 foreach my $cust_bill ( @cust_bill ) {
3054 $cust_bill->$method();
3056 if ( $job ) { #progressbar foo
3058 if ( time - $min_sec > $last ) {
3059 my $error = $job->update_statustext(
3060 int( 100 * $num / scalar(@cust_bill) )
3062 die $error if $error;
3073 +{ ( map { $_=>$self->$_ } $self->fields ),
3074 'owed' => $self->owed,
3075 #XXX last payment applied date
3081 =head1 CLASS METHODS
3087 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3092 my ($class, $start, $end) = @_;
3094 $class->paid_sql($start, $end). ' - '.
3095 $class->credited_sql($start, $end);
3100 Returns an SQL fragment to retreive the net amount (charged minus credited).
3105 my ($class, $start, $end) = @_;
3106 'charged - '. $class->credited_sql($start, $end);
3111 Returns an SQL fragment to retreive the amount paid against this invoice.
3116 my ($class, $start, $end) = @_;
3117 $start &&= "AND cust_bill_pay._date <= $start";
3118 $end &&= "AND cust_bill_pay._date > $end";
3119 $start = '' unless defined($start);
3120 $end = '' unless defined($end);
3121 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3122 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3127 Returns an SQL fragment to retreive the amount credited against this invoice.
3132 my ($class, $start, $end) = @_;
3133 $start &&= "AND cust_credit_bill._date <= $start";
3134 $end &&= "AND cust_credit_bill._date > $end";
3135 $start = '' unless defined($start);
3136 $end = '' unless defined($end);
3137 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3138 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3143 Returns an SQL fragment to retrieve the due date of an invoice.
3144 Currently only supported on PostgreSQL.
3149 die "don't use: doesn't account for agent-specific invoice_default_terms";
3151 #we're passed a $conf but not a specific customer (that's in the query), so
3152 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3153 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3156 my $conf = new FS::Conf;
3160 cust_bill.invoice_terms,
3161 cust_main.invoice_terms,
3162 \''.($conf->config('invoice_default_terms') || '').'\'
3163 ), E\'Net (\\\\d+)\'
3165 ) * 86400 + cust_bill._date'
3176 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3177 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base