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;
280 DO NOT USE THIS METHOD. Instead, apply a credit against the invoice, or use
283 This is only for internal use by V<void>, which is what you should be using.
285 DO NOT USE THIS METHOD. Whatever reason you think you have is almost certainly
286 wrong. Use B<void>, that's what it is for. Really. This means you.
292 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
294 local $SIG{HUP} = 'IGNORE';
295 local $SIG{INT} = 'IGNORE';
296 local $SIG{QUIT} = 'IGNORE';
297 local $SIG{TERM} = 'IGNORE';
298 local $SIG{TSTP} = 'IGNORE';
299 local $SIG{PIPE} = 'IGNORE';
301 my $oldAutoCommit = $FS::UID::AutoCommit;
302 local $FS::UID::AutoCommit = 0;
305 foreach my $table (qw(
312 #cust_event # problematic
313 #cust_pay_batch # unnecessary
315 foreach my $linked ( $self->$table() ) {
316 my $error = $linked->delete;
318 $dbh->rollback if $oldAutoCommit;
325 my $error = $self->SUPER::delete(@_);
327 $dbh->rollback if $oldAutoCommit;
331 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
337 =item replace [ OLD_RECORD ]
339 You can, but probably shouldn't modify invoices...
341 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
342 supplied, replaces this record. If there is an error, returns the error,
343 otherwise returns false.
347 #replace can be inherited from Record.pm
349 # replace_check is now the preferred way to #implement replace data checks
350 # (so $object->replace() works without an argument)
353 my( $new, $old ) = ( shift, shift );
354 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
355 #return "Can't change _date!" unless $old->_date eq $new->_date;
356 return "Can't change _date" unless $old->_date == $new->_date;
357 return "Can't change charged" unless $old->charged == $new->charged
358 || $old->pending eq 'Y'
359 || $old->charged == 0
360 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
366 =item add_cc_surcharge
372 sub add_cc_surcharge {
373 my ($self, $pkgnum, $amount) = (shift, shift, shift);
376 my $cust_bill_pkg = new FS::cust_bill_pkg({
377 'invnum' => $self->invnum,
381 $error = $cust_bill_pkg->insert;
382 return $error if $error;
384 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
385 $self->charged($self->charged+$amount);
386 $error = $self->replace;
387 return $error if $error;
389 $self->apply_payments_and_credits;
395 Checks all fields to make sure this is a valid invoice. If there is an error,
396 returns the error, otherwise returns false. Called by the insert and replace
405 $self->ut_numbern('invnum')
406 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
407 || $self->ut_numbern('_date')
408 || $self->ut_money('charged')
409 || $self->ut_numbern('printed')
410 || $self->ut_enum('closed', [ '', 'Y' ])
411 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
412 || $self->ut_numbern('agent_invid') #varchar?
413 || $self->ut_flag('pending')
415 return $error if $error;
417 $self->_date(time) unless $self->_date;
419 $self->printed(0) if $self->printed eq '';
426 Returns the displayed invoice number for this invoice: agent_invid if
427 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
433 if ( $self->agent_invid
434 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
435 return $self->agent_invid;
437 return $self->invnum;
443 Returns the customer's last invoice before this one.
449 if ( !$self->get('previous_bill') ) {
450 $self->set('previous_bill', qsearchs({
451 'table' => 'cust_bill',
452 'hashref' => { 'custnum' => $self->custnum,
453 '_date' => { op=>'<', value=>$self->_date } },
454 'order_by' => 'ORDER BY _date DESC LIMIT 1',
457 $self->get('previous_bill');
462 Returns a list consisting of the total previous balance for this customer,
463 followed by the previous outstanding invoices (as FS::cust_bill objects also).
469 # simple memoize; we use this a lot
470 if (!$self->get('previous')) {
472 my @cust_bill = sort { $a->_date <=> $b->_date }
473 grep { $_->owed != 0 }
474 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
475 #'_date' => { op=>'<', value=>$self->_date },
476 'invnum' => { op=>'<', value=>$self->invnum },
479 foreach ( @cust_bill ) { $total += $_->owed; }
480 $self->set('previous', [$total, @cust_bill]);
482 return @{ $self->get('previous') };
485 =item enable_previous
487 Whether to show the 'Previous Charges' section when printing this invoice.
488 The negation of the 'disable_previous_balance' config setting.
492 sub enable_previous {
494 my $agentnum = $self->cust_main->agentnum;
495 !$self->conf->exists('disable_previous_balance', $agentnum);
500 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
507 { 'table' => 'cust_bill_pkg',
508 'hashref' => { 'invnum' => $self->invnum },
509 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
510 # the AUTLOADED FK search. or should
511 # that default to ORDER by the pkey?
516 =item cust_bill_pkg_pkgnum PKGNUM
518 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
523 sub cust_bill_pkg_pkgnum {
524 my( $self, $pkgnum ) = @_;
526 { 'table' => 'cust_bill_pkg',
527 'hashref' => { 'invnum' => $self->invnum,
530 'order_by' => 'ORDER BY billpkgnum',
537 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
544 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
545 $self->cust_bill_pkg;
547 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
552 Returns true if any of the packages (or their definitions) corresponding to the
553 line items for this invoice have the no_auto flag set.
559 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
562 =item open_cust_bill_pkg
564 Returns the open line items for this invoice.
566 Note that cust_bill_pkg with both setup and recur fees are returned as two
567 separate line items, each with only one fee.
571 # modeled after cust_main::open_cust_bill
572 sub open_cust_bill_pkg {
575 # grep { $_->owed > 0 } $self->cust_bill_pkg
577 my %other = ( 'recur' => 'setup',
578 'setup' => 'recur', );
580 foreach my $field ( qw( recur setup )) {
581 push @open, map { $_->set( $other{$field}, 0 ); $_; }
582 grep { $_->owed($field) > 0 }
583 $self->cust_bill_pkg;
591 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
595 #false laziness w/cust_pkg.pm
599 'table' => 'cust_event',
600 'addl_from' => 'JOIN part_event USING ( eventpart )',
601 'hashref' => { 'tablenum' => $self->invnum },
602 'extra_sql' => " AND eventtable = 'cust_bill' ",
608 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
612 #false laziness w/cust_pkg.pm
616 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
617 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
618 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
619 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
620 $sth->fetchrow_arrayref->[0];
625 Returns the customer (see L<FS::cust_main>) for this invoice.
629 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice
631 Returns a list: an empty list on success or a list of errors.
638 grep { $_->suspend(@_) }
639 grep {! $_->getfield('cancel') }
644 =item cust_suspend_if_balance_over AMOUNT
646 Suspends the customer associated with this invoice if the total amount owed on
647 this invoice and all older invoices is greater than the specified amount.
649 Returns a list: an empty list on success or a list of errors.
653 sub cust_suspend_if_balance_over {
654 my( $self, $amount ) = ( shift, shift );
655 my $cust_main = $self->cust_main;
656 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
659 $cust_main->suspend(@_);
665 Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options
670 my( $self, %opt ) = @_;
672 warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
673 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
676 return ( 'Access denied' )
677 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
679 my @pkgs = $self->cust_pkg;
681 if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
683 my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
684 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
689 map { $_->cancel(%opt) }
690 grep { ! $_->getfield('cancel') }
696 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
702 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
703 sort { $a->_date <=> $b->_date }
704 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
709 =item cust_credit_bill
711 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
717 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
718 sort { $a->_date <=> $b->_date }
719 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
723 sub cust_credit_bill {
724 shift->cust_credited(@_);
727 #=item cust_bill_pay_pkgnum PKGNUM
729 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
730 #with matching pkgnum.
734 #sub cust_bill_pay_pkgnum {
735 # my( $self, $pkgnum ) = @_;
736 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
737 # sort { $a->_date <=> $b->_date }
738 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
739 # 'pkgnum' => $pkgnum,
744 =item cust_bill_pay_pkg PKGNUM
746 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
747 applied against the matching pkgnum.
751 sub cust_bill_pay_pkg {
752 my( $self, $pkgnum ) = @_;
755 'select' => 'cust_bill_pay_pkg.*',
756 'table' => 'cust_bill_pay_pkg',
757 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
758 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
759 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
760 " AND cust_bill_pkg.pkgnum = $pkgnum",
765 #=item cust_credited_pkgnum PKGNUM
767 #=item cust_credit_bill_pkgnum PKGNUM
769 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
770 #with matching pkgnum.
774 #sub cust_credited_pkgnum {
775 # my( $self, $pkgnum ) = @_;
776 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
777 # sort { $a->_date <=> $b->_date }
778 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
779 # 'pkgnum' => $pkgnum,
784 #sub cust_credit_bill_pkgnum {
785 # shift->cust_credited_pkgnum(@_);
788 =item cust_credit_bill_pkg PKGNUM
790 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
791 applied against the matching pkgnum.
795 sub cust_credit_bill_pkg {
796 my( $self, $pkgnum ) = @_;
799 'select' => 'cust_credit_bill_pkg.*',
800 'table' => 'cust_credit_bill_pkg',
801 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
802 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
803 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
804 " AND cust_bill_pkg.pkgnum = $pkgnum",
809 =item cust_bill_batch
811 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
815 sub cust_bill_batch {
817 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
822 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
823 hash keyed by term length.
829 FS::discount_plan->all($self);
834 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
841 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
843 foreach (@taxlines) { $total += $_->setup; }
849 Returns the amount owed (still outstanding) on this invoice, which is charged
850 minus all payment applications (see L<FS::cust_bill_pay>) and credit
851 applications (see L<FS::cust_credit_bill>).
857 my $balance = $self->charged;
858 $balance -= $_->amount foreach ( $self->cust_bill_pay );
859 $balance -= $_->amount foreach ( $self->cust_credited );
860 $balance = sprintf( "%.2f", $balance);
861 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
866 my( $self, $pkgnum ) = @_;
868 #my $balance = $self->charged;
870 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
872 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
873 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
875 $balance = sprintf( "%.2f", $balance);
876 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
882 Returns true if this invoice should be hidden. See the
883 selfservice-hide_invoices-taxclass configuraiton setting.
889 my $conf = $self->conf;
890 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
892 my @cust_bill_pkg = $self->cust_bill_pkg;
893 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
894 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
897 =item apply_payments_and_credits [ OPTION => VALUE ... ]
899 Applies unapplied payments and credits to this invoice.
900 Payments with the no_auto_apply flag set will not be applied.
902 A hash of optional arguments may be passed. Currently "manual" is supported.
903 If true, a payment receipt is sent instead of a statement when
904 'payment_receipt_email' configuration option is set.
906 If there is an error, returns the error, otherwise returns false.
910 sub apply_payments_and_credits {
911 my( $self, %options ) = @_;
912 my $conf = $self->conf;
914 local $SIG{HUP} = 'IGNORE';
915 local $SIG{INT} = 'IGNORE';
916 local $SIG{QUIT} = 'IGNORE';
917 local $SIG{TERM} = 'IGNORE';
918 local $SIG{TSTP} = 'IGNORE';
919 local $SIG{PIPE} = 'IGNORE';
921 my $oldAutoCommit = $FS::UID::AutoCommit;
922 local $FS::UID::AutoCommit = 0;
925 $self->select_for_update; #mutex
927 my @payments = grep { $_->unapplied > 0 }
928 grep { !$_->no_auto_apply }
929 $self->cust_main->cust_pay;
930 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
932 if ( $conf->exists('pkg-balances') ) {
933 # limit @payments & @credits to those w/ a pkgnum grepped from $self
934 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
935 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
936 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
939 while ( $self->owed > 0 and ( @payments || @credits ) ) {
942 if ( @payments && @credits ) {
944 #decide which goes first by weight of top (unapplied) line item
946 my @open_lineitems = $self->open_cust_bill_pkg;
949 max( map { $_->part_pkg->pay_weight || 0 }
954 my $max_credit_weight =
955 max( map { $_->part_pkg->credit_weight || 0 }
961 #if both are the same... payments first? it has to be something
962 if ( $max_pay_weight >= $max_credit_weight ) {
968 } elsif ( @payments ) {
970 } elsif ( @credits ) {
973 die "guru meditation #12 and 35";
977 if ( $app eq 'pay' ) {
979 my $payment = shift @payments;
980 $unapp_amount = $payment->unapplied;
981 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
982 $app->pkgnum( $payment->pkgnum )
983 if $conf->exists('pkg-balances') && $payment->pkgnum;
985 } elsif ( $app eq 'credit' ) {
987 my $credit = shift @credits;
988 $unapp_amount = $credit->credited;
989 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
990 $app->pkgnum( $credit->pkgnum )
991 if $conf->exists('pkg-balances') && $credit->pkgnum;
994 die "guru meditation #12 and 35";
998 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
999 warn "owed_pkgnum ". $app->pkgnum;
1000 $owed = $self->owed_pkgnum($app->pkgnum);
1002 $owed = $self->owed;
1004 next unless $owed > 0;
1006 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1007 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1009 $app->invnum( $self->invnum );
1011 my $error = $app->insert(%options);
1013 $dbh->rollback if $oldAutoCommit;
1014 return "Error inserting ". $app->table. " record: $error";
1016 die $error if $error;
1020 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1027 Sends this invoice to the destinations configured for this customer: sends
1028 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1030 Options can be passed as a hashref. Positional parameters are no longer
1033 I<template>: a suffix for alternate invoices
1035 I<agentnum>: obsolete, now does nothing.
1037 I<from> overrides the default email invoice From: address.
1039 I<amount>: obsolete, does nothing
1041 I<notice_name> overrides "Invoice" as the name of the sent document
1042 (templates from 10/2009 or newer required).
1044 I<lpr> overrides the system 'lpr' option as the command to print a document
1045 from standard input.
1051 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1052 my $conf = $self->conf;
1054 my $cust_main = $self->cust_main;
1056 my @invoicing_list = $cust_main->invoicing_list;
1059 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1060 && ! $cust_main->invoice_noemail;
1063 if grep { $_ eq 'POST' } @invoicing_list; #postal
1065 #this has never been used post-$ORIGINAL_ISP afaik
1066 $self->fax_invoice($opt)
1067 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1075 my $opt = shift || {};
1076 if ($opt and !ref($opt)) {
1077 die ref($self). '->email called with positional parameters';
1080 my $conf = $self->conf;
1082 my $from = delete $opt->{from};
1084 # this is where we set the From: address
1085 $from ||= $self->_agent_invoice_from || #XXX should go away
1086 $conf->invoice_from_full( $self->cust_main->agentnum );
1088 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1090 if ( ! @invoicing_list ) { #no recipients
1091 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1092 die 'No recipients for customer #'. $self->custnum;
1094 #default: better to notify this person than silence
1095 @invoicing_list = ($from);
1099 $self->SUPER::email( {
1101 'to' => \@invoicing_list,
1107 #this stays here for now because its explicitly used as
1108 # FS::cust_bill::queueable_email
1109 sub queueable_email {
1112 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1113 or die "invalid invoice number: " . $opt{invnum};
1116 $self->set('mode', $opt{mode});
1119 my %args = map {$_ => $opt{$_}}
1121 qw( from notice_name no_coupon template );
1123 my $error = $self->email( \%args );
1124 die $error if $error;
1130 my $conf = $self->conf;
1132 #my $template = scalar(@_) ? shift : '';
1135 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1138 my $cust_main = $self->cust_main;
1139 my $name = $cust_main->name;
1140 my $name_short = $cust_main->name_short;
1141 my $invoice_number = $self->invnum;
1142 my $invoice_date = $self->_date_pretty;
1144 eval qq("$subject");
1147 =item lpr_data HASHREF
1149 Returns the postscript or plaintext for this invoice as an arrayref.
1151 Options must be passed as a hashref. Positional parameters are no longer
1154 I<template>, if specified, is the name of a suffix for alternate invoices.
1156 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1162 my $conf = $self->conf;
1163 my $opt = shift || {};
1164 if ($opt and !ref($opt)) {
1165 # nobody does this anyway
1166 die "FS::cust_bill::lpr_data called with positional parameters";
1169 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1170 [ $self->$method( $opt ) ];
1175 Prints this invoice.
1177 Options must be passed as a hashref.
1179 I<template>, if specified, is the name of a suffix for alternate invoices.
1181 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1187 return if $self->hide;
1188 my $conf = $self->conf;
1189 my $opt = shift || {};
1190 if ($opt and !ref($opt)) {
1191 die "FS::cust_bill::print called with positional parameters";
1194 my $lpr = delete $opt->{lpr};
1195 if($conf->exists('invoice_print_pdf')) {
1196 # Add the invoice to the current batch.
1197 $self->batch_invoice($opt);
1201 $self->lpr_data($opt),
1202 'agentnum' => $self->cust_main->agentnum,
1208 =item fax_invoice HASHREF
1212 Options must be passed as a hashref.
1214 I<template>, if specified, is the name of a suffix for alternate invoices.
1216 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1222 return if $self->hide;
1223 my $conf = $self->conf;
1224 my $opt = shift || {};
1225 if ($opt and !ref($opt)) {
1226 die "FS::cust_bill::fax_invoice called with positional parameters";
1229 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1230 unless $conf->exists('invoice_latex');
1232 my $dialstring = $self->cust_main->getfield('fax');
1235 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1236 'dialstring' => $dialstring,
1238 die $error if $error;
1242 =item batch_invoice [ HASHREF ]
1244 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1245 isn't an open batch, one will be created.
1247 HASHREF may contain any options to be passed to C<print_pdf>.
1252 my ($self, $opt) = @_;
1253 my $bill_batch = $self->get_open_bill_batch;
1254 my $cust_bill_batch = FS::cust_bill_batch->new({
1255 batchnum => $bill_batch->batchnum,
1256 invnum => $self->invnum,
1258 return $cust_bill_batch->insert($opt);
1261 =item get_open_batch
1263 Returns the currently open batch as an FS::bill_batch object, creating a new
1264 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1269 sub get_open_bill_batch {
1271 my $conf = $self->conf;
1272 my $hashref = { status => 'O' };
1273 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1274 ? $self->cust_main->agentnum
1276 my $batch = qsearchs('bill_batch', $hashref);
1277 return $batch if $batch;
1278 $batch = FS::bill_batch->new($hashref);
1279 my $error = $batch->insert;
1280 die $error if $error;
1284 =item ftp_invoice [ TEMPLATENAME ]
1286 Sends this invoice data via FTP.
1288 TEMPLATENAME is unused?
1294 my $conf = $self->conf;
1295 my $template = scalar(@_) ? shift : '';
1298 'protocol' => 'ftp',
1299 'server' => $conf->config('cust_bill-ftpserver'),
1300 'username' => $conf->config('cust_bill-ftpusername'),
1301 'password' => $conf->config('cust_bill-ftppassword'),
1302 'dir' => $conf->config('cust_bill-ftpdir'),
1303 'format' => $conf->config('cust_bill-ftpformat'),
1307 =item spool_invoice [ TEMPLATENAME ]
1309 Spools this invoice data (see L<FS::spool_csv>)
1311 TEMPLATENAME is unused?
1317 my $conf = $self->conf;
1318 my $template = scalar(@_) ? shift : '';
1321 'format' => $conf->config('cust_bill-spoolformat'),
1322 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1326 =item send_csv OPTION => VALUE, ...
1328 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1332 protocol - currently only "ftp"
1338 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1339 and YYMMDDHHMMSS is a timestamp.
1341 See L</print_csv> for a description of the output format.
1346 my($self, %opt) = @_;
1350 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1351 mkdir $spooldir, 0700 unless -d $spooldir;
1353 # don't localize dates here, they're a defined format
1354 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1355 my $file = "$spooldir/$tracctnum.csv";
1357 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1359 open(CSV, ">$file") or die "can't open $file: $!";
1367 if ( $opt{protocol} eq 'ftp' ) {
1368 eval "use Net::FTP;";
1370 $net = Net::FTP->new($opt{server}) or die @$;
1372 die "unknown protocol: $opt{protocol}";
1375 $net->login( $opt{username}, $opt{password} )
1376 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1378 $net->binary or die "can't set binary mode";
1380 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1382 $net->put($file) or die "can't put $file: $!";
1392 Spools CSV invoice data.
1398 =item format - any of FS::Misc::::Invoicing::spool_formats
1400 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1401 customer has the corresponding invoice destinations set (see
1402 L<FS::cust_main_invoice>).
1404 =item agent_spools - if set to a true value, will spool to per-agent files
1405 rather than a single global file
1407 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1408 append to that spool. L<FS::Cron::upload> will then send the spool file to
1411 =item balanceover - if set, only spools the invoice if the total amount owed on
1412 this invoice and all older invoices is greater than the specified amount.
1414 =item time - the "current time". Controls the printing of past due messages
1422 my($self, %opt) = @_;
1424 my $time = $opt{'time'} || time;
1425 my $cust_main = $self->cust_main;
1427 if ( $opt{'dest'} ) {
1428 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1429 $cust_main->invoicing_list;
1430 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1431 || ! keys %invoicing_list;
1434 if ( $opt{'balanceover'} ) {
1436 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1439 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1440 mkdir $spooldir, 0700 unless -d $spooldir;
1442 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1445 if ( $opt{'agent_spools'} ) {
1446 $file = 'agentnum'.$cust_main->agentnum;
1451 if ( $opt{'upload_targetnum'} ) {
1452 $spooldir .= '/target'.$opt{'upload_targetnum'};
1453 mkdir $spooldir, 0700 unless -d $spooldir;
1454 } # otherwise it just goes into export.xxx/cust_bill
1456 if ( lc($opt{'format'}) eq 'billco' ) {
1460 $file = "$spooldir/$file.csv";
1462 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1464 open(CSV, ">>$file") or die "can't open $file: $!";
1465 flock(CSV, LOCK_EX);
1470 if ( lc($opt{'format'}) eq 'billco' ) {
1472 flock(CSV, LOCK_UN);
1475 $file =~ s/-header.csv$/-detail.csv/;
1477 open(CSV,">>$file") or die "can't open $file: $!";
1478 flock(CSV, LOCK_EX);
1482 print CSV $detail if defined($detail);
1484 flock(CSV, LOCK_UN);
1491 =item print_csv OPTION => VALUE, ...
1493 Returns CSV data for this invoice.
1497 format - 'default', 'billco', 'oneline', 'bridgestone'
1499 Returns a list consisting of two scalars. The first is a single line of CSV
1500 header information for this invoice. The second is one or more lines of CSV
1501 detail information for this invoice.
1503 If I<format> is not specified or "default", the fields of the CSV file are as
1506 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1507 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1511 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1513 B<record_type> is C<cust_bill> for the initial header line only. The
1514 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1515 fields are filled in.
1517 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1518 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1521 =item invnum - invoice number
1523 =item custnum - customer number
1525 =item _date - invoice date
1527 =item charged - total invoice amount
1529 =item first - customer first name
1531 =item last - customer first name
1533 =item company - company name
1535 =item address1 - address line 1
1537 =item address2 - address line 1
1547 =item pkg - line item description
1549 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1551 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1553 =item sdate - start date for recurring fee
1555 =item edate - end date for recurring fee
1559 If I<format> is "billco", the fields of the header CSV file are as follows:
1561 +-------------------------------------------------------------------+
1562 | FORMAT HEADER FILE |
1563 |-------------------------------------------------------------------|
1564 | Field | Description | Name | Type | Width |
1565 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1566 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1567 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1568 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1569 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1570 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1571 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1572 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1573 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1574 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1575 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1576 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1577 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1578 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1579 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1580 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1581 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1582 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1583 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1584 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1585 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1586 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1587 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1588 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1589 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1590 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1591 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1592 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1593 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1594 +-------+-------------------------------+------------+------+-------+
1596 If I<format> is "billco", the fields of the detail CSV file are as follows:
1598 FORMAT FOR DETAIL FILE
1600 Field | Description | Name | Type | Width
1601 1 | N/A-Leave Empty | RC | CHAR | 2
1602 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1603 3 | Account Number | TRACCTNUM | CHAR | 15
1604 4 | Invoice Number | TRINVOICE | CHAR | 15
1605 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1606 6 | Transaction Detail | DETAILS | CHAR | 100
1607 7 | Amount | AMT | NUM* | 9
1608 8 | Line Format Control** | LNCTRL | CHAR | 2
1609 9 | Grouping Code | GROUP | CHAR | 2
1610 10 | User Defined | ACCT CODE | CHAR | 15
1612 If format is 'oneline', there is no detail file. Each invoice has a
1613 header line only, with the fields:
1615 Agent number, agent name, customer number, first name, last name, address
1616 line 1, address line 2, city, state, zip, invoice date, invoice number,
1617 amount charged, amount due, previous balance, due date.
1619 and then, for each line item, three columns containing the package number,
1620 description, and amount.
1622 If format is 'bridgestone', there is no detail file. Each invoice has a
1623 header line with the following fields in a fixed-width format:
1625 Customer number (in display format), date, name (first last), company,
1626 address 1, address 2, city, state, zip.
1628 This is a mailing list format, and has no per-invoice fields. To avoid
1629 sending redundant notices, the spooling event should have a "once" or
1630 "once_percust_every" condition.
1635 my($self, %opt) = @_;
1637 eval "use Text::CSV_XS";
1640 my $cust_main = $self->cust_main;
1642 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1643 my $format = lc($opt{'format'});
1645 my $time = $opt{'time'} || time;
1647 my $tracctnum = ''; #leaking out from billco-specific sections :/
1648 if ( $format eq 'billco' ) {
1651 $self->conf->config('billco-account_num', $cust_main->agentnum);
1653 $tracctnum = $account_num eq 'display_custnum'
1654 ? $cust_main->display_custnum
1655 : $opt{'tracctnum'};
1658 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1660 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1662 my( $previous_balance, @unused ) = $self->previous; #previous balance
1664 my $pmt_cr_applied = 0;
1665 $pmt_cr_applied += $_->{'amount'}
1666 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1668 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1671 '', # 1 | N/A-Leave Empty CHAR 2
1672 '', # 2 | N/A-Leave Empty CHAR 15
1673 $tracctnum, # 3 | Transaction Account No CHAR 15
1674 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1675 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1676 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1677 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1678 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1679 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1680 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1681 '', # 10 | Ancillary Billing Information CHAR 30
1682 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1683 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1686 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1689 $duedate, # 14 | Bill Due Date CHAR 10
1691 $previous_balance, # 15 | Previous Balance NUM* 9
1692 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1693 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1694 $totaldue, # 18 | Total Amt Due NUM* 9
1695 $totaldue, # 19 | Total Amt Due NUM* 9
1696 '', # 20 | 30 Day Aging NUM* 9
1697 '', # 21 | 60 Day Aging NUM* 9
1698 '', # 22 | 90 Day Aging NUM* 9
1699 'N', # 23 | Y/N CHAR 1
1700 '', # 24 | Remittance automation CHAR 100
1701 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1702 $self->custnum, # 26 | Customer Reference Number CHAR 15
1703 '0', # 27 | Federal Tax*** NUM* 9
1704 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1705 '0', # 29 | Other Taxes & Fees*** NUM* 9
1708 } elsif ( $format eq 'oneline' ) { #name
1710 my ($previous_balance) = $self->previous;
1711 $previous_balance = sprintf('%.2f', $previous_balance);
1712 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1718 $self->_items_pkg, #_items_nontax? no sections or anything
1723 $cust_main->agentnum,
1724 $cust_main->agent->agent,
1728 $cust_main->company,
1729 $cust_main->address1,
1730 $cust_main->address2,
1736 time2str("%x", $self->_date),
1741 $self->due_date2str("%x"),
1746 } elsif ( $format eq 'bridgestone' ) {
1748 # bypass the CSV stuff and just return this
1749 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1750 my $zip = $cust_main->zip;
1752 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1756 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1758 $cust_main->display_custnum,
1760 uc(substr($cust_main->contact_firstlast,0,30)),
1761 uc(substr($cust_main->company ,0,30)),
1762 uc(substr($cust_main->address1 ,0,30)),
1763 uc(substr($cust_main->address2 ,0,30)),
1764 uc(substr($cust_main->city ,0,20)),
1765 uc($cust_main->state),
1771 } elsif ( $format eq 'ics' ) {
1773 my $bill = $cust_main->bill_location;
1774 my $zip = $bill->zip;
1778 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1783 # minor false laziness with print_generic
1784 my ($previous_balance) = $self->previous;
1785 my $balance_due = $self->owed + $previous_balance;
1786 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1787 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1790 if ( $self->due_date and $time >= $self->due_date ) {
1791 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1795 my $header = sprintf(
1796 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1797 $cust_main->display_custnum, #BID
1798 uc($cust_main->first), #FNAME
1799 uc($cust_main->last), #LNAME
1800 '00', #BATCH, should this ever be anything else?
1801 uc($cust_main->company), #COMP
1802 uc($bill->address1), #STREET1
1803 uc($bill->address2), #STREET2
1804 uc($bill->city), #CITY
1805 uc($bill->state), #STATE
1808 time2str('%Y%m%d', $self->_date), #BILL_DATE
1809 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1810 ( map {sprintf('%0.2f', $_)}
1811 $balance_due, #AMNT_DUE
1812 $previous_balance, #PREV_BAL
1813 $payment_total, #PYMT_RCVD
1814 $credit_total, #CREDITS
1815 $previous_balance, #BEG_BAL--is this correct?
1816 $self->charged, #NEW_CHRG
1819 $past_due, #PAST_MSG
1823 my %svc_class = ('' => ''); # maybe cache this more persistently?
1825 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1827 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1828 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1832 my @dates = ( $self->_date, undef );
1833 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1834 $dates[1] = $prev->sdate; #questionable
1837 # generate an 01 detail for each service
1838 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1839 foreach my $cust_svc ( @svcs ) {
1840 $show_pkgnum = ''; # hide it if we're showing svcnums
1842 my $svcpart = $cust_svc->svcpart;
1843 if (!exists($svc_class{$svcpart})) {
1844 my $classnum = $cust_svc->part_svc->classnum;
1845 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1847 $svc_class{$svcpart} = $part_svc_class ?
1848 $part_svc_class->classname :
1852 my @h_label = $cust_svc->label(@dates, 'I');
1853 push @details, sprintf('01%-9s%-20s%-47s',
1855 $svc_class{$svcpart},
1858 } #foreach $cust_svc
1861 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1862 if ($cust_bill_pkg->recur > 0) {
1863 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1864 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1866 push @details, sprintf('02%-6s%-60s%-10s',
1869 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1871 } #foreach $cust_bill_pkg
1873 # Tag this row so that we know whether this is one page (1), two pages
1874 # (2), # or "big" (B). The tag will be stripped off before uploading.
1875 if ( scalar(@details) < 12 ) {
1877 } elsif ( scalar(@details) < 58 ) {
1883 return join('', $header, @details, "\n");
1891 time2str("%x", $self->_date),
1892 sprintf("%.2f", $self->charged),
1893 ( map { $cust_main->getfield($_) }
1894 qw( first last company address1 address2 city state zip country ) ),
1896 ) or die "can't create csv";
1899 my $header = $csv->string. "\n";
1902 if ( lc($opt{'format'}) eq 'billco' ) {
1905 my %items_opt = ( format => 'template',
1906 escape_function => sub { shift } );
1907 # I don't know what characters billco actually tolerates in spool entries.
1908 # Text::CSV will take care of delimiters, though.
1910 my @items = ( $self->_items_pkg(%items_opt),
1911 $self->_items_fee(%items_opt) );
1912 foreach my $item (@items) {
1914 my $description = $item->{'description'};
1915 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1916 $description .= ': ' . $item->{ext_description}[0];
1920 '', # 1 | N/A-Leave Empty CHAR 2
1921 '', # 2 | N/A-Leave Empty CHAR 15
1922 $tracctnum, # 3 | Account Number CHAR 15
1923 $self->invnum, # 4 | Invoice Number CHAR 15
1924 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1925 $description, # 6 | Transaction Detail CHAR 100
1926 $item->{'amount'}, # 7 | Amount NUM* 9
1927 '', # 8 | Line Format Control** CHAR 2
1928 '', # 9 | Grouping Code CHAR 2
1929 '', # 10 | User Defined CHAR 15
1932 $detail .= $csv->string. "\n";
1936 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1942 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1944 my($pkg, $setup, $recur, $sdate, $edate);
1945 if ( $cust_bill_pkg->pkgnum ) {
1947 ($pkg, $setup, $recur, $sdate, $edate) = (
1948 $cust_bill_pkg->part_pkg->pkg,
1949 ( $cust_bill_pkg->setup != 0
1950 ? sprintf("%.2f", $cust_bill_pkg->setup )
1952 ( $cust_bill_pkg->recur != 0
1953 ? sprintf("%.2f", $cust_bill_pkg->recur )
1955 ( $cust_bill_pkg->sdate
1956 ? time2str("%x", $cust_bill_pkg->sdate)
1958 ($cust_bill_pkg->edate
1959 ? time2str("%x", $cust_bill_pkg->edate)
1963 } else { #pkgnum tax
1964 next unless $cust_bill_pkg->setup != 0;
1965 $pkg = $cust_bill_pkg->desc;
1966 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1967 ( $sdate, $edate ) = ( '', '' );
1973 ( map { '' } (1..11) ),
1974 ($pkg, $setup, $recur, $sdate, $edate)
1975 ) or die "can't create csv";
1977 $detail .= $csv->string. "\n";
1983 ( $header, $detail );
1988 croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
1993 Attempts to pay this invoice with a credit card payment via a
1994 Business::OnlinePayment realtime gateway. See
1995 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1996 for supported processors.
2002 $self->realtime_bop( 'CC', @_ );
2007 Attempts to pay this invoice with an electronic check (ACH) payment via a
2008 Business::OnlinePayment realtime gateway. See
2009 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2010 for supported processors.
2016 $self->realtime_bop( 'ECHECK', @_ );
2021 Attempts to pay this invoice with phone bill (LEC) payment via a
2022 Business::OnlinePayment realtime gateway. See
2023 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2024 for supported processors.
2030 $self->realtime_bop( 'LEC', @_ );
2034 my( $self, $method ) = (shift,shift);
2035 my $conf = $self->conf;
2038 my $cust_main = $self->cust_main;
2039 my $balance = $cust_main->balance;
2040 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2041 $amount = sprintf("%.2f", $amount);
2042 return "not run (balance $balance)" unless $amount > 0;
2044 my $description = 'Internet Services';
2045 if ( $conf->exists('business-onlinepayment-description') ) {
2046 my $dtempl = $conf->config('business-onlinepayment-description');
2048 my $agent_obj = $cust_main->agent
2049 or die "can't retreive agent for $cust_main (agentnum ".
2050 $cust_main->agentnum. ")";
2051 my $agent = $agent_obj->agent;
2052 my $pkgs = join(', ',
2053 map { $_->part_pkg->pkg }
2054 grep { $_->pkgnum } $self->cust_bill_pkg
2056 $description = eval qq("$dtempl");
2059 $cust_main->realtime_bop($method, $amount,
2060 'description' => $description,
2061 'invnum' => $self->invnum,
2062 #this didn't do what we want, it just calls apply_payments_and_credits
2064 'apply_to_invoice' => 1,
2067 #this changes application behavior: auto payments
2068 #triggered against a specific invoice are now applied
2069 #to that invoice instead of oldest open.
2075 =item batch_card OPTION => VALUE...
2077 Adds a payment for this invoice to the pending credit card batch (see
2078 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2079 runs the payment using a realtime gateway.
2084 my ($self, %options) = @_;
2085 my $cust_main = $self->cust_main;
2087 $options{invnum} = $self->invnum;
2089 $cust_main->batch_card(%options);
2092 sub _agent_template {
2094 $self->cust_main->agent_template;
2097 sub _agent_invoice_from {
2099 $self->cust_main->agent_invoice_from;
2102 =item invoice_barcode DIR_OR_FALSE
2104 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2105 it is taken as the temp directory where the PNG file will be generated and the
2106 PNG file name is returned. Otherwise, the PNG image itself is returned.
2110 sub invoice_barcode {
2111 my ($self, $dir) = (shift,shift);
2113 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2114 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2115 my $gd = $gdbar->plot(Height => 30);
2118 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2122 ) or die "can't open temp file: $!\n";
2123 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2124 my $png_file = $bh->filename;
2131 =item invnum_date_pretty
2133 Returns a string with the invoice number and date, for example:
2134 "Invoice #54 (3/20/2008)".
2136 Intended for back-end context, with regard to translation and date formatting.
2140 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2141 # for backend use (and also does the wrong thing, localizing for end customer
2142 # instead of backoffice configured date format)
2143 sub invnum_date_pretty {
2145 #$self->mt('Invoice #').
2146 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2147 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2150 #sub _items_extra_usage_sections {
2152 # my $escape = shift;
2154 # my %sections = ();
2156 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2157 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2159 # next unless $cust_bill_pkg->pkgnum > 0;
2161 # foreach my $section ( keys %usage_class ) {
2163 # my $usage = $cust_bill_pkg->usage($section);
2165 # next unless $usage && $usage > 0;
2167 # $sections{$section} ||= 0;
2168 # $sections{$section} += $usage;
2174 # map { { 'description' => &{$escape}($_),
2175 # 'subtotal' => $sections{$_},
2176 # 'summarized' => '',
2177 # 'tax_section' => '',
2180 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2184 sub _items_extra_usage_sections {
2186 my $conf = $self->conf;
2194 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2196 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2197 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2198 next unless $cust_bill_pkg->pkgnum > 0;
2200 foreach my $classnum ( keys %usage_class ) {
2201 my $section = $usage_class{$classnum}->classname;
2202 $classnums{$section} = $classnum;
2204 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2205 my $amount = $detail->amount;
2206 next unless $amount && $amount > 0;
2208 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2209 $sections{$section}{amount} += $amount; #subtotal
2210 $sections{$section}{calls}++;
2211 $sections{$section}{duration} += $detail->duration;
2213 my $desc = $detail->regionname;
2214 my $description = $desc;
2215 $description = substr($desc, 0, $maxlength). '...'
2216 if $format eq 'latex' && length($desc) > $maxlength;
2218 $lines{$section}{$desc} ||= {
2219 description => &{$escape}($description),
2220 #pkgpart => $part_pkg->pkgpart,
2221 pkgnum => $cust_bill_pkg->pkgnum,
2226 #unit_amount => $cust_bill_pkg->unitrecur,
2227 quantity => $cust_bill_pkg->quantity,
2228 product_code => 'N/A',
2229 ext_description => [],
2232 $lines{$section}{$desc}{amount} += $amount;
2233 $lines{$section}{$desc}{calls}++;
2234 $lines{$section}{$desc}{duration} += $detail->duration;
2240 my %sectionmap = ();
2241 foreach (keys %sections) {
2242 my $usage_class = $usage_class{$classnums{$_}};
2243 $sectionmap{$_} = { 'description' => &{$escape}($_),
2244 'amount' => $sections{$_}{amount}, #subtotal
2245 'calls' => $sections{$_}{calls},
2246 'duration' => $sections{$_}{duration},
2248 'tax_section' => '',
2249 'sort_weight' => $usage_class->weight,
2250 ( $usage_class->format
2251 ? ( map { $_ => $usage_class->$_($format) }
2252 qw( description_generator header_generator total_generator total_line_generator )
2259 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2263 foreach my $section ( keys %lines ) {
2264 foreach my $line ( keys %{$lines{$section}} ) {
2265 my $l = $lines{$section}{$line};
2266 $l->{section} = $sectionmap{$section};
2267 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2268 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2273 return(\@sections, \@lines);
2279 my $end = $self->_date;
2281 # start at date of previous invoice + 1 second or 0 if no previous invoice
2282 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2283 $start = 0 if !$start;
2286 my $cust_main = $self->cust_main;
2287 my @pkgs = $cust_main->all_pkgs;
2288 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2291 foreach my $pkg ( @pkgs ) {
2292 my @h_cust_svc = $pkg->h_cust_svc($end);
2293 foreach my $h_cust_svc ( @h_cust_svc ) {
2294 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2295 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2297 my $inserted = $h_cust_svc->date_inserted;
2298 my $deleted = $h_cust_svc->date_deleted;
2299 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2301 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2303 # DID either activated or ported in; cannot be both for same DID simultaneously
2304 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2305 && (!$phone_inserted->lnp_status
2306 || $phone_inserted->lnp_status eq ''
2307 || $phone_inserted->lnp_status eq 'native')) {
2310 else { # this one not so clean, should probably move to (h_)svc_phone
2311 local($FS::Record::qsearch_qualify_columns) = 0;
2312 my $phone_portedin = qsearchs( 'h_svc_phone',
2313 { 'svcnum' => $h_cust_svc->svcnum,
2314 'lnp_status' => 'portedin' },
2315 FS::h_svc_phone->sql_h_searchs($end),
2317 $num_portedin++ if $phone_portedin;
2320 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2321 if($deleted >= $start && $deleted <= $end && $phone_deleted
2322 && (!$phone_deleted->lnp_status
2323 || $phone_deleted->lnp_status ne 'portingout')) {
2326 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2327 && $phone_deleted->lnp_status
2328 && $phone_deleted->lnp_status eq 'portingout') {
2332 # increment usage minutes
2333 if ( $phone_inserted ) {
2334 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2335 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2338 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2341 # don't look at this service again
2342 push @seen, $h_cust_svc->svcnum;
2346 $minutes = sprintf("%d", $minutes);
2347 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2348 . "$num_deactivated Ported-Out: $num_portedout ",
2349 "Total Minutes: $minutes");
2352 sub _items_accountcode_cdr {
2357 my $section = { 'amount' => 0,
2360 'sort_weight' => '',
2362 'description' => 'Usage by Account Code',
2368 my %accountcodes = ();
2370 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2371 next unless $cust_bill_pkg->pkgnum > 0;
2373 my @header = $cust_bill_pkg->details_header;
2374 next unless scalar(@header);
2375 $section->{'header'} = join(',',@header);
2377 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2379 $section->{'header'} = $detail->formatted('format' => $format)
2380 if($detail->detail eq $section->{'header'});
2382 my $accountcode = $detail->accountcode;
2383 next unless $accountcode;
2385 my $amount = $detail->amount;
2386 next unless $amount && $amount > 0;
2388 $accountcodes{$accountcode} ||= {
2389 description => $accountcode,
2396 product_code => 'N/A',
2397 section => $section,
2398 ext_description => [ $section->{'header'} ],
2402 $section->{'amount'} += $amount;
2403 $accountcodes{$accountcode}{'amount'} += $amount;
2404 $accountcodes{$accountcode}{calls}++;
2405 $accountcodes{$accountcode}{duration} += $detail->duration;
2406 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2410 foreach my $l ( values %accountcodes ) {
2411 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2412 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2413 foreach my $sorted_detail ( @sorted_detail ) {
2414 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2416 delete $l->{detail_temp};
2420 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2422 return ($section,\@sorted_lines);
2425 sub _items_svc_phone_sections {
2427 my $conf = $self->conf;
2435 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2437 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2438 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2440 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2441 next unless $cust_bill_pkg->pkgnum > 0;
2443 my @header = $cust_bill_pkg->details_header;
2444 next unless scalar(@header);
2446 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2448 my $phonenum = $detail->phonenum;
2449 next unless $phonenum;
2451 my $amount = $detail->amount;
2452 next unless $amount && $amount > 0;
2454 $sections{$phonenum} ||= { 'amount' => 0,
2457 'sort_weight' => -1,
2458 'phonenum' => $phonenum,
2460 $sections{$phonenum}{amount} += $amount; #subtotal
2461 $sections{$phonenum}{calls}++;
2462 $sections{$phonenum}{duration} += $detail->duration;
2464 my $desc = $detail->regionname;
2465 my $description = $desc;
2466 $description = substr($desc, 0, $maxlength). '...'
2467 if $format eq 'latex' && length($desc) > $maxlength;
2469 $lines{$phonenum}{$desc} ||= {
2470 description => &{$escape}($description),
2471 #pkgpart => $part_pkg->pkgpart,
2479 product_code => 'N/A',
2480 ext_description => [],
2483 $lines{$phonenum}{$desc}{amount} += $amount;
2484 $lines{$phonenum}{$desc}{calls}++;
2485 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2487 my $line = $usage_class{$detail->classnum}->classname;
2488 $sections{"$phonenum $line"} ||=
2492 'sort_weight' => $usage_class{$detail->classnum}->weight,
2493 'phonenum' => $phonenum,
2494 'header' => [ @header ],
2496 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2497 $sections{"$phonenum $line"}{calls}++;
2498 $sections{"$phonenum $line"}{duration} += $detail->duration;
2500 $lines{"$phonenum $line"}{$desc} ||= {
2501 description => &{$escape}($description),
2502 #pkgpart => $part_pkg->pkgpart,
2510 product_code => 'N/A',
2511 ext_description => [],
2514 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2515 $lines{"$phonenum $line"}{$desc}{calls}++;
2516 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2517 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2518 $detail->formatted('format' => $format);
2523 my %sectionmap = ();
2524 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2525 foreach ( keys %sections ) {
2526 my @header = @{ $sections{$_}{header} || [] };
2528 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2529 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2530 my $usage_class = $summary ? $simple : $usage_simple;
2531 my $ending = $summary ? ' usage charges' : '';
2534 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2536 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2537 'amount' => $sections{$_}{amount}, #subtotal
2538 'calls' => $sections{$_}{calls},
2539 'duration' => $sections{$_}{duration},
2541 'tax_section' => '',
2542 'phonenum' => $sections{$_}{phonenum},
2543 'sort_weight' => $sections{$_}{sort_weight},
2544 'post_total' => $summary, #inspire pagebreak
2546 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2547 qw( description_generator
2550 total_line_generator
2557 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2558 $a->{sort_weight} <=> $b->{sort_weight}
2563 foreach my $section ( keys %lines ) {
2564 foreach my $line ( keys %{$lines{$section}} ) {
2565 my $l = $lines{$section}{$line};
2566 $l->{section} = $sectionmap{$section};
2567 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2568 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2573 if($conf->exists('phone_usage_class_summary')) {
2574 # this only works with Latex
2578 # after this, we'll have only two sections per DID:
2579 # Calls Summary and Calls Detail
2580 foreach my $section ( @sections ) {
2581 if($section->{'post_total'}) {
2582 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2583 $section->{'total_line_generator'} = sub { '' };
2584 $section->{'total_generator'} = sub { '' };
2585 $section->{'header_generator'} = sub { '' };
2586 $section->{'description_generator'} = '';
2587 push @newsections, $section;
2588 my %calls_detail = %$section;
2589 $calls_detail{'post_total'} = '';
2590 $calls_detail{'sort_weight'} = '';
2591 $calls_detail{'description_generator'} = sub { '' };
2592 $calls_detail{'header_generator'} = sub {
2593 return ' & Date/Time & Called Number & Duration & Price'
2594 if $format eq 'latex';
2597 $calls_detail{'description'} = 'Calls Detail: '
2598 . $section->{'phonenum'};
2599 push @newsections, \%calls_detail;
2603 # after this, each usage class is collapsed/summarized into a single
2604 # line under the Calls Summary section
2605 foreach my $newsection ( @newsections ) {
2606 if($newsection->{'post_total'}) { # this means Calls Summary
2607 foreach my $section ( @sections ) {
2608 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2609 && !$section->{'post_total'});
2610 my $newdesc = $section->{'description'};
2611 my $tn = $section->{'phonenum'};
2612 $newdesc =~ s/$tn//g;
2613 my $line = { ext_description => [],
2617 calls => $section->{'calls'},
2618 section => $newsection,
2619 duration => $section->{'duration'},
2620 description => $newdesc,
2621 amount => sprintf("%.2f",$section->{'amount'}),
2622 product_code => 'N/A',
2624 push @newlines, $line;
2629 # after this, Calls Details is populated with all CDRs
2630 foreach my $newsection ( @newsections ) {
2631 if(!$newsection->{'post_total'}) { # this means Calls Details
2632 foreach my $line ( @lines ) {
2633 next unless (scalar(@{$line->{'ext_description'}}) &&
2634 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2636 my @extdesc = @{$line->{'ext_description'}};
2638 foreach my $extdesc ( @extdesc ) {
2639 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2640 push @newextdesc, $extdesc;
2642 $line->{'ext_description'} = \@newextdesc;
2643 $line->{'section'} = $newsection;
2644 push @newlines, $line;
2649 return(\@newsections, \@newlines);
2652 return(\@sections, \@lines);
2656 =sub _items_usage_class_summary OPTIONS
2658 Returns a list of detail items summarizing the usage charges on this
2659 invoice. Each one will have 'amount', 'description' (the usage charge name),
2660 and 'usage_classnum'.
2662 OPTIONS can include 'escape' (a function to escape the descriptions).
2666 sub _items_usage_class_summary {
2670 my $escape = $opt{escape} || sub { $_[0] };
2671 my $money_char = $opt{money_char};
2672 my $invnum = $self->invnum;
2673 my @classes = qsearch({
2674 'table' => 'usage_class',
2675 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2676 ' COUNT(*) AS calls, SUM(duration) AS duration',
2677 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2678 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2679 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2680 ' GROUP BY classnum, classname, weight'.
2681 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2682 ' ORDER BY weight ASC',
2686 description => &{$escape}($self->mt('Usage Summary')),
2690 foreach my $class (@classes) {
2691 $section->{subtotal} += $class->get('amount');
2693 'description' => &{$escape}($class->classname),
2694 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2695 'quantity' => $class->get('calls'),
2696 'duration' => $class->get('duration'),
2697 'usage_classnum' => $class->classnum,
2698 'section' => $section,
2701 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2705 sub _items_previous {
2707 my $conf = $self->conf;
2708 my $cust_main = $self->cust_main;
2709 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2711 foreach ( @pr_cust_bill ) {
2712 my $date = $conf->exists('invoice_show_prior_due_date')
2713 ? 'due '. $_->due_date2str('short')
2714 : $self->time2str_local('short', $_->_date);
2716 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2717 #'pkgpart' => 'N/A',
2719 'amount' => sprintf("%.2f", $_->owed),
2725 # 'description' => 'Previous Balance',
2726 # #'pkgpart' => 'N/A',
2727 # 'pkgnum' => 'N/A',
2728 # 'amount' => sprintf("%10.2f", $pr_total ),
2729 # 'ext_description' => [ map {
2730 # "Invoice ". $_->invnum.
2731 # " (". time2str("%x",$_->_date). ") ".
2732 # sprintf("%10.2f", $_->owed)
2733 # } @pr_cust_bill ],
2738 sub _items_credits {
2739 my( $self, %opt ) = @_;
2740 my $trim_len = $opt{'trim_len'} || 40;
2745 if ( $self->conf->exists('previous_balance-payments_since') ) {
2746 if ( $opt{'template'} eq 'statement' ) {
2747 # then the current bill is a "statement" (i.e. an invoice sent as
2748 # a payment receipt)
2749 # and in that case we want to see payments on or after THIS invoice
2750 @objects = qsearch('cust_credit', {
2751 'custnum' => $self->custnum,
2752 '_date' => {op => '>=', value => $self->_date},
2756 $date = $self->previous_bill->_date if $self->previous_bill;
2757 @objects = qsearch('cust_credit', {
2758 'custnum' => $self->custnum,
2759 '_date' => {op => '>=', value => $date},
2763 @objects = $self->cust_credited;
2766 foreach my $obj ( @objects ) {
2767 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2769 my $reason = substr($cust_credit->reason, 0, $trim_len);
2770 $reason .= '...' if length($reason) < length($cust_credit->reason);
2771 $reason = " ($reason) " if $reason;
2774 #'description' => 'Credit ref\#'. $_->crednum.
2775 # " (". time2str("%x",$_->cust_credit->_date) .")".
2777 'description' => $self->mt('Credit applied').' '.
2778 $self->time2str_local('short', $obj->_date). $reason,
2779 'amount' => sprintf("%.2f",$obj->amount),
2787 sub _items_payments {
2792 my $detailed = $self->conf->exists('invoice_payment_details');
2794 if ( $self->conf->exists('previous_balance-payments_since') ) {
2795 # then show payments dated on/after the previous bill...
2796 if ( $opt{'template'} eq 'statement' ) {
2797 # then the current bill is a "statement" (i.e. an invoice sent as
2798 # a payment receipt)
2799 # and in that case we want to see payments on or after THIS invoice
2800 @objects = qsearch('cust_pay', {
2801 'custnum' => $self->custnum,
2802 '_date' => {op => '>=', value => $self->_date},
2805 # the normal case: payments on or after the previous invoice
2807 $date = $self->previous_bill->_date if $self->previous_bill;
2808 @objects = qsearch('cust_pay', {
2809 'custnum' => $self->custnum,
2810 '_date' => {op => '>=', value => $date},
2812 # and before the current bill...
2813 @objects = grep { $_->_date < $self->_date } @objects;
2816 @objects = $self->cust_bill_pay;
2819 foreach my $obj (@objects) {
2820 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2821 my $desc = $self->mt('Payment received').' '.
2822 $self->time2str_local('short', $cust_pay->_date );
2823 $desc .= $self->mt(' via ') .
2824 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2828 'description' => $desc,
2829 'amount' => sprintf("%.2f", $obj->amount )
2839 my $conf = $self->conf;
2842 my ($pr_total) = $self->previous;
2843 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2845 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2846 # if enabled, specifically add a line for the previous balance total
2847 $previous_charges_desc = $self->mt(
2848 $conf->config('previous_balance-text') || 'Previous Balance'
2851 # then return separate lines for previous balance and total new charges
2854 { total_item => $previous_charges_desc,
2855 total_amount => sprintf('%.2f',$pr_total)
2860 if ( $conf->exists('previous_balance-exclude_from_total')
2861 or !$self->enable_previous ) {
2862 # show new charges only
2864 $new_charges_desc = $self->mt(
2865 $conf->config('previous_balance-text-total_new_charges')
2866 || 'Total New Charges'
2869 $new_charges_amount = $self->charged;
2872 # show new charges + previous invoice total
2874 $new_charges_desc = $self->mt('Total Charges');
2875 if ( $self->enable_previous ) {
2876 $new_charges_amount = sprintf('%.2f', $self->charged + $pr_total);
2878 $new_charges_amount = sprintf('%.2f', $self->charged);
2883 if ( $conf->exists('invoice_show_prior_due_date') ) {
2884 # then the due date should be shown with Total New Charges,
2885 # and should NOT be shown with the Balance Due message.
2886 if ( $self->due_date ) {
2887 # localize the "Please pay by" message and the date itself
2888 # (grammar issues with this, yeah)
2889 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2890 $self->due_date2str('short');
2891 } elsif ( $self->terms ) {
2892 # phrases like "due on receipt" should be localized
2893 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2898 { total_item => $new_charges_desc,
2899 total_amount => $new_charges_amount,
2907 =item call_details [ OPTION => VALUE ... ]
2909 Returns an array of CSV strings representing the call details for this invoice
2910 The only option available is the boolean prepend_billed_number
2915 my ($self, %opt) = @_;
2917 my $format_function = sub { shift };
2919 if ($opt{prepend_billed_number}) {
2920 $format_function = sub {
2924 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2929 my @details = map { $_->details( 'format_function' => $format_function,
2930 'escape_function' => sub{ return() },
2934 $self->cust_bill_pkg;
2935 my $header = $details[0];
2936 ( $header, grep { $_ ne $header } @details );
2939 =item cust_pay_batch
2941 Returns all L<FS::cust_pay_batch> records linked to this invoice. Deprecated,
2946 sub cust_pay_batch {
2947 carp "FS::cust_bill->cust_pay_batch is deprecated";
2949 qsearch('cust_pay_batch', { 'invnum' => $self->invnum });
2958 =item process_reprint
2962 sub process_reprint {
2963 process_re_X('print', @_);
2966 =item process_reemail
2970 sub process_reemail {
2971 process_re_X('email', @_);
2979 process_re_X('fax', @_);
2987 process_re_X('ftp', @_);
2994 sub process_respool {
2995 process_re_X('spool', @_);
3000 my( $method, $job ) = ( shift, shift );
3001 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3004 warn Dumper($param) if $DEBUG;
3014 # this is called from search/cust_bill.html and given all its search
3015 # parameters, so it needs to perform the same search.
3018 # spool_invoice ftp_invoice fax_invoice print_invoice
3019 my($method, $job, %param ) = @_;
3021 warn "re_X $method for job $job with param:\n".
3022 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3025 #some false laziness w/search/cust_bill.html
3026 $param{'order_by'} = 'cust_bill._date';
3028 my $query = FS::cust_bill->search(\%param);
3029 delete $query->{'count_query'};
3030 delete $query->{'count_addl'};
3032 $query->{debug} = 1; # was in here before, is obviously useful
3034 my @cust_bill = qsearch( $query );
3036 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3038 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3041 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3042 foreach my $cust_bill ( @cust_bill ) {
3043 $cust_bill->$method();
3045 if ( $job ) { #progressbar foo
3047 if ( time - $min_sec > $last ) {
3048 my $error = $job->update_statustext(
3049 int( 100 * $num / scalar(@cust_bill) )
3051 die $error if $error;
3062 +{ ( map { $_=>$self->$_ } $self->fields ),
3063 'owed' => $self->owed,
3064 #XXX last payment applied date
3070 =head1 CLASS METHODS
3076 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3081 my ($class, $start, $end) = @_;
3083 $class->paid_sql($start, $end). ' - '.
3084 $class->credited_sql($start, $end);
3089 Returns an SQL fragment to retreive the net amount (charged minus credited).
3094 my ($class, $start, $end) = @_;
3095 'charged - '. $class->credited_sql($start, $end);
3100 Returns an SQL fragment to retreive the amount paid against this invoice.
3105 my ($class, $start, $end) = @_;
3106 $start &&= "AND cust_bill_pay._date <= $start";
3107 $end &&= "AND cust_bill_pay._date > $end";
3108 $start = '' unless defined($start);
3109 $end = '' unless defined($end);
3110 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3111 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3116 Returns an SQL fragment to retreive the amount credited against this invoice.
3121 my ($class, $start, $end) = @_;
3122 $start &&= "AND cust_credit_bill._date <= $start";
3123 $end &&= "AND cust_credit_bill._date > $end";
3124 $start = '' unless defined($start);
3125 $end = '' unless defined($end);
3126 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3127 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3132 Returns an SQL fragment to retrieve the due date of an invoice.
3133 Currently only supported on PostgreSQL.
3138 die "don't use: doesn't account for agent-specific invoice_default_terms";
3140 #we're passed a $conf but not a specific customer (that's in the query), so
3141 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3142 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3145 my $conf = new FS::Conf;
3149 cust_bill.invoice_terms,
3150 cust_main.invoice_terms,
3151 \''.($conf->config('invoice_default_terms') || '').'\'
3152 ), E\'Net (\\\\d+)\'
3154 ) * 86400 + cust_bill._date'
3165 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3166 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base