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");
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 call_details [ OPTION => VALUE ... ]
2915 Returns an array of CSV strings representing the call details for this invoice
2916 The only option available is the boolean prepend_billed_number
2921 my ($self, %opt) = @_;
2923 my $format_function = sub { shift };
2925 if ($opt{prepend_billed_number}) {
2926 $format_function = sub {
2930 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2935 my @details = map { $_->details( 'format_function' => $format_function,
2936 'escape_function' => sub{ return() },
2940 $self->cust_bill_pkg;
2941 my $header = $details[0];
2942 ( $header, grep { $_ ne $header } @details );
2945 =item cust_pay_batch
2947 Returns all L<FS::cust_pay_batch> records linked to this invoice. Deprecated,
2952 sub cust_pay_batch {
2953 carp "FS::cust_bill->cust_pay_batch is deprecated";
2955 qsearch('cust_pay_batch', { 'invnum' => $self->invnum });
2964 =item process_reprint
2968 sub process_reprint {
2969 process_re_X('print', @_);
2972 =item process_reemail
2976 sub process_reemail {
2977 process_re_X('email', @_);
2985 process_re_X('fax', @_);
2993 process_re_X('ftp', @_);
3000 sub process_respool {
3001 process_re_X('spool', @_);
3006 my( $method, $job ) = ( shift, shift );
3007 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3010 warn Dumper($param) if $DEBUG;
3020 # this is called from search/cust_bill.html and given all its search
3021 # parameters, so it needs to perform the same search.
3024 # spool_invoice ftp_invoice fax_invoice print_invoice
3025 my($method, $job, %param ) = @_;
3027 warn "re_X $method for job $job with param:\n".
3028 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3031 #some false laziness w/search/cust_bill.html
3032 $param{'order_by'} = 'cust_bill._date';
3034 my $query = FS::cust_bill->search(\%param);
3035 delete $query->{'count_query'};
3036 delete $query->{'count_addl'};
3038 $query->{debug} = 1; # was in here before, is obviously useful
3040 my @cust_bill = qsearch( $query );
3042 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3044 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3047 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3048 foreach my $cust_bill ( @cust_bill ) {
3049 $cust_bill->$method();
3051 if ( $job ) { #progressbar foo
3053 if ( time - $min_sec > $last ) {
3054 my $error = $job->update_statustext(
3055 int( 100 * $num / scalar(@cust_bill) )
3057 die $error if $error;
3068 +{ ( map { $_=>$self->$_ } $self->fields ),
3069 'owed' => $self->owed,
3070 #XXX last payment applied date
3076 =head1 CLASS METHODS
3082 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3087 my ($class, $start, $end) = @_;
3089 $class->paid_sql($start, $end). ' - '.
3090 $class->credited_sql($start, $end);
3095 Returns an SQL fragment to retreive the net amount (charged minus credited).
3100 my ($class, $start, $end) = @_;
3101 'charged - '. $class->credited_sql($start, $end);
3106 Returns an SQL fragment to retreive the amount paid against this invoice.
3111 my ($class, $start, $end) = @_;
3112 $start &&= "AND cust_bill_pay._date <= $start";
3113 $end &&= "AND cust_bill_pay._date > $end";
3114 $start = '' unless defined($start);
3115 $end = '' unless defined($end);
3116 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3117 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3122 Returns an SQL fragment to retreive the amount credited against this invoice.
3127 my ($class, $start, $end) = @_;
3128 $start &&= "AND cust_credit_bill._date <= $start";
3129 $end &&= "AND cust_credit_bill._date > $end";
3130 $start = '' unless defined($start);
3131 $end = '' unless defined($end);
3132 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3133 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3138 Returns an SQL fragment to retrieve the due date of an invoice.
3139 Currently only supported on PostgreSQL.
3144 die "don't use: doesn't account for agent-specific invoice_default_terms";
3146 #we're passed a $conf but not a specific customer (that's in the query), so
3147 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3148 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3151 my $conf = new FS::Conf;
3155 cust_bill.invoice_terms,
3156 cust_main.invoice_terms,
3157 \''.($conf->config('invoice_default_terms') || '').'\'
3158 ), E\'Net (\\\\d+)\'
3160 ) * 86400 + cust_bill._date'
3171 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3172 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base