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};
1119 $self->set('mode', $opt{mode});
1122 my %args = map {$_ => $opt{$_}}
1124 qw( from notice_name no_coupon template );
1126 my $error = $self->email( \%args );
1127 die $error if $error;
1133 my $conf = $self->conf;
1135 #my $template = scalar(@_) ? shift : '';
1138 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1141 my $cust_main = $self->cust_main;
1142 my $name = $cust_main->name;
1143 my $name_short = $cust_main->name_short;
1144 my $invoice_number = $self->invnum;
1145 my $invoice_date = $self->_date_pretty;
1147 eval qq("$subject");
1150 =item lpr_data HASHREF
1152 Returns the postscript or plaintext for this invoice as an arrayref.
1154 Options must be passed as a hashref. Positional parameters are no longer
1157 I<template>, if specified, is the name of a suffix for alternate invoices.
1159 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1165 my $conf = $self->conf;
1166 my $opt = shift || {};
1167 if ($opt and !ref($opt)) {
1168 # nobody does this anyway
1169 die "FS::cust_bill::lpr_data called with positional parameters";
1172 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1173 [ $self->$method( $opt ) ];
1178 Prints this invoice.
1180 Options must be passed as a hashref.
1182 I<template>, if specified, is the name of a suffix for alternate invoices.
1184 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1190 return if $self->hide;
1191 my $conf = $self->conf;
1192 my $opt = shift || {};
1193 if ($opt and !ref($opt)) {
1194 die "FS::cust_bill::print called with positional parameters";
1197 my $lpr = delete $opt->{lpr};
1198 if($conf->exists('invoice_print_pdf')) {
1199 # Add the invoice to the current batch.
1200 $self->batch_invoice($opt);
1204 $self->lpr_data($opt),
1205 'agentnum' => $self->cust_main->agentnum,
1211 =item fax_invoice HASHREF
1215 Options must be passed as a hashref.
1217 I<template>, if specified, is the name of a suffix for alternate invoices.
1219 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1225 return if $self->hide;
1226 my $conf = $self->conf;
1227 my $opt = shift || {};
1228 if ($opt and !ref($opt)) {
1229 die "FS::cust_bill::fax_invoice called with positional parameters";
1232 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1233 unless $conf->exists('invoice_latex');
1235 my $dialstring = $self->cust_main->getfield('fax');
1238 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1239 'dialstring' => $dialstring,
1241 die $error if $error;
1245 =item batch_invoice [ HASHREF ]
1247 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1248 isn't an open batch, one will be created.
1250 HASHREF may contain any options to be passed to C<print_pdf>.
1255 my ($self, $opt) = @_;
1256 my $bill_batch = $self->get_open_bill_batch;
1257 my $cust_bill_batch = FS::cust_bill_batch->new({
1258 batchnum => $bill_batch->batchnum,
1259 invnum => $self->invnum,
1261 return $cust_bill_batch->insert($opt);
1264 =item get_open_batch
1266 Returns the currently open batch as an FS::bill_batch object, creating a new
1267 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1272 sub get_open_bill_batch {
1274 my $conf = $self->conf;
1275 my $hashref = { status => 'O' };
1276 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1277 ? $self->cust_main->agentnum
1279 my $batch = qsearchs('bill_batch', $hashref);
1280 return $batch if $batch;
1281 $batch = FS::bill_batch->new($hashref);
1282 my $error = $batch->insert;
1283 die $error if $error;
1287 =item ftp_invoice [ TEMPLATENAME ]
1289 Sends this invoice data via FTP.
1291 TEMPLATENAME is unused?
1297 my $conf = $self->conf;
1298 my $template = scalar(@_) ? shift : '';
1301 'protocol' => 'ftp',
1302 'server' => $conf->config('cust_bill-ftpserver'),
1303 'username' => $conf->config('cust_bill-ftpusername'),
1304 'password' => $conf->config('cust_bill-ftppassword'),
1305 'dir' => $conf->config('cust_bill-ftpdir'),
1306 'format' => $conf->config('cust_bill-ftpformat'),
1310 =item spool_invoice [ TEMPLATENAME ]
1312 Spools this invoice data (see L<FS::spool_csv>)
1314 TEMPLATENAME is unused?
1320 my $conf = $self->conf;
1321 my $template = scalar(@_) ? shift : '';
1324 'format' => $conf->config('cust_bill-spoolformat'),
1325 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1329 =item send_csv OPTION => VALUE, ...
1331 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1335 protocol - currently only "ftp"
1341 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1342 and YYMMDDHHMMSS is a timestamp.
1344 See L</print_csv> for a description of the output format.
1349 my($self, %opt) = @_;
1353 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1354 mkdir $spooldir, 0700 unless -d $spooldir;
1356 # don't localize dates here, they're a defined format
1357 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1358 my $file = "$spooldir/$tracctnum.csv";
1360 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1362 open(CSV, ">$file") or die "can't open $file: $!";
1370 if ( $opt{protocol} eq 'ftp' ) {
1371 eval "use Net::FTP;";
1373 $net = Net::FTP->new($opt{server}) or die @$;
1375 die "unknown protocol: $opt{protocol}";
1378 $net->login( $opt{username}, $opt{password} )
1379 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1381 $net->binary or die "can't set binary mode";
1383 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1385 $net->put($file) or die "can't put $file: $!";
1395 Spools CSV invoice data.
1401 =item format - any of FS::Misc::::Invoicing::spool_formats
1403 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1404 customer has the corresponding invoice destinations set (see
1405 L<FS::cust_main_invoice>).
1407 =item agent_spools - if set to a true value, will spool to per-agent files
1408 rather than a single global file
1410 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1411 append to that spool. L<FS::Cron::upload> will then send the spool file to
1414 =item balanceover - if set, only spools the invoice if the total amount owed on
1415 this invoice and all older invoices is greater than the specified amount.
1417 =item time - the "current time". Controls the printing of past due messages
1425 my($self, %opt) = @_;
1427 my $time = $opt{'time'} || time;
1428 my $cust_main = $self->cust_main;
1430 if ( $opt{'dest'} ) {
1431 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1432 $cust_main->invoicing_list;
1433 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1434 || ! keys %invoicing_list;
1437 if ( $opt{'balanceover'} ) {
1439 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1442 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1443 mkdir $spooldir, 0700 unless -d $spooldir;
1445 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1448 if ( $opt{'agent_spools'} ) {
1449 $file = 'agentnum'.$cust_main->agentnum;
1454 if ( $opt{'upload_targetnum'} ) {
1455 $spooldir .= '/target'.$opt{'upload_targetnum'};
1456 mkdir $spooldir, 0700 unless -d $spooldir;
1457 } # otherwise it just goes into export.xxx/cust_bill
1459 if ( lc($opt{'format'}) eq 'billco' ) {
1463 $file = "$spooldir/$file.csv";
1465 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1467 open(CSV, ">>$file") or die "can't open $file: $!";
1468 flock(CSV, LOCK_EX);
1473 if ( lc($opt{'format'}) eq 'billco' ) {
1475 flock(CSV, LOCK_UN);
1478 $file =~ s/-header.csv$/-detail.csv/;
1480 open(CSV,">>$file") or die "can't open $file: $!";
1481 flock(CSV, LOCK_EX);
1485 print CSV $detail if defined($detail);
1487 flock(CSV, LOCK_UN);
1494 =item print_csv OPTION => VALUE, ...
1496 Returns CSV data for this invoice.
1500 format - 'default', 'billco', 'oneline', 'bridgestone'
1502 Returns a list consisting of two scalars. The first is a single line of CSV
1503 header information for this invoice. The second is one or more lines of CSV
1504 detail information for this invoice.
1506 If I<format> is not specified or "default", the fields of the CSV file are as
1509 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1510 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1514 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1516 B<record_type> is C<cust_bill> for the initial header line only. The
1517 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1518 fields are filled in.
1520 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1521 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1524 =item invnum - invoice number
1526 =item custnum - customer number
1528 =item _date - invoice date
1530 =item charged - total invoice amount
1532 =item first - customer first name
1534 =item last - customer first name
1536 =item company - company name
1538 =item address1 - address line 1
1540 =item address2 - address line 1
1550 =item pkg - line item description
1552 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1554 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1556 =item sdate - start date for recurring fee
1558 =item edate - end date for recurring fee
1562 If I<format> is "billco", the fields of the header CSV file are as follows:
1564 +-------------------------------------------------------------------+
1565 | FORMAT HEADER FILE |
1566 |-------------------------------------------------------------------|
1567 | Field | Description | Name | Type | Width |
1568 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1569 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1570 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1571 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1572 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1573 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1574 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1575 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1576 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1577 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1578 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1579 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1580 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1581 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1582 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1583 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1584 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1585 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1586 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1587 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1588 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1589 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1590 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1591 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1592 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1593 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1594 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1595 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1596 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1597 +-------+-------------------------------+------------+------+-------+
1599 If I<format> is "billco", the fields of the detail CSV file are as follows:
1601 FORMAT FOR DETAIL FILE
1603 Field | Description | Name | Type | Width
1604 1 | N/A-Leave Empty | RC | CHAR | 2
1605 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1606 3 | Account Number | TRACCTNUM | CHAR | 15
1607 4 | Invoice Number | TRINVOICE | CHAR | 15
1608 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1609 6 | Transaction Detail | DETAILS | CHAR | 100
1610 7 | Amount | AMT | NUM* | 9
1611 8 | Line Format Control** | LNCTRL | CHAR | 2
1612 9 | Grouping Code | GROUP | CHAR | 2
1613 10 | User Defined | ACCT CODE | CHAR | 15
1615 If format is 'oneline', there is no detail file. Each invoice has a
1616 header line only, with the fields:
1618 Agent number, agent name, customer number, first name, last name, address
1619 line 1, address line 2, city, state, zip, invoice date, invoice number,
1620 amount charged, amount due, previous balance, due date.
1622 and then, for each line item, three columns containing the package number,
1623 description, and amount.
1625 If format is 'bridgestone', there is no detail file. Each invoice has a
1626 header line with the following fields in a fixed-width format:
1628 Customer number (in display format), date, name (first last), company,
1629 address 1, address 2, city, state, zip.
1631 This is a mailing list format, and has no per-invoice fields. To avoid
1632 sending redundant notices, the spooling event should have a "once" or
1633 "once_percust_every" condition.
1638 my($self, %opt) = @_;
1640 eval "use Text::CSV_XS";
1643 my $cust_main = $self->cust_main;
1645 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1646 my $format = lc($opt{'format'});
1648 my $time = $opt{'time'} || time;
1650 my $tracctnum = ''; #leaking out from billco-specific sections :/
1651 if ( $format eq 'billco' ) {
1654 $self->conf->config('billco-account_num', $cust_main->agentnum);
1656 $tracctnum = $account_num eq 'display_custnum'
1657 ? $cust_main->display_custnum
1658 : $opt{'tracctnum'};
1661 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1663 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1665 my( $previous_balance, @unused ) = $self->previous; #previous balance
1667 my $pmt_cr_applied = 0;
1668 $pmt_cr_applied += $_->{'amount'}
1669 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1671 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1674 '', # 1 | N/A-Leave Empty CHAR 2
1675 '', # 2 | N/A-Leave Empty CHAR 15
1676 $tracctnum, # 3 | Transaction Account No CHAR 15
1677 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1678 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1679 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1680 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1681 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1682 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1683 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1684 '', # 10 | Ancillary Billing Information CHAR 30
1685 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1686 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1689 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1692 $duedate, # 14 | Bill Due Date CHAR 10
1694 $previous_balance, # 15 | Previous Balance NUM* 9
1695 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1696 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1697 $totaldue, # 18 | Total Amt Due NUM* 9
1698 $totaldue, # 19 | Total Amt Due NUM* 9
1699 '', # 20 | 30 Day Aging NUM* 9
1700 '', # 21 | 60 Day Aging NUM* 9
1701 '', # 22 | 90 Day Aging NUM* 9
1702 'N', # 23 | Y/N CHAR 1
1703 '', # 24 | Remittance automation CHAR 100
1704 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1705 $self->custnum, # 26 | Customer Reference Number CHAR 15
1706 '0', # 27 | Federal Tax*** NUM* 9
1707 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1708 '0', # 29 | Other Taxes & Fees*** NUM* 9
1711 } elsif ( $format eq 'oneline' ) { #name
1713 my ($previous_balance) = $self->previous;
1714 $previous_balance = sprintf('%.2f', $previous_balance);
1715 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1721 $self->_items_pkg, #_items_nontax? no sections or anything
1726 $cust_main->agentnum,
1727 $cust_main->agent->agent,
1731 $cust_main->company,
1732 $cust_main->address1,
1733 $cust_main->address2,
1739 time2str("%x", $self->_date),
1744 $self->due_date2str("%x"),
1749 } elsif ( $format eq 'bridgestone' ) {
1751 # bypass the CSV stuff and just return this
1752 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1753 my $zip = $cust_main->zip;
1755 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1759 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1761 $cust_main->display_custnum,
1763 uc(substr($cust_main->contact_firstlast,0,30)),
1764 uc(substr($cust_main->company ,0,30)),
1765 uc(substr($cust_main->address1 ,0,30)),
1766 uc(substr($cust_main->address2 ,0,30)),
1767 uc(substr($cust_main->city ,0,20)),
1768 uc($cust_main->state),
1774 } elsif ( $format eq 'ics' ) {
1776 my $bill = $cust_main->bill_location;
1777 my $zip = $bill->zip;
1781 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1786 # minor false laziness with print_generic
1787 my ($previous_balance) = $self->previous;
1788 my $balance_due = $self->owed + $previous_balance;
1789 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1790 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1793 if ( $self->due_date and $time >= $self->due_date ) {
1794 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1798 my $header = sprintf(
1799 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1800 $cust_main->display_custnum, #BID
1801 uc($cust_main->first), #FNAME
1802 uc($cust_main->last), #LNAME
1803 '00', #BATCH, should this ever be anything else?
1804 uc($cust_main->company), #COMP
1805 uc($bill->address1), #STREET1
1806 uc($bill->address2), #STREET2
1807 uc($bill->city), #CITY
1808 uc($bill->state), #STATE
1811 time2str('%Y%m%d', $self->_date), #BILL_DATE
1812 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1813 ( map {sprintf('%0.2f', $_)}
1814 $balance_due, #AMNT_DUE
1815 $previous_balance, #PREV_BAL
1816 $payment_total, #PYMT_RCVD
1817 $credit_total, #CREDITS
1818 $previous_balance, #BEG_BAL--is this correct?
1819 $self->charged, #NEW_CHRG
1822 $past_due, #PAST_MSG
1826 my %svc_class = ('' => ''); # maybe cache this more persistently?
1828 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1830 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1831 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1835 my @dates = ( $self->_date, undef );
1836 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1837 $dates[1] = $prev->sdate; #questionable
1840 # generate an 01 detail for each service
1841 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1842 foreach my $cust_svc ( @svcs ) {
1843 $show_pkgnum = ''; # hide it if we're showing svcnums
1845 my $svcpart = $cust_svc->svcpart;
1846 if (!exists($svc_class{$svcpart})) {
1847 my $classnum = $cust_svc->part_svc->classnum;
1848 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1850 $svc_class{$svcpart} = $part_svc_class ?
1851 $part_svc_class->classname :
1855 my @h_label = $cust_svc->label(@dates, 'I');
1856 push @details, sprintf('01%-9s%-20s%-47s',
1858 $svc_class{$svcpart},
1861 } #foreach $cust_svc
1864 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1865 if ($cust_bill_pkg->recur > 0) {
1866 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1867 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1869 push @details, sprintf('02%-6s%-60s%-10s',
1872 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1874 } #foreach $cust_bill_pkg
1876 # Tag this row so that we know whether this is one page (1), two pages
1877 # (2), # or "big" (B). The tag will be stripped off before uploading.
1878 if ( scalar(@details) < 12 ) {
1880 } elsif ( scalar(@details) < 58 ) {
1886 return join('', $header, @details, "\n");
1894 time2str("%x", $self->_date),
1895 sprintf("%.2f", $self->charged),
1896 ( map { $cust_main->getfield($_) }
1897 qw( first last company address1 address2 city state zip country ) ),
1899 ) or die "can't create csv";
1902 my $header = $csv->string. "\n";
1905 if ( lc($opt{'format'}) eq 'billco' ) {
1908 my %items_opt = ( format => 'template',
1909 escape_function => sub { shift } );
1910 # I don't know what characters billco actually tolerates in spool entries.
1911 # Text::CSV will take care of delimiters, though.
1913 my @items = ( $self->_items_pkg(%items_opt),
1914 $self->_items_fee(%items_opt) );
1915 foreach my $item (@items) {
1917 my $description = $item->{'description'};
1918 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1919 $description .= ': ' . $item->{ext_description}[0];
1923 '', # 1 | N/A-Leave Empty CHAR 2
1924 '', # 2 | N/A-Leave Empty CHAR 15
1925 $tracctnum, # 3 | Account Number CHAR 15
1926 $self->invnum, # 4 | Invoice Number CHAR 15
1927 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1928 $description, # 6 | Transaction Detail CHAR 100
1929 $item->{'amount'}, # 7 | Amount NUM* 9
1930 '', # 8 | Line Format Control** CHAR 2
1931 '', # 9 | Grouping Code CHAR 2
1932 '', # 10 | User Defined CHAR 15
1935 $detail .= $csv->string. "\n";
1939 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1945 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1947 my($pkg, $setup, $recur, $sdate, $edate);
1948 if ( $cust_bill_pkg->pkgnum ) {
1950 ($pkg, $setup, $recur, $sdate, $edate) = (
1951 $cust_bill_pkg->part_pkg->pkg,
1952 ( $cust_bill_pkg->setup != 0
1953 ? sprintf("%.2f", $cust_bill_pkg->setup )
1955 ( $cust_bill_pkg->recur != 0
1956 ? sprintf("%.2f", $cust_bill_pkg->recur )
1958 ( $cust_bill_pkg->sdate
1959 ? time2str("%x", $cust_bill_pkg->sdate)
1961 ($cust_bill_pkg->edate
1962 ? time2str("%x", $cust_bill_pkg->edate)
1966 } else { #pkgnum tax
1967 next unless $cust_bill_pkg->setup != 0;
1968 $pkg = $cust_bill_pkg->desc;
1969 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1970 ( $sdate, $edate ) = ( '', '' );
1976 ( map { '' } (1..11) ),
1977 ($pkg, $setup, $recur, $sdate, $edate)
1978 ) or die "can't create csv";
1980 $detail .= $csv->string. "\n";
1986 ( $header, $detail );
1991 croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
1996 Attempts to pay this invoice with a credit card payment via a
1997 Business::OnlinePayment realtime gateway. See
1998 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1999 for supported processors.
2005 $self->realtime_bop( 'CC', @_ );
2010 Attempts to pay this invoice with an electronic check (ACH) payment via a
2011 Business::OnlinePayment realtime gateway. See
2012 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2013 for supported processors.
2019 $self->realtime_bop( 'ECHECK', @_ );
2024 Attempts to pay this invoice with phone bill (LEC) payment via a
2025 Business::OnlinePayment realtime gateway. See
2026 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2027 for supported processors.
2033 $self->realtime_bop( 'LEC', @_ );
2037 my( $self, $method ) = (shift,shift);
2038 my $conf = $self->conf;
2041 my $cust_main = $self->cust_main;
2042 my $balance = $cust_main->balance;
2043 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2044 $amount = sprintf("%.2f", $amount);
2045 return "not run (balance $balance)" unless $amount > 0;
2047 my $description = 'Internet Services';
2048 if ( $conf->exists('business-onlinepayment-description') ) {
2049 my $dtempl = $conf->config('business-onlinepayment-description');
2051 my $agent_obj = $cust_main->agent
2052 or die "can't retreive agent for $cust_main (agentnum ".
2053 $cust_main->agentnum. ")";
2054 my $agent = $agent_obj->agent;
2055 my $pkgs = join(', ',
2056 map { $_->part_pkg->pkg }
2057 grep { $_->pkgnum } $self->cust_bill_pkg
2059 $description = eval qq("$dtempl");
2062 $cust_main->realtime_bop($method, $amount,
2063 'description' => $description,
2064 'invnum' => $self->invnum,
2065 #this didn't do what we want, it just calls apply_payments_and_credits
2067 'apply_to_invoice' => 1,
2070 #this changes application behavior: auto payments
2071 #triggered against a specific invoice are now applied
2072 #to that invoice instead of oldest open.
2078 =item batch_card OPTION => VALUE...
2080 Adds a payment for this invoice to the pending credit card batch (see
2081 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2082 runs the payment using a realtime gateway.
2087 my ($self, %options) = @_;
2088 my $cust_main = $self->cust_main;
2090 $options{invnum} = $self->invnum;
2092 $cust_main->batch_card(%options);
2095 sub _agent_template {
2097 $self->cust_main->agent_template;
2100 sub _agent_invoice_from {
2102 $self->cust_main->agent_invoice_from;
2105 =item invoice_barcode DIR_OR_FALSE
2107 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2108 it is taken as the temp directory where the PNG file will be generated and the
2109 PNG file name is returned. Otherwise, the PNG image itself is returned.
2113 sub invoice_barcode {
2114 my ($self, $dir) = (shift,shift);
2116 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2117 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2118 my $gd = $gdbar->plot(Height => 30);
2121 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2125 ) or die "can't open temp file: $!\n";
2126 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2127 my $png_file = $bh->filename;
2134 =item invnum_date_pretty
2136 Returns a string with the invoice number and date, for example:
2137 "Invoice #54 (3/20/2008)".
2139 Intended for back-end context, with regard to translation and date formatting.
2143 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2144 # for backend use (and also does the wrong thing, localizing for end customer
2145 # instead of backoffice configured date format)
2146 sub invnum_date_pretty {
2148 #$self->mt('Invoice #').
2149 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2150 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2153 #sub _items_extra_usage_sections {
2155 # my $escape = shift;
2157 # my %sections = ();
2159 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2160 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2162 # next unless $cust_bill_pkg->pkgnum > 0;
2164 # foreach my $section ( keys %usage_class ) {
2166 # my $usage = $cust_bill_pkg->usage($section);
2168 # next unless $usage && $usage > 0;
2170 # $sections{$section} ||= 0;
2171 # $sections{$section} += $usage;
2177 # map { { 'description' => &{$escape}($_),
2178 # 'subtotal' => $sections{$_},
2179 # 'summarized' => '',
2180 # 'tax_section' => '',
2183 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2187 sub _items_extra_usage_sections {
2189 my $conf = $self->conf;
2197 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2199 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2200 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2201 next unless $cust_bill_pkg->pkgnum > 0;
2203 foreach my $classnum ( keys %usage_class ) {
2204 my $section = $usage_class{$classnum}->classname;
2205 $classnums{$section} = $classnum;
2207 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2208 my $amount = $detail->amount;
2209 next unless $amount && $amount > 0;
2211 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2212 $sections{$section}{amount} += $amount; #subtotal
2213 $sections{$section}{calls}++;
2214 $sections{$section}{duration} += $detail->duration;
2216 my $desc = $detail->regionname;
2217 my $description = $desc;
2218 $description = substr($desc, 0, $maxlength). '...'
2219 if $format eq 'latex' && length($desc) > $maxlength;
2221 $lines{$section}{$desc} ||= {
2222 description => &{$escape}($description),
2223 #pkgpart => $part_pkg->pkgpart,
2224 pkgnum => $cust_bill_pkg->pkgnum,
2229 #unit_amount => $cust_bill_pkg->unitrecur,
2230 quantity => $cust_bill_pkg->quantity,
2231 product_code => 'N/A',
2232 ext_description => [],
2235 $lines{$section}{$desc}{amount} += $amount;
2236 $lines{$section}{$desc}{calls}++;
2237 $lines{$section}{$desc}{duration} += $detail->duration;
2243 my %sectionmap = ();
2244 foreach (keys %sections) {
2245 my $usage_class = $usage_class{$classnums{$_}};
2246 $sectionmap{$_} = { 'description' => &{$escape}($_),
2247 'amount' => $sections{$_}{amount}, #subtotal
2248 'calls' => $sections{$_}{calls},
2249 'duration' => $sections{$_}{duration},
2251 'tax_section' => '',
2252 'sort_weight' => $usage_class->weight,
2253 ( $usage_class->format
2254 ? ( map { $_ => $usage_class->$_($format) }
2255 qw( description_generator header_generator total_generator total_line_generator )
2262 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2266 foreach my $section ( keys %lines ) {
2267 foreach my $line ( keys %{$lines{$section}} ) {
2268 my $l = $lines{$section}{$line};
2269 $l->{section} = $sectionmap{$section};
2270 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2271 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2276 return(\@sections, \@lines);
2282 my $end = $self->_date;
2284 # start at date of previous invoice + 1 second or 0 if no previous invoice
2285 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2286 $start = 0 if !$start;
2289 my $cust_main = $self->cust_main;
2290 my @pkgs = $cust_main->all_pkgs;
2291 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2294 foreach my $pkg ( @pkgs ) {
2295 my @h_cust_svc = $pkg->h_cust_svc($end);
2296 foreach my $h_cust_svc ( @h_cust_svc ) {
2297 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2298 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2300 my $inserted = $h_cust_svc->date_inserted;
2301 my $deleted = $h_cust_svc->date_deleted;
2302 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2304 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2306 # DID either activated or ported in; cannot be both for same DID simultaneously
2307 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2308 && (!$phone_inserted->lnp_status
2309 || $phone_inserted->lnp_status eq ''
2310 || $phone_inserted->lnp_status eq 'native')) {
2313 else { # this one not so clean, should probably move to (h_)svc_phone
2314 local($FS::Record::qsearch_qualify_columns) = 0;
2315 my $phone_portedin = qsearchs( 'h_svc_phone',
2316 { 'svcnum' => $h_cust_svc->svcnum,
2317 'lnp_status' => 'portedin' },
2318 FS::h_svc_phone->sql_h_searchs($end),
2320 $num_portedin++ if $phone_portedin;
2323 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2324 if($deleted >= $start && $deleted <= $end && $phone_deleted
2325 && (!$phone_deleted->lnp_status
2326 || $phone_deleted->lnp_status ne 'portingout')) {
2329 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2330 && $phone_deleted->lnp_status
2331 && $phone_deleted->lnp_status eq 'portingout') {
2335 # increment usage minutes
2336 if ( $phone_inserted ) {
2337 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2338 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2341 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2344 # don't look at this service again
2345 push @seen, $h_cust_svc->svcnum;
2349 $minutes = sprintf("%d", $minutes);
2350 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2351 . "$num_deactivated Ported-Out: $num_portedout ",
2352 "Total Minutes: $minutes");
2355 sub _items_accountcode_cdr {
2360 my $section = { 'amount' => 0,
2363 'sort_weight' => '',
2365 'description' => 'Usage by Account Code',
2371 my %accountcodes = ();
2373 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2374 next unless $cust_bill_pkg->pkgnum > 0;
2376 my @header = $cust_bill_pkg->details_header;
2377 next unless scalar(@header);
2378 $section->{'header'} = join(',',@header);
2380 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2382 $section->{'header'} = $detail->formatted('format' => $format)
2383 if($detail->detail eq $section->{'header'});
2385 my $accountcode = $detail->accountcode;
2386 next unless $accountcode;
2388 my $amount = $detail->amount;
2389 next unless $amount && $amount > 0;
2391 $accountcodes{$accountcode} ||= {
2392 description => $accountcode,
2399 product_code => 'N/A',
2400 section => $section,
2401 ext_description => [ $section->{'header'} ],
2405 $section->{'amount'} += $amount;
2406 $accountcodes{$accountcode}{'amount'} += $amount;
2407 $accountcodes{$accountcode}{calls}++;
2408 $accountcodes{$accountcode}{duration} += $detail->duration;
2409 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2413 foreach my $l ( values %accountcodes ) {
2414 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2415 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2416 foreach my $sorted_detail ( @sorted_detail ) {
2417 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2419 delete $l->{detail_temp};
2423 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2425 return ($section,\@sorted_lines);
2428 sub _items_svc_phone_sections {
2430 my $conf = $self->conf;
2438 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2440 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2441 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2443 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2444 next unless $cust_bill_pkg->pkgnum > 0;
2446 my @header = $cust_bill_pkg->details_header;
2447 next unless scalar(@header);
2449 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2451 my $phonenum = $detail->phonenum;
2452 next unless $phonenum;
2454 my $amount = $detail->amount;
2455 next unless $amount && $amount > 0;
2457 $sections{$phonenum} ||= { 'amount' => 0,
2460 'sort_weight' => -1,
2461 'phonenum' => $phonenum,
2463 $sections{$phonenum}{amount} += $amount; #subtotal
2464 $sections{$phonenum}{calls}++;
2465 $sections{$phonenum}{duration} += $detail->duration;
2467 my $desc = $detail->regionname;
2468 my $description = $desc;
2469 $description = substr($desc, 0, $maxlength). '...'
2470 if $format eq 'latex' && length($desc) > $maxlength;
2472 $lines{$phonenum}{$desc} ||= {
2473 description => &{$escape}($description),
2474 #pkgpart => $part_pkg->pkgpart,
2482 product_code => 'N/A',
2483 ext_description => [],
2486 $lines{$phonenum}{$desc}{amount} += $amount;
2487 $lines{$phonenum}{$desc}{calls}++;
2488 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2490 my $line = $usage_class{$detail->classnum}->classname;
2491 $sections{"$phonenum $line"} ||=
2495 'sort_weight' => $usage_class{$detail->classnum}->weight,
2496 'phonenum' => $phonenum,
2497 'header' => [ @header ],
2499 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2500 $sections{"$phonenum $line"}{calls}++;
2501 $sections{"$phonenum $line"}{duration} += $detail->duration;
2503 $lines{"$phonenum $line"}{$desc} ||= {
2504 description => &{$escape}($description),
2505 #pkgpart => $part_pkg->pkgpart,
2513 product_code => 'N/A',
2514 ext_description => [],
2517 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2518 $lines{"$phonenum $line"}{$desc}{calls}++;
2519 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2520 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2521 $detail->formatted('format' => $format);
2526 my %sectionmap = ();
2527 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2528 foreach ( keys %sections ) {
2529 my @header = @{ $sections{$_}{header} || [] };
2531 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2532 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2533 my $usage_class = $summary ? $simple : $usage_simple;
2534 my $ending = $summary ? ' usage charges' : '';
2537 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2539 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2540 'amount' => $sections{$_}{amount}, #subtotal
2541 'calls' => $sections{$_}{calls},
2542 'duration' => $sections{$_}{duration},
2544 'tax_section' => '',
2545 'phonenum' => $sections{$_}{phonenum},
2546 'sort_weight' => $sections{$_}{sort_weight},
2547 'post_total' => $summary, #inspire pagebreak
2549 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2550 qw( description_generator
2553 total_line_generator
2560 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2561 $a->{sort_weight} <=> $b->{sort_weight}
2566 foreach my $section ( keys %lines ) {
2567 foreach my $line ( keys %{$lines{$section}} ) {
2568 my $l = $lines{$section}{$line};
2569 $l->{section} = $sectionmap{$section};
2570 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2571 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2576 if($conf->exists('phone_usage_class_summary')) {
2577 # this only works with Latex
2581 # after this, we'll have only two sections per DID:
2582 # Calls Summary and Calls Detail
2583 foreach my $section ( @sections ) {
2584 if($section->{'post_total'}) {
2585 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2586 $section->{'total_line_generator'} = sub { '' };
2587 $section->{'total_generator'} = sub { '' };
2588 $section->{'header_generator'} = sub { '' };
2589 $section->{'description_generator'} = '';
2590 push @newsections, $section;
2591 my %calls_detail = %$section;
2592 $calls_detail{'post_total'} = '';
2593 $calls_detail{'sort_weight'} = '';
2594 $calls_detail{'description_generator'} = sub { '' };
2595 $calls_detail{'header_generator'} = sub {
2596 return ' & Date/Time & Called Number & Duration & Price'
2597 if $format eq 'latex';
2600 $calls_detail{'description'} = 'Calls Detail: '
2601 . $section->{'phonenum'};
2602 push @newsections, \%calls_detail;
2606 # after this, each usage class is collapsed/summarized into a single
2607 # line under the Calls Summary section
2608 foreach my $newsection ( @newsections ) {
2609 if($newsection->{'post_total'}) { # this means Calls Summary
2610 foreach my $section ( @sections ) {
2611 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2612 && !$section->{'post_total'});
2613 my $newdesc = $section->{'description'};
2614 my $tn = $section->{'phonenum'};
2615 $newdesc =~ s/$tn//g;
2616 my $line = { ext_description => [],
2620 calls => $section->{'calls'},
2621 section => $newsection,
2622 duration => $section->{'duration'},
2623 description => $newdesc,
2624 amount => sprintf("%.2f",$section->{'amount'}),
2625 product_code => 'N/A',
2627 push @newlines, $line;
2632 # after this, Calls Details is populated with all CDRs
2633 foreach my $newsection ( @newsections ) {
2634 if(!$newsection->{'post_total'}) { # this means Calls Details
2635 foreach my $line ( @lines ) {
2636 next unless (scalar(@{$line->{'ext_description'}}) &&
2637 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2639 my @extdesc = @{$line->{'ext_description'}};
2641 foreach my $extdesc ( @extdesc ) {
2642 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2643 push @newextdesc, $extdesc;
2645 $line->{'ext_description'} = \@newextdesc;
2646 $line->{'section'} = $newsection;
2647 push @newlines, $line;
2652 return(\@newsections, \@newlines);
2655 return(\@sections, \@lines);
2659 =sub _items_usage_class_summary OPTIONS
2661 Returns a list of detail items summarizing the usage charges on this
2662 invoice. Each one will have 'amount', 'description' (the usage charge name),
2663 and 'usage_classnum'.
2665 OPTIONS can include 'escape' (a function to escape the descriptions).
2669 sub _items_usage_class_summary {
2673 my $escape = $opt{escape} || sub { $_[0] };
2674 my $money_char = $opt{money_char};
2675 my $invnum = $self->invnum;
2676 my @classes = qsearch({
2677 'table' => 'usage_class',
2678 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2679 ' COUNT(*) AS calls, SUM(duration) AS duration',
2680 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2681 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2682 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2683 ' GROUP BY classnum, classname, weight'.
2684 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2685 ' ORDER BY weight ASC',
2689 description => &{$escape}($self->mt('Usage Summary')),
2693 foreach my $class (@classes) {
2694 $section->{subtotal} += $class->get('amount');
2696 'description' => &{$escape}($class->classname),
2697 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2698 'quantity' => $class->get('calls'),
2699 'duration' => $class->get('duration'),
2700 'usage_classnum' => $class->classnum,
2701 'section' => $section,
2704 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2708 sub _items_previous {
2710 my $conf = $self->conf;
2711 my $cust_main = $self->cust_main;
2712 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2714 foreach ( @pr_cust_bill ) {
2715 my $date = $conf->exists('invoice_show_prior_due_date')
2716 ? 'due '. $_->due_date2str('short')
2717 : $self->time2str_local('short', $_->_date);
2719 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2720 #'pkgpart' => 'N/A',
2722 'amount' => sprintf("%.2f", $_->owed),
2728 # 'description' => 'Previous Balance',
2729 # #'pkgpart' => 'N/A',
2730 # 'pkgnum' => 'N/A',
2731 # 'amount' => sprintf("%10.2f", $pr_total ),
2732 # 'ext_description' => [ map {
2733 # "Invoice ". $_->invnum.
2734 # " (". time2str("%x",$_->_date). ") ".
2735 # sprintf("%10.2f", $_->owed)
2736 # } @pr_cust_bill ],
2741 sub _items_credits {
2742 my( $self, %opt ) = @_;
2743 my $trim_len = $opt{'trim_len'} || 40;
2748 if ( $self->conf->exists('previous_balance-payments_since') ) {
2749 if ( $opt{'template'} eq 'statement' ) {
2750 # then the current bill is a "statement" (i.e. an invoice sent as
2751 # a payment receipt)
2752 # and in that case we want to see payments on or after THIS invoice
2753 @objects = qsearch('cust_credit', {
2754 'custnum' => $self->custnum,
2755 '_date' => {op => '>=', value => $self->_date},
2759 $date = $self->previous_bill->_date if $self->previous_bill;
2760 @objects = qsearch('cust_credit', {
2761 'custnum' => $self->custnum,
2762 '_date' => {op => '>=', value => $date},
2766 @objects = $self->cust_credited;
2769 foreach my $obj ( @objects ) {
2770 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2772 my $reason = substr($cust_credit->reason, 0, $trim_len);
2773 $reason .= '...' if length($reason) < length($cust_credit->reason);
2774 $reason = " ($reason) " if $reason;
2777 #'description' => 'Credit ref\#'. $_->crednum.
2778 # " (". time2str("%x",$_->cust_credit->_date) .")".
2780 'description' => $self->mt('Credit applied').' '.
2781 $self->time2str_local('short', $obj->_date). $reason,
2782 'amount' => sprintf("%.2f",$obj->amount),
2790 sub _items_payments {
2795 my $detailed = $self->conf->exists('invoice_payment_details');
2797 if ( $self->conf->exists('previous_balance-payments_since') ) {
2798 # then show payments dated on/after the previous bill...
2799 if ( $opt{'template'} eq 'statement' ) {
2800 # then the current bill is a "statement" (i.e. an invoice sent as
2801 # a payment receipt)
2802 # and in that case we want to see payments on or after THIS invoice
2803 @objects = qsearch('cust_pay', {
2804 'custnum' => $self->custnum,
2805 '_date' => {op => '>=', value => $self->_date},
2808 # the normal case: payments on or after the previous invoice
2810 $date = $self->previous_bill->_date if $self->previous_bill;
2811 @objects = qsearch('cust_pay', {
2812 'custnum' => $self->custnum,
2813 '_date' => {op => '>=', value => $date},
2815 # and before the current bill...
2816 @objects = grep { $_->_date < $self->_date } @objects;
2819 @objects = $self->cust_bill_pay;
2822 foreach my $obj (@objects) {
2823 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2824 my $desc = $self->mt('Payment received').' '.
2825 $self->time2str_local('short', $cust_pay->_date );
2826 $desc .= $self->mt(' via ') .
2827 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2831 'description' => $desc,
2832 'amount' => sprintf("%.2f", $obj->amount )
2842 my $conf = $self->conf;
2845 my ($pr_total) = $self->previous;
2846 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2848 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2849 # if enabled, specifically add a line for the previous balance total
2850 $previous_charges_desc = $self->mt(
2851 $conf->config('previous_balance-text') || 'Previous Balance'
2854 # then return separate lines for previous balance and total new charges
2857 { total_item => $previous_charges_desc,
2858 total_amount => sprintf('%.2f',$pr_total)
2863 if ( $conf->exists('previous_balance-exclude_from_total')
2864 or !$self->enable_previous ) {
2865 # show new charges only
2867 $new_charges_desc = $self->mt(
2868 $conf->config('previous_balance-text-total_new_charges')
2869 || 'Total New Charges'
2872 $new_charges_amount = $self->charged;
2875 # show new charges + previous invoice total
2877 $new_charges_desc = $self->mt('Total Charges');
2878 if ( $self->enable_previous ) {
2879 $new_charges_amount = sprintf('%.2f', $self->charged + $pr_total);
2881 $new_charges_amount = sprintf('%.2f', $self->charged);
2886 if ( $conf->exists('invoice_show_prior_due_date') ) {
2887 # then the due date should be shown with Total New Charges,
2888 # and should NOT be shown with the Balance Due message.
2889 if ( $self->due_date ) {
2890 # localize the "Please pay by" message and the date itself
2891 # (grammar issues with this, yeah)
2892 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2893 $self->due_date2str('short');
2894 } elsif ( $self->terms ) {
2895 # phrases like "due on receipt" should be localized
2896 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2901 { total_item => $new_charges_desc,
2902 total_amount => $new_charges_amount,
2910 =item call_details [ OPTION => VALUE ... ]
2912 Returns an array of CSV strings representing the call details for this invoice
2913 The only option available is the boolean prepend_billed_number
2918 my ($self, %opt) = @_;
2920 my $format_function = sub { shift };
2922 if ($opt{prepend_billed_number}) {
2923 $format_function = sub {
2927 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2932 my @details = map { $_->details( 'format_function' => $format_function,
2933 'escape_function' => sub{ return() },
2937 $self->cust_bill_pkg;
2938 my $header = $details[0];
2939 ( $header, grep { $_ ne $header } @details );
2942 =item cust_pay_batch
2944 Returns all L<FS::cust_pay_batch> records linked to this invoice. Deprecated,
2949 sub cust_pay_batch {
2950 carp "FS::cust_bill->cust_pay_batch is deprecated";
2952 qsearch('cust_pay_batch', { 'invnum' => $self->invnum });
2961 =item process_reprint
2965 sub process_reprint {
2966 process_re_X('print', @_);
2969 =item process_reemail
2973 sub process_reemail {
2974 process_re_X('email', @_);
2982 process_re_X('fax', @_);
2990 process_re_X('ftp', @_);
2997 sub process_respool {
2998 process_re_X('spool', @_);
3003 my( $method, $job ) = ( shift, shift );
3004 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3007 warn Dumper($param) if $DEBUG;
3017 # this is called from search/cust_bill.html and given all its search
3018 # parameters, so it needs to perform the same search.
3021 # spool_invoice ftp_invoice fax_invoice print_invoice
3022 my($method, $job, %param ) = @_;
3024 warn "re_X $method for job $job with param:\n".
3025 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3028 #some false laziness w/search/cust_bill.html
3029 $param{'order_by'} = 'cust_bill._date';
3031 my $query = FS::cust_bill->search(\%param);
3032 delete $query->{'count_query'};
3033 delete $query->{'count_addl'};
3035 $query->{debug} = 1; # was in here before, is obviously useful
3037 my @cust_bill = qsearch( $query );
3039 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3041 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3044 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3045 foreach my $cust_bill ( @cust_bill ) {
3046 $cust_bill->$method();
3048 if ( $job ) { #progressbar foo
3050 if ( time - $min_sec > $last ) {
3051 my $error = $job->update_statustext(
3052 int( 100 * $num / scalar(@cust_bill) )
3054 die $error if $error;
3065 +{ ( map { $_=>$self->$_ } $self->fields ),
3066 'owed' => $self->owed,
3067 #XXX last payment applied date
3073 =head1 CLASS METHODS
3079 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3084 my ($class, $start, $end) = @_;
3086 $class->paid_sql($start, $end). ' - '.
3087 $class->credited_sql($start, $end);
3092 Returns an SQL fragment to retreive the net amount (charged minus credited).
3097 my ($class, $start, $end) = @_;
3098 'charged - '. $class->credited_sql($start, $end);
3103 Returns an SQL fragment to retreive the amount paid against this invoice.
3108 my ($class, $start, $end) = @_;
3109 $start &&= "AND cust_bill_pay._date <= $start";
3110 $end &&= "AND cust_bill_pay._date > $end";
3111 $start = '' unless defined($start);
3112 $end = '' unless defined($end);
3113 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3114 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3119 Returns an SQL fragment to retreive the amount credited against this invoice.
3124 my ($class, $start, $end) = @_;
3125 $start &&= "AND cust_credit_bill._date <= $start";
3126 $end &&= "AND cust_credit_bill._date > $end";
3127 $start = '' unless defined($start);
3128 $end = '' unless defined($end);
3129 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3130 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3135 Returns an SQL fragment to retrieve the due date of an invoice.
3136 Currently only supported on PostgreSQL.
3141 die "don't use: doesn't account for agent-specific invoice_default_terms";
3143 #we're passed a $conf but not a specific customer (that's in the query), so
3144 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3145 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3148 my $conf = new FS::Conf;
3152 cust_bill.invoice_terms,
3153 cust_main.invoice_terms,
3154 \''.($conf->config('invoice_default_terms') || '').'\'
3155 ), E\'Net (\\\\d+)\'
3157 ) * 86400 + cust_bill._date'
3168 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3169 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base