2 use base qw( FS::cust_bill::Search FS::Template_Mixin
3 FS::cust_main_Mixin FS::Record
7 use vars qw( $DEBUG $me );
9 use Fcntl qw(:flock); #for spool_csv
11 use List::Util qw(min max sum);
15 use Storable qw( freeze thaw );
17 use FS::UID qw( datasrc );
18 use FS::Misc qw( send_fax do_print );
19 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;
30 use FS::cust_pay_batch;
31 use FS::cust_bill_event;
34 use FS::cust_bill_pay;
35 use FS::cust_bill_pay_batch;
36 use FS::part_bill_event;
39 use FS::cust_bill_batch;
40 use FS::cust_bill_pay_pkg;
41 use FS::cust_credit_bill_pkg;
42 use FS::discount_plan;
43 use FS::cust_bill_void;
47 $me = '[FS::cust_bill]';
51 FS::cust_bill - Object methods for cust_bill records
57 $record = new FS::cust_bill \%hash;
58 $record = new FS::cust_bill { 'column' => 'value' };
60 $error = $record->insert;
62 $error = $new_record->replace($old_record);
64 $error = $record->delete;
66 $error = $record->check;
68 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
70 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
72 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
74 @cust_pay_objects = $cust_bill->cust_pay;
76 $tax_amount = $record->tax;
78 @lines = $cust_bill->print_text;
79 @lines = $cust_bill->print_text('time' => $time);
83 An FS::cust_bill object represents an invoice; a declaration that a customer
84 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
85 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
86 following fields are currently supported:
92 =item invnum - primary key (assigned automatically for new invoices)
94 =item custnum - customer (see L<FS::cust_main>)
96 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
97 L<Time::Local> and L<Date::Parse> for conversion functions.
99 =item charged - amount of this invoice
101 =item invoice_terms - optional terms override for this specific invoice
109 =item billing_balance - the customer's balance immediately before generating
110 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
111 to determine the customer's balance at a specific time.
113 =item previous_balance - the customer's balance immediately after generating
114 the invoice before this one. DEPRECATED.
116 =item printed - formerly used to track the number of times an invoice had
117 been printed; no longer used.
125 =item closed - books closed flag, empty or `Y'
127 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
129 =item agent_invid - legacy invoice number
131 =item promised_date - customer promised payment date, for collection
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'; }
149 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
150 # (except email_subject and invnum_date_pretty)
153 $self->conf->config('notice_name') || 'Invoice'
156 sub cust_linked { $_[0]->cust_main_custnum; }
157 sub cust_unlinked_msg {
159 "WARNING: can't find cust_main.custnum ". $self->custnum.
160 ' (cust_bill.invnum '. $self->invnum. ')';
165 Adds this invoice to the database ("Posts" the invoice). If there is an error,
166 returns the error, otherwise returns false.
172 warn "$me insert called\n" if $DEBUG;
174 local $SIG{HUP} = 'IGNORE';
175 local $SIG{INT} = 'IGNORE';
176 local $SIG{QUIT} = 'IGNORE';
177 local $SIG{TERM} = 'IGNORE';
178 local $SIG{TSTP} = 'IGNORE';
179 local $SIG{PIPE} = 'IGNORE';
181 my $oldAutoCommit = $FS::UID::AutoCommit;
182 local $FS::UID::AutoCommit = 0;
185 my $error = $self->SUPER::insert;
187 $dbh->rollback if $oldAutoCommit;
191 if ( $self->get('cust_bill_pkg') ) {
192 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
193 $cust_bill_pkg->invnum($self->invnum);
194 my $error = $cust_bill_pkg->insert;
196 $dbh->rollback if $oldAutoCommit;
197 return "can't create invoice line item: $error";
202 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
209 Voids this invoice: deletes the invoice and adds a record of the voided invoice
210 to the FS::cust_bill_void table (and related tables starting from
211 FS::cust_bill_pkg_void).
217 my $reason = scalar(@_) ? shift : '';
219 local $SIG{HUP} = 'IGNORE';
220 local $SIG{INT} = 'IGNORE';
221 local $SIG{QUIT} = 'IGNORE';
222 local $SIG{TERM} = 'IGNORE';
223 local $SIG{TSTP} = 'IGNORE';
224 local $SIG{PIPE} = 'IGNORE';
226 my $oldAutoCommit = $FS::UID::AutoCommit;
227 local $FS::UID::AutoCommit = 0;
230 my $cust_bill_void = new FS::cust_bill_void ( {
231 map { $_ => $self->get($_) } $self->fields
233 $cust_bill_void->reason($reason);
234 my $error = $cust_bill_void->insert;
236 $dbh->rollback if $oldAutoCommit;
240 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
241 my $error = $cust_bill_pkg->void($reason);
243 $dbh->rollback if $oldAutoCommit;
248 $error = $self->delete;
250 $dbh->rollback if $oldAutoCommit;
254 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
262 This method now works but you probably shouldn't use it. Instead, apply a
263 credit against the invoice, or use the new void method.
265 Using this method to delete invoices outright is really, really bad. There
266 would be no record you ever posted this invoice, and there are no check to
267 make sure charged = 0 or that there are no associated cust_bill_pkg records.
269 Really, don't use it.
275 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
277 local $SIG{HUP} = 'IGNORE';
278 local $SIG{INT} = 'IGNORE';
279 local $SIG{QUIT} = 'IGNORE';
280 local $SIG{TERM} = 'IGNORE';
281 local $SIG{TSTP} = 'IGNORE';
282 local $SIG{PIPE} = 'IGNORE';
284 my $oldAutoCommit = $FS::UID::AutoCommit;
285 local $FS::UID::AutoCommit = 0;
288 foreach my $table (qw(
299 foreach my $linked ( $self->$table() ) {
300 my $error = $linked->delete;
302 $dbh->rollback if $oldAutoCommit;
309 my $error = $self->SUPER::delete(@_);
311 $dbh->rollback if $oldAutoCommit;
315 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
321 =item replace [ OLD_RECORD ]
323 You can, but probably shouldn't modify invoices...
325 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
326 supplied, replaces this record. If there is an error, returns the error,
327 otherwise returns false.
331 #replace can be inherited from Record.pm
333 # replace_check is now the preferred way to #implement replace data checks
334 # (so $object->replace() works without an argument)
337 my( $new, $old ) = ( shift, shift );
338 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
339 #return "Can't change _date!" unless $old->_date eq $new->_date;
340 return "Can't change _date" unless $old->_date == $new->_date;
341 return "Can't change charged" unless $old->charged == $new->charged
342 || $old->charged == 0
343 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
349 =item add_cc_surcharge
355 sub add_cc_surcharge {
356 my ($self, $pkgnum, $amount) = (shift, shift, shift);
359 my $cust_bill_pkg = new FS::cust_bill_pkg({
360 'invnum' => $self->invnum,
364 $error = $cust_bill_pkg->insert;
365 return $error if $error;
367 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
368 $self->charged($self->charged+$amount);
369 $error = $self->replace;
370 return $error if $error;
372 $self->apply_payments_and_credits;
378 Checks all fields to make sure this is a valid invoice. If there is an error,
379 returns the error, otherwise returns false. Called by the insert and replace
388 $self->ut_numbern('invnum')
389 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
390 || $self->ut_numbern('_date')
391 || $self->ut_money('charged')
392 || $self->ut_numbern('printed')
393 || $self->ut_enum('closed', [ '', 'Y' ])
394 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
395 || $self->ut_numbern('agent_invid') #varchar?
397 return $error if $error;
399 $self->_date(time) unless $self->_date;
401 $self->printed(0) if $self->printed eq '';
408 Returns the displayed invoice number for this invoice: agent_invid if
409 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
415 if ( $self->agent_invid
416 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
417 return $self->agent_invid;
419 return $self->invnum;
425 Returns the customer's last invoice before this one.
431 if ( !$self->get('previous_bill') ) {
432 $self->set('previous_bill', qsearchs({
433 'table' => 'cust_bill',
434 'hashref' => { 'custnum' => $self->custnum,
435 '_date' => { op=>'<', value=>$self->_date } },
436 'order_by' => 'ORDER BY _date DESC LIMIT 1',
439 $self->get('previous_bill');
444 Returns a list consisting of the total previous balance for this customer,
445 followed by the previous outstanding invoices (as FS::cust_bill objects also).
451 # simple memoize; we use this a lot
452 if (!$self->get('previous')) {
454 my @cust_bill = sort { $a->_date <=> $b->_date }
455 grep { $_->owed != 0 }
456 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
457 #'_date' => { op=>'<', value=>$self->_date },
458 'invnum' => { op=>'<', value=>$self->invnum },
461 foreach ( @cust_bill ) { $total += $_->owed; }
462 $self->set('previous', [$total, @cust_bill]);
464 return @{ $self->get('previous') };
467 =item enable_previous
469 Whether to show the 'Previous Charges' section when printing this invoice.
470 The negation of the 'disable_previous_balance' config setting.
474 sub enable_previous {
476 my $agentnum = $self->cust_main->agentnum;
477 !$self->conf->exists('disable_previous_balance', $agentnum);
482 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
489 { 'table' => 'cust_bill_pkg',
490 'hashref' => { 'invnum' => $self->invnum },
491 'order_by' => 'ORDER BY billpkgnum',
496 =item cust_bill_pkg_pkgnum PKGNUM
498 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
503 sub cust_bill_pkg_pkgnum {
504 my( $self, $pkgnum ) = @_;
506 { 'table' => 'cust_bill_pkg',
507 'hashref' => { 'invnum' => $self->invnum,
510 'order_by' => 'ORDER BY billpkgnum',
517 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
524 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
525 $self->cust_bill_pkg;
527 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
532 Returns true if any of the packages (or their definitions) corresponding to the
533 line items for this invoice have the no_auto flag set.
539 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
542 =item open_cust_bill_pkg
544 Returns the open line items for this invoice.
546 Note that cust_bill_pkg with both setup and recur fees are returned as two
547 separate line items, each with only one fee.
551 # modeled after cust_main::open_cust_bill
552 sub open_cust_bill_pkg {
555 # grep { $_->owed > 0 } $self->cust_bill_pkg
557 my %other = ( 'recur' => 'setup',
558 'setup' => 'recur', );
560 foreach my $field ( qw( recur setup )) {
561 push @open, map { $_->set( $other{$field}, 0 ); $_; }
562 grep { $_->owed($field) > 0 }
563 $self->cust_bill_pkg;
569 =item cust_bill_event
571 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
575 sub cust_bill_event {
577 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
580 =item num_cust_bill_event
582 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
586 sub num_cust_bill_event {
589 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
590 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
591 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
592 $sth->fetchrow_arrayref->[0];
597 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
601 #false laziness w/cust_pkg.pm
605 'table' => 'cust_event',
606 'addl_from' => 'JOIN part_event USING ( eventpart )',
607 'hashref' => { 'tablenum' => $self->invnum },
608 'extra_sql' => " AND eventtable = 'cust_bill' ",
614 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
618 #false laziness w/cust_pkg.pm
622 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
623 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
624 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
625 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
626 $sth->fetchrow_arrayref->[0];
631 Returns the customer (see L<FS::cust_main>) for this invoice.
637 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
640 =item cust_suspend_if_balance_over AMOUNT
642 Suspends the customer associated with this invoice if the total amount owed on
643 this invoice and all older invoices is greater than the specified amount.
645 Returns a list: an empty list on success or a list of errors.
649 sub cust_suspend_if_balance_over {
650 my( $self, $amount ) = ( shift, shift );
651 my $cust_main = $self->cust_main;
652 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
655 $cust_main->suspend(@_);
661 Depreciated. See the cust_credited method.
663 #Returns a list consisting of the total previous credited (see
664 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
665 #outstanding credits (FS::cust_credit objects).
671 croak "FS::cust_bill->cust_credit depreciated; see ".
672 "FS::cust_bill->cust_credit_bill";
675 #my @cust_credit = sort { $a->_date <=> $b->_date }
676 # grep { $_->credited != 0 && $_->_date < $self->_date }
677 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
679 #foreach (@cust_credit) { $total += $_->credited; }
680 #$total, @cust_credit;
685 Depreciated. See the cust_bill_pay method.
687 #Returns all payments (see L<FS::cust_pay>) for this invoice.
693 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
695 #sort { $a->_date <=> $b->_date }
696 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
702 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
705 sub cust_bill_pay_batch {
707 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
712 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
718 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
719 sort { $a->_date <=> $b->_date }
720 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
725 =item cust_credit_bill
727 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
733 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
734 sort { $a->_date <=> $b->_date }
735 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
739 sub cust_credit_bill {
740 shift->cust_credited(@_);
743 #=item cust_bill_pay_pkgnum PKGNUM
745 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
746 #with matching pkgnum.
750 #sub cust_bill_pay_pkgnum {
751 # my( $self, $pkgnum ) = @_;
752 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
753 # sort { $a->_date <=> $b->_date }
754 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
755 # 'pkgnum' => $pkgnum,
760 =item cust_bill_pay_pkg PKGNUM
762 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
763 applied against the matching pkgnum.
767 sub cust_bill_pay_pkg {
768 my( $self, $pkgnum ) = @_;
771 'select' => 'cust_bill_pay_pkg.*',
772 'table' => 'cust_bill_pay_pkg',
773 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
774 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
775 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
776 " AND cust_bill_pkg.pkgnum = $pkgnum",
781 #=item cust_credited_pkgnum PKGNUM
783 #=item cust_credit_bill_pkgnum PKGNUM
785 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
786 #with matching pkgnum.
790 #sub cust_credited_pkgnum {
791 # my( $self, $pkgnum ) = @_;
792 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
793 # sort { $a->_date <=> $b->_date }
794 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
795 # 'pkgnum' => $pkgnum,
800 #sub cust_credit_bill_pkgnum {
801 # shift->cust_credited_pkgnum(@_);
804 =item cust_credit_bill_pkg PKGNUM
806 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
807 applied against the matching pkgnum.
811 sub cust_credit_bill_pkg {
812 my( $self, $pkgnum ) = @_;
815 'select' => 'cust_credit_bill_pkg.*',
816 'table' => 'cust_credit_bill_pkg',
817 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
818 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
819 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
820 " AND cust_bill_pkg.pkgnum = $pkgnum",
825 =item cust_bill_batch
827 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
831 sub cust_bill_batch {
833 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
838 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
839 hash keyed by term length.
845 FS::discount_plan->all($self);
850 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
857 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
859 foreach (@taxlines) { $total += $_->setup; }
865 Returns the amount owed (still outstanding) on this invoice, which is charged
866 minus all payment applications (see L<FS::cust_bill_pay>) and credit
867 applications (see L<FS::cust_credit_bill>).
873 my $balance = $self->charged;
874 $balance -= $_->amount foreach ( $self->cust_bill_pay );
875 $balance -= $_->amount foreach ( $self->cust_credited );
876 $balance = sprintf( "%.2f", $balance);
877 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
882 my( $self, $pkgnum ) = @_;
884 #my $balance = $self->charged;
886 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
888 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
889 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
891 $balance = sprintf( "%.2f", $balance);
892 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
898 Returns true if this invoice should be hidden. See the
899 selfservice-hide_invoices-taxclass configuraiton setting.
905 my $conf = $self->conf;
906 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
908 my @cust_bill_pkg = $self->cust_bill_pkg;
909 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
910 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
913 =item apply_payments_and_credits [ OPTION => VALUE ... ]
915 Applies unapplied payments and credits to this invoice.
916 Payments with the no_auto_apply flag set will not be applied.
918 A hash of optional arguments may be passed. Currently "manual" is supported.
919 If true, a payment receipt is sent instead of a statement when
920 'payment_receipt_email' configuration option is set.
922 If there is an error, returns the error, otherwise returns false.
926 sub apply_payments_and_credits {
927 my( $self, %options ) = @_;
928 my $conf = $self->conf;
930 local $SIG{HUP} = 'IGNORE';
931 local $SIG{INT} = 'IGNORE';
932 local $SIG{QUIT} = 'IGNORE';
933 local $SIG{TERM} = 'IGNORE';
934 local $SIG{TSTP} = 'IGNORE';
935 local $SIG{PIPE} = 'IGNORE';
937 my $oldAutoCommit = $FS::UID::AutoCommit;
938 local $FS::UID::AutoCommit = 0;
941 $self->select_for_update; #mutex
943 my @payments = grep { $_->unapplied > 0 }
944 grep { !$_->no_auto_apply }
945 $self->cust_main->cust_pay;
946 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
948 if ( $conf->exists('pkg-balances') ) {
949 # limit @payments & @credits to those w/ a pkgnum grepped from $self
950 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
951 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
952 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
955 while ( $self->owed > 0 and ( @payments || @credits ) ) {
958 if ( @payments && @credits ) {
960 #decide which goes first by weight of top (unapplied) line item
962 my @open_lineitems = $self->open_cust_bill_pkg;
965 max( map { $_->part_pkg->pay_weight || 0 }
970 my $max_credit_weight =
971 max( map { $_->part_pkg->credit_weight || 0 }
977 #if both are the same... payments first? it has to be something
978 if ( $max_pay_weight >= $max_credit_weight ) {
984 } elsif ( @payments ) {
986 } elsif ( @credits ) {
989 die "guru meditation #12 and 35";
993 if ( $app eq 'pay' ) {
995 my $payment = shift @payments;
996 $unapp_amount = $payment->unapplied;
997 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
998 $app->pkgnum( $payment->pkgnum )
999 if $conf->exists('pkg-balances') && $payment->pkgnum;
1001 } elsif ( $app eq 'credit' ) {
1003 my $credit = shift @credits;
1004 $unapp_amount = $credit->credited;
1005 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1006 $app->pkgnum( $credit->pkgnum )
1007 if $conf->exists('pkg-balances') && $credit->pkgnum;
1010 die "guru meditation #12 and 35";
1014 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1015 warn "owed_pkgnum ". $app->pkgnum;
1016 $owed = $self->owed_pkgnum($app->pkgnum);
1018 $owed = $self->owed;
1020 next unless $owed > 0;
1022 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1023 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1025 $app->invnum( $self->invnum );
1027 my $error = $app->insert(%options);
1029 $dbh->rollback if $oldAutoCommit;
1030 return "Error inserting ". $app->table. " record: $error";
1032 die $error if $error;
1036 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1043 Sends this invoice to the destinations configured for this customer: sends
1044 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1046 Options can be passed as a hashref. Positional parameters are no longer
1049 I<template>: a suffix for alternate invoices
1051 I<agentnum>: obsolete, now does nothing.
1053 I<from> overrides the default email invoice From: address.
1055 I<amount>: obsolete, does nothing
1057 I<notice_name> overrides "Invoice" as the name of the sent document
1058 (templates from 10/2009 or newer required).
1060 I<lpr> overrides the system 'lpr' option as the command to print a document
1061 from standard input.
1067 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1068 my $conf = $self->conf;
1070 my $cust_main = $self->cust_main;
1072 my @invoicing_list = $cust_main->invoicing_list;
1075 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1076 && ! $cust_main->invoice_noemail;
1079 if grep { $_ eq 'POST' } @invoicing_list; #postal
1081 #this has never been used post-$ORIGINAL_ISP afaik
1082 $self->fax_invoice($opt)
1083 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1091 my $opt = shift || {};
1092 if ($opt and !ref($opt)) {
1093 die ref($self). '->email called with positional parameters';
1096 my $conf = $self->conf;
1098 my $from = delete $opt->{from};
1100 # this is where we set the From: address
1101 $from ||= $self->_agent_invoice_from || #XXX should go away
1102 $conf->invoice_from_full( $self->cust_main->agentnum );
1104 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1106 if ( ! @invoicing_list ) { #no recipients
1107 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1108 die 'No recipients for customer #'. $self->custnum;
1110 #default: better to notify this person than silence
1111 @invoicing_list = ($from);
1115 $self->SUPER::email( {
1117 'to' => \@invoicing_list,
1123 #this stays here for now because its explicitly used as
1124 # FS::cust_bill::queueable_email
1125 sub queueable_email {
1128 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1129 or die "invalid invoice number: " . $opt{invnum};
1132 $self->set('mode', $opt{mode});
1135 my %args = map {$_ => $opt{$_}}
1137 qw( from notice_name no_coupon template );
1139 my $error = $self->email( \%args );
1140 die $error if $error;
1146 my $conf = $self->conf;
1148 #my $template = scalar(@_) ? shift : '';
1151 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1154 my $cust_main = $self->cust_main;
1155 my $name = $cust_main->name;
1156 my $name_short = $cust_main->name_short;
1157 my $invoice_number = $self->invnum;
1158 my $invoice_date = $self->_date_pretty;
1160 eval qq("$subject");
1163 =item lpr_data HASHREF
1165 Returns the postscript or plaintext for this invoice as an arrayref.
1167 Options must be passed as a hashref. Positional parameters are no longer
1170 I<template>, if specified, is the name of a suffix for alternate invoices.
1172 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1178 my $conf = $self->conf;
1179 my $opt = shift || {};
1180 if ($opt and !ref($opt)) {
1181 # nobody does this anyway
1182 die "FS::cust_bill::lpr_data called with positional parameters";
1185 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1186 [ $self->$method( $opt ) ];
1191 Prints this invoice.
1193 Options must be passed as a hashref.
1195 I<template>, if specified, is the name of a suffix for alternate invoices.
1197 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1203 return if $self->hide;
1204 my $conf = $self->conf;
1205 my $opt = shift || {};
1206 if ($opt and !ref($opt)) {
1207 die "FS::cust_bill::print called with positional parameters";
1210 my $lpr = delete $opt->{lpr};
1211 if($conf->exists('invoice_print_pdf')) {
1212 # Add the invoice to the current batch.
1213 $self->batch_invoice($opt);
1217 $self->lpr_data($opt),
1218 'agentnum' => $self->cust_main->agentnum,
1224 =item fax_invoice HASHREF
1228 Options must be passed as a hashref.
1230 I<template>, if specified, is the name of a suffix for alternate invoices.
1232 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1238 return if $self->hide;
1239 my $conf = $self->conf;
1240 my $opt = shift || {};
1241 if ($opt and !ref($opt)) {
1242 die "FS::cust_bill::fax_invoice called with positional parameters";
1245 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1246 unless $conf->exists('invoice_latex');
1248 my $dialstring = $self->cust_main->getfield('fax');
1251 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1252 'dialstring' => $dialstring,
1254 die $error if $error;
1258 =item batch_invoice [ HASHREF ]
1260 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1261 isn't an open batch, one will be created.
1263 HASHREF may contain any options to be passed to C<print_pdf>.
1268 my ($self, $opt) = @_;
1269 my $bill_batch = $self->get_open_bill_batch;
1270 my $cust_bill_batch = FS::cust_bill_batch->new({
1271 batchnum => $bill_batch->batchnum,
1272 invnum => $self->invnum,
1274 return $cust_bill_batch->insert($opt);
1277 =item get_open_batch
1279 Returns the currently open batch as an FS::bill_batch object, creating a new
1280 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1285 sub get_open_bill_batch {
1287 my $conf = $self->conf;
1288 my $hashref = { status => 'O' };
1289 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1290 ? $self->cust_main->agentnum
1292 my $batch = qsearchs('bill_batch', $hashref);
1293 return $batch if $batch;
1294 $batch = FS::bill_batch->new($hashref);
1295 my $error = $batch->insert;
1296 die $error if $error;
1300 =item ftp_invoice [ TEMPLATENAME ]
1302 Sends this invoice data via FTP.
1304 TEMPLATENAME is unused?
1310 my $conf = $self->conf;
1311 my $template = scalar(@_) ? shift : '';
1314 'protocol' => 'ftp',
1315 'server' => $conf->config('cust_bill-ftpserver'),
1316 'username' => $conf->config('cust_bill-ftpusername'),
1317 'password' => $conf->config('cust_bill-ftppassword'),
1318 'dir' => $conf->config('cust_bill-ftpdir'),
1319 'format' => $conf->config('cust_bill-ftpformat'),
1323 =item spool_invoice [ TEMPLATENAME ]
1325 Spools this invoice data (see L<FS::spool_csv>)
1327 TEMPLATENAME is unused?
1333 my $conf = $self->conf;
1334 my $template = scalar(@_) ? shift : '';
1337 'format' => $conf->config('cust_bill-spoolformat'),
1338 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1342 =item send_csv OPTION => VALUE, ...
1344 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1348 protocol - currently only "ftp"
1354 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1355 and YYMMDDHHMMSS is a timestamp.
1357 See L</print_csv> for a description of the output format.
1362 my($self, %opt) = @_;
1366 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1367 mkdir $spooldir, 0700 unless -d $spooldir;
1369 # don't localize dates here, they're a defined format
1370 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1371 my $file = "$spooldir/$tracctnum.csv";
1373 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1375 open(CSV, ">$file") or die "can't open $file: $!";
1383 if ( $opt{protocol} eq 'ftp' ) {
1384 eval "use Net::FTP;";
1386 $net = Net::FTP->new($opt{server}) or die @$;
1388 die "unknown protocol: $opt{protocol}";
1391 $net->login( $opt{username}, $opt{password} )
1392 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1394 $net->binary or die "can't set binary mode";
1396 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1398 $net->put($file) or die "can't put $file: $!";
1408 Spools CSV invoice data.
1414 =item format - any of FS::Misc::::Invoicing::spool_formats
1416 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1417 customer has the corresponding invoice destinations set (see
1418 L<FS::cust_main_invoice>).
1420 =item agent_spools - if set to a true value, will spool to per-agent files
1421 rather than a single global file
1423 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1424 append to that spool. L<FS::Cron::upload> will then send the spool file to
1427 =item balanceover - if set, only spools the invoice if the total amount owed on
1428 this invoice and all older invoices is greater than the specified amount.
1430 =item time - the "current time". Controls the printing of past due messages
1438 my($self, %opt) = @_;
1440 my $time = $opt{'time'} || time;
1441 my $cust_main = $self->cust_main;
1443 if ( $opt{'dest'} ) {
1444 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1445 $cust_main->invoicing_list;
1446 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1447 || ! keys %invoicing_list;
1450 if ( $opt{'balanceover'} ) {
1452 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1455 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1456 mkdir $spooldir, 0700 unless -d $spooldir;
1458 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1461 if ( $opt{'agent_spools'} ) {
1462 $file = 'agentnum'.$cust_main->agentnum;
1467 if ( $opt{'upload_targetnum'} ) {
1468 $spooldir .= '/target'.$opt{'upload_targetnum'};
1469 mkdir $spooldir, 0700 unless -d $spooldir;
1470 } # otherwise it just goes into export.xxx/cust_bill
1472 if ( lc($opt{'format'}) eq 'billco' ) {
1476 $file = "$spooldir/$file.csv";
1478 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1480 open(CSV, ">>$file") or die "can't open $file: $!";
1481 flock(CSV, LOCK_EX);
1486 if ( lc($opt{'format'}) eq 'billco' ) {
1488 flock(CSV, LOCK_UN);
1491 $file =~ s/-header.csv$/-detail.csv/;
1493 open(CSV,">>$file") or die "can't open $file: $!";
1494 flock(CSV, LOCK_EX);
1498 print CSV $detail if defined($detail);
1500 flock(CSV, LOCK_UN);
1507 =item print_csv OPTION => VALUE, ...
1509 Returns CSV data for this invoice.
1513 format - 'default', 'billco', 'oneline', 'bridgestone'
1515 Returns a list consisting of two scalars. The first is a single line of CSV
1516 header information for this invoice. The second is one or more lines of CSV
1517 detail information for this invoice.
1519 If I<format> is not specified or "default", the fields of the CSV file are as
1522 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1523 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1527 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1529 B<record_type> is C<cust_bill> for the initial header line only. The
1530 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1531 fields are filled in.
1533 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1534 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1537 =item invnum - invoice number
1539 =item custnum - customer number
1541 =item _date - invoice date
1543 =item charged - total invoice amount
1545 =item first - customer first name
1547 =item last - customer first name
1549 =item company - company name
1551 =item address1 - address line 1
1553 =item address2 - address line 1
1563 =item pkg - line item description
1565 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1567 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1569 =item sdate - start date for recurring fee
1571 =item edate - end date for recurring fee
1575 If I<format> is "billco", the fields of the header CSV file are as follows:
1577 +-------------------------------------------------------------------+
1578 | FORMAT HEADER FILE |
1579 |-------------------------------------------------------------------|
1580 | Field | Description | Name | Type | Width |
1581 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1582 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1583 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1584 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1585 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1586 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1587 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1588 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1589 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1590 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1591 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1592 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1593 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1594 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1595 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1596 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1597 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1598 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1599 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1600 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1601 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1602 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1603 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1604 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1605 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1606 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1607 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1608 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1609 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1610 +-------+-------------------------------+------------+------+-------+
1612 If I<format> is "billco", the fields of the detail CSV file are as follows:
1614 FORMAT FOR DETAIL FILE
1616 Field | Description | Name | Type | Width
1617 1 | N/A-Leave Empty | RC | CHAR | 2
1618 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1619 3 | Account Number | TRACCTNUM | CHAR | 15
1620 4 | Invoice Number | TRINVOICE | CHAR | 15
1621 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1622 6 | Transaction Detail | DETAILS | CHAR | 100
1623 7 | Amount | AMT | NUM* | 9
1624 8 | Line Format Control** | LNCTRL | CHAR | 2
1625 9 | Grouping Code | GROUP | CHAR | 2
1626 10 | User Defined | ACCT CODE | CHAR | 15
1628 If format is 'oneline', there is no detail file. Each invoice has a
1629 header line only, with the fields:
1631 Agent number, agent name, customer number, first name, last name, address
1632 line 1, address line 2, city, state, zip, invoice date, invoice number,
1633 amount charged, amount due, previous balance, due date.
1635 and then, for each line item, three columns containing the package number,
1636 description, and amount.
1638 If format is 'bridgestone', there is no detail file. Each invoice has a
1639 header line with the following fields in a fixed-width format:
1641 Customer number (in display format), date, name (first last), company,
1642 address 1, address 2, city, state, zip.
1644 This is a mailing list format, and has no per-invoice fields. To avoid
1645 sending redundant notices, the spooling event should have a "once" or
1646 "once_percust_every" condition.
1651 my($self, %opt) = @_;
1653 eval "use Text::CSV_XS";
1656 my $cust_main = $self->cust_main;
1658 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1659 my $format = lc($opt{'format'});
1661 my $time = $opt{'time'} || time;
1663 my $tracctnum = ''; #leaking out from billco-specific sections :/
1664 if ( $format eq 'billco' ) {
1667 $self->conf->config('billco-account_num', $cust_main->agentnum);
1669 $tracctnum = $account_num eq 'display_custnum'
1670 ? $cust_main->display_custnum
1671 : $opt{'tracctnum'};
1674 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1676 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1678 my( $previous_balance, @unused ) = $self->previous; #previous balance
1680 my $pmt_cr_applied = 0;
1681 $pmt_cr_applied += $_->{'amount'}
1682 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1684 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1687 '', # 1 | N/A-Leave Empty CHAR 2
1688 '', # 2 | N/A-Leave Empty CHAR 15
1689 $tracctnum, # 3 | Transaction Account No CHAR 15
1690 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1691 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1692 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1693 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1694 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1695 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1696 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1697 '', # 10 | Ancillary Billing Information CHAR 30
1698 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1699 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1702 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1705 $duedate, # 14 | Bill Due Date CHAR 10
1707 $previous_balance, # 15 | Previous Balance NUM* 9
1708 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1709 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1710 $totaldue, # 18 | Total Amt Due NUM* 9
1711 $totaldue, # 19 | Total Amt Due NUM* 9
1712 '', # 20 | 30 Day Aging NUM* 9
1713 '', # 21 | 60 Day Aging NUM* 9
1714 '', # 22 | 90 Day Aging NUM* 9
1715 'N', # 23 | Y/N CHAR 1
1716 '', # 24 | Remittance automation CHAR 100
1717 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1718 $self->custnum, # 26 | Customer Reference Number CHAR 15
1719 '0', # 27 | Federal Tax*** NUM* 9
1720 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1721 '0', # 29 | Other Taxes & Fees*** NUM* 9
1724 } elsif ( $format eq 'oneline' ) { #name
1726 my ($previous_balance) = $self->previous;
1727 $previous_balance = sprintf('%.2f', $previous_balance);
1728 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1734 $self->_items_pkg, #_items_nontax? no sections or anything
1739 $cust_main->agentnum,
1740 $cust_main->agent->agent,
1744 $cust_main->company,
1745 $cust_main->address1,
1746 $cust_main->address2,
1752 time2str("%x", $self->_date),
1757 $self->due_date2str("%x"),
1762 } elsif ( $format eq 'bridgestone' ) {
1764 # bypass the CSV stuff and just return this
1765 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1766 my $zip = $cust_main->zip;
1768 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1772 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1774 $cust_main->display_custnum,
1776 uc(substr($cust_main->contact_firstlast,0,30)),
1777 uc(substr($cust_main->company ,0,30)),
1778 uc(substr($cust_main->address1 ,0,30)),
1779 uc(substr($cust_main->address2 ,0,30)),
1780 uc(substr($cust_main->city ,0,20)),
1781 uc($cust_main->state),
1787 } elsif ( $format eq 'ics' ) {
1789 my $bill = $cust_main->bill_location;
1790 my $zip = $bill->zip;
1794 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1799 # minor false laziness with print_generic
1800 my ($previous_balance) = $self->previous;
1801 my $balance_due = $self->owed + $previous_balance;
1802 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1803 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1806 if ( $self->due_date and $time >= $self->due_date ) {
1807 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1811 my $header = sprintf(
1812 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1813 $cust_main->display_custnum, #BID
1814 uc($cust_main->first), #FNAME
1815 uc($cust_main->last), #LNAME
1816 '00', #BATCH, should this ever be anything else?
1817 uc($cust_main->company), #COMP
1818 uc($bill->address1), #STREET1
1819 uc($bill->address2), #STREET2
1820 uc($bill->city), #CITY
1821 uc($bill->state), #STATE
1824 time2str('%Y%m%d', $self->_date), #BILL_DATE
1825 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1826 ( map {sprintf('%0.2f', $_)}
1827 $balance_due, #AMNT_DUE
1828 $previous_balance, #PREV_BAL
1829 $payment_total, #PYMT_RCVD
1830 $credit_total, #CREDITS
1831 $previous_balance, #BEG_BAL--is this correct?
1832 $self->charged, #NEW_CHRG
1835 $past_due, #PAST_MSG
1839 my %svc_class = ('' => ''); # maybe cache this more persistently?
1841 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1843 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1844 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1848 my @dates = ( $self->_date, undef );
1849 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1850 $dates[1] = $prev->sdate; #questionable
1853 # generate an 01 detail for each service
1854 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1855 foreach my $cust_svc ( @svcs ) {
1856 $show_pkgnum = ''; # hide it if we're showing svcnums
1858 my $svcpart = $cust_svc->svcpart;
1859 if (!exists($svc_class{$svcpart})) {
1860 my $classnum = $cust_svc->part_svc->classnum;
1861 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1863 $svc_class{$svcpart} = $part_svc_class ?
1864 $part_svc_class->classname :
1868 my @h_label = $cust_svc->label(@dates, 'I');
1869 push @details, sprintf('01%-9s%-20s%-47s',
1871 $svc_class{$svcpart},
1874 } #foreach $cust_svc
1877 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1878 if ($cust_bill_pkg->recur > 0) {
1879 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1880 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1882 push @details, sprintf('02%-6s%-60s%-10s',
1885 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1887 } #foreach $cust_bill_pkg
1889 # Tag this row so that we know whether this is one page (1), two pages
1890 # (2), # or "big" (B). The tag will be stripped off before uploading.
1891 if ( scalar(@details) < 12 ) {
1893 } elsif ( scalar(@details) < 58 ) {
1899 return join('', $header, @details, "\n");
1907 time2str("%x", $self->_date),
1908 sprintf("%.2f", $self->charged),
1909 ( map { $cust_main->getfield($_) }
1910 qw( first last company address1 address2 city state zip country ) ),
1912 ) or die "can't create csv";
1915 my $header = $csv->string. "\n";
1918 if ( lc($opt{'format'}) eq 'billco' ) {
1921 my %items_opt = ( format => 'template',
1922 escape_function => sub { shift } );
1923 # I don't know what characters billco actually tolerates in spool entries.
1924 # Text::CSV will take care of delimiters, though.
1926 my @items = ( $self->_items_pkg(%items_opt),
1927 $self->_items_fee(%items_opt) );
1928 foreach my $item (@items) {
1930 my $description = $item->{'description'};
1931 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1932 $description .= ': ' . $item->{ext_description}[0];
1936 '', # 1 | N/A-Leave Empty CHAR 2
1937 '', # 2 | N/A-Leave Empty CHAR 15
1938 $tracctnum, # 3 | Account Number CHAR 15
1939 $self->invnum, # 4 | Invoice Number CHAR 15
1940 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1941 $description, # 6 | Transaction Detail CHAR 100
1942 $item->{'amount'}, # 7 | Amount NUM* 9
1943 '', # 8 | Line Format Control** CHAR 2
1944 '', # 9 | Grouping Code CHAR 2
1945 '', # 10 | User Defined CHAR 15
1948 $detail .= $csv->string. "\n";
1952 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1958 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1960 my($pkg, $setup, $recur, $sdate, $edate);
1961 if ( $cust_bill_pkg->pkgnum ) {
1963 ($pkg, $setup, $recur, $sdate, $edate) = (
1964 $cust_bill_pkg->part_pkg->pkg,
1965 ( $cust_bill_pkg->setup != 0
1966 ? sprintf("%.2f", $cust_bill_pkg->setup )
1968 ( $cust_bill_pkg->recur != 0
1969 ? sprintf("%.2f", $cust_bill_pkg->recur )
1971 ( $cust_bill_pkg->sdate
1972 ? time2str("%x", $cust_bill_pkg->sdate)
1974 ($cust_bill_pkg->edate
1975 ? time2str("%x", $cust_bill_pkg->edate)
1979 } else { #pkgnum tax
1980 next unless $cust_bill_pkg->setup != 0;
1981 $pkg = $cust_bill_pkg->desc;
1982 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1983 ( $sdate, $edate ) = ( '', '' );
1989 ( map { '' } (1..11) ),
1990 ($pkg, $setup, $recur, $sdate, $edate)
1991 ) or die "can't create csv";
1993 $detail .= $csv->string. "\n";
1999 ( $header, $detail );
2005 Pays this invoice with a compliemntary payment. If there is an error,
2006 returns the error, otherwise returns false.
2012 my $cust_pay = new FS::cust_pay ( {
2013 'invnum' => $self->invnum,
2014 'paid' => $self->owed,
2017 'payinfo' => $self->cust_main->payinfo,
2025 Attempts to pay this invoice with a credit card payment via a
2026 Business::OnlinePayment realtime gateway. See
2027 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2028 for supported processors.
2034 $self->realtime_bop( 'CC', @_ );
2039 Attempts to pay this invoice with an electronic check (ACH) payment via a
2040 Business::OnlinePayment realtime gateway. See
2041 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2042 for supported processors.
2048 $self->realtime_bop( 'ECHECK', @_ );
2053 Attempts to pay this invoice with phone bill (LEC) payment via a
2054 Business::OnlinePayment realtime gateway. See
2055 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2056 for supported processors.
2062 $self->realtime_bop( 'LEC', @_ );
2066 my( $self, $method ) = (shift,shift);
2067 my $conf = $self->conf;
2070 my $cust_main = $self->cust_main;
2071 my $balance = $cust_main->balance;
2072 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2073 $amount = sprintf("%.2f", $amount);
2074 return "not run (balance $balance)" unless $amount > 0;
2076 my $description = 'Internet Services';
2077 if ( $conf->exists('business-onlinepayment-description') ) {
2078 my $dtempl = $conf->config('business-onlinepayment-description');
2080 my $agent_obj = $cust_main->agent
2081 or die "can't retreive agent for $cust_main (agentnum ".
2082 $cust_main->agentnum. ")";
2083 my $agent = $agent_obj->agent;
2084 my $pkgs = join(', ',
2085 map { $_->part_pkg->pkg }
2086 grep { $_->pkgnum } $self->cust_bill_pkg
2088 $description = eval qq("$dtempl");
2091 $cust_main->realtime_bop($method, $amount,
2092 'description' => $description,
2093 'invnum' => $self->invnum,
2094 #this didn't do what we want, it just calls apply_payments_and_credits
2096 'apply_to_invoice' => 1,
2099 #this changes application behavior: auto payments
2100 #triggered against a specific invoice are now applied
2101 #to that invoice instead of oldest open.
2107 =item batch_card OPTION => VALUE...
2109 Adds a payment for this invoice to the pending credit card batch (see
2110 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2111 runs the payment using a realtime gateway.
2116 my ($self, %options) = @_;
2117 my $cust_main = $self->cust_main;
2119 $options{invnum} = $self->invnum;
2121 $cust_main->batch_card(%options);
2124 sub _agent_template {
2126 $self->cust_main->agent_template;
2129 sub _agent_invoice_from {
2131 $self->cust_main->agent_invoice_from;
2134 =item invoice_barcode DIR_OR_FALSE
2136 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2137 it is taken as the temp directory where the PNG file will be generated and the
2138 PNG file name is returned. Otherwise, the PNG image itself is returned.
2142 sub invoice_barcode {
2143 my ($self, $dir) = (shift,shift);
2145 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2146 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2147 my $gd = $gdbar->plot(Height => 30);
2150 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2154 ) or die "can't open temp file: $!\n";
2155 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2156 my $png_file = $bh->filename;
2163 =item invnum_date_pretty
2165 Returns a string with the invoice number and date, for example:
2166 "Invoice #54 (3/20/2008)".
2168 Intended for back-end context, with regard to translation and date formatting.
2172 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2173 # for backend use (and also does the wrong thing, localizing for end customer
2174 # instead of backoffice configured date format)
2175 sub invnum_date_pretty {
2177 #$self->mt('Invoice #').
2178 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2179 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2182 #sub _items_extra_usage_sections {
2184 # my $escape = shift;
2186 # my %sections = ();
2188 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2189 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2191 # next unless $cust_bill_pkg->pkgnum > 0;
2193 # foreach my $section ( keys %usage_class ) {
2195 # my $usage = $cust_bill_pkg->usage($section);
2197 # next unless $usage && $usage > 0;
2199 # $sections{$section} ||= 0;
2200 # $sections{$section} += $usage;
2206 # map { { 'description' => &{$escape}($_),
2207 # 'subtotal' => $sections{$_},
2208 # 'summarized' => '',
2209 # 'tax_section' => '',
2212 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2216 sub _items_extra_usage_sections {
2218 my $conf = $self->conf;
2226 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2228 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2229 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2230 next unless $cust_bill_pkg->pkgnum > 0;
2232 foreach my $classnum ( keys %usage_class ) {
2233 my $section = $usage_class{$classnum}->classname;
2234 $classnums{$section} = $classnum;
2236 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2237 my $amount = $detail->amount;
2238 next unless $amount && $amount > 0;
2240 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2241 $sections{$section}{amount} += $amount; #subtotal
2242 $sections{$section}{calls}++;
2243 $sections{$section}{duration} += $detail->duration;
2245 my $desc = $detail->regionname;
2246 my $description = $desc;
2247 $description = substr($desc, 0, $maxlength). '...'
2248 if $format eq 'latex' && length($desc) > $maxlength;
2250 $lines{$section}{$desc} ||= {
2251 description => &{$escape}($description),
2252 #pkgpart => $part_pkg->pkgpart,
2253 pkgnum => $cust_bill_pkg->pkgnum,
2258 #unit_amount => $cust_bill_pkg->unitrecur,
2259 quantity => $cust_bill_pkg->quantity,
2260 product_code => 'N/A',
2261 ext_description => [],
2264 $lines{$section}{$desc}{amount} += $amount;
2265 $lines{$section}{$desc}{calls}++;
2266 $lines{$section}{$desc}{duration} += $detail->duration;
2272 my %sectionmap = ();
2273 foreach (keys %sections) {
2274 my $usage_class = $usage_class{$classnums{$_}};
2275 $sectionmap{$_} = { 'description' => &{$escape}($_),
2276 'amount' => $sections{$_}{amount}, #subtotal
2277 'calls' => $sections{$_}{calls},
2278 'duration' => $sections{$_}{duration},
2280 'tax_section' => '',
2281 'sort_weight' => $usage_class->weight,
2282 ( $usage_class->format
2283 ? ( map { $_ => $usage_class->$_($format) }
2284 qw( description_generator header_generator total_generator total_line_generator )
2291 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2295 foreach my $section ( keys %lines ) {
2296 foreach my $line ( keys %{$lines{$section}} ) {
2297 my $l = $lines{$section}{$line};
2298 $l->{section} = $sectionmap{$section};
2299 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2300 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2305 return(\@sections, \@lines);
2311 my $end = $self->_date;
2313 # start at date of previous invoice + 1 second or 0 if no previous invoice
2314 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2315 $start = 0 if !$start;
2318 my $cust_main = $self->cust_main;
2319 my @pkgs = $cust_main->all_pkgs;
2320 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2323 foreach my $pkg ( @pkgs ) {
2324 my @h_cust_svc = $pkg->h_cust_svc($end);
2325 foreach my $h_cust_svc ( @h_cust_svc ) {
2326 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2327 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2329 my $inserted = $h_cust_svc->date_inserted;
2330 my $deleted = $h_cust_svc->date_deleted;
2331 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2333 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2335 # DID either activated or ported in; cannot be both for same DID simultaneously
2336 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2337 && (!$phone_inserted->lnp_status
2338 || $phone_inserted->lnp_status eq ''
2339 || $phone_inserted->lnp_status eq 'native')) {
2342 else { # this one not so clean, should probably move to (h_)svc_phone
2343 my $phone_portedin = qsearchs( 'h_svc_phone',
2344 { 'svcnum' => $h_cust_svc->svcnum,
2345 'lnp_status' => 'portedin' },
2346 FS::h_svc_phone->sql_h_searchs($end),
2348 $num_portedin++ if $phone_portedin;
2351 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2352 if($deleted >= $start && $deleted <= $end && $phone_deleted
2353 && (!$phone_deleted->lnp_status
2354 || $phone_deleted->lnp_status ne 'portingout')) {
2357 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2358 && $phone_deleted->lnp_status
2359 && $phone_deleted->lnp_status eq 'portingout') {
2363 # increment usage minutes
2364 if ( $phone_inserted ) {
2365 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2366 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2369 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2372 # don't look at this service again
2373 push @seen, $h_cust_svc->svcnum;
2377 $minutes = sprintf("%d", $minutes);
2378 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2379 . "$num_deactivated Ported-Out: $num_portedout ",
2380 "Total Minutes: $minutes");
2383 sub _items_accountcode_cdr {
2388 my $section = { 'amount' => 0,
2391 'sort_weight' => '',
2393 'description' => 'Usage by Account Code',
2399 my %accountcodes = ();
2401 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2402 next unless $cust_bill_pkg->pkgnum > 0;
2404 my @header = $cust_bill_pkg->details_header;
2405 next unless scalar(@header);
2406 $section->{'header'} = join(',',@header);
2408 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2410 $section->{'header'} = $detail->formatted('format' => $format)
2411 if($detail->detail eq $section->{'header'});
2413 my $accountcode = $detail->accountcode;
2414 next unless $accountcode;
2416 my $amount = $detail->amount;
2417 next unless $amount && $amount > 0;
2419 $accountcodes{$accountcode} ||= {
2420 description => $accountcode,
2427 product_code => 'N/A',
2428 section => $section,
2429 ext_description => [ $section->{'header'} ],
2433 $section->{'amount'} += $amount;
2434 $accountcodes{$accountcode}{'amount'} += $amount;
2435 $accountcodes{$accountcode}{calls}++;
2436 $accountcodes{$accountcode}{duration} += $detail->duration;
2437 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2441 foreach my $l ( values %accountcodes ) {
2442 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2443 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2444 foreach my $sorted_detail ( @sorted_detail ) {
2445 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2447 delete $l->{detail_temp};
2451 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2453 return ($section,\@sorted_lines);
2456 sub _items_svc_phone_sections {
2458 my $conf = $self->conf;
2466 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2468 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2469 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2471 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2472 next unless $cust_bill_pkg->pkgnum > 0;
2474 my @header = $cust_bill_pkg->details_header;
2475 next unless scalar(@header);
2477 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2479 my $phonenum = $detail->phonenum;
2480 next unless $phonenum;
2482 my $amount = $detail->amount;
2483 next unless $amount && $amount > 0;
2485 $sections{$phonenum} ||= { 'amount' => 0,
2488 'sort_weight' => -1,
2489 'phonenum' => $phonenum,
2491 $sections{$phonenum}{amount} += $amount; #subtotal
2492 $sections{$phonenum}{calls}++;
2493 $sections{$phonenum}{duration} += $detail->duration;
2495 my $desc = $detail->regionname;
2496 my $description = $desc;
2497 $description = substr($desc, 0, $maxlength). '...'
2498 if $format eq 'latex' && length($desc) > $maxlength;
2500 $lines{$phonenum}{$desc} ||= {
2501 description => &{$escape}($description),
2502 #pkgpart => $part_pkg->pkgpart,
2510 product_code => 'N/A',
2511 ext_description => [],
2514 $lines{$phonenum}{$desc}{amount} += $amount;
2515 $lines{$phonenum}{$desc}{calls}++;
2516 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2518 my $line = $usage_class{$detail->classnum}->classname;
2519 $sections{"$phonenum $line"} ||=
2523 'sort_weight' => $usage_class{$detail->classnum}->weight,
2524 'phonenum' => $phonenum,
2525 'header' => [ @header ],
2527 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2528 $sections{"$phonenum $line"}{calls}++;
2529 $sections{"$phonenum $line"}{duration} += $detail->duration;
2531 $lines{"$phonenum $line"}{$desc} ||= {
2532 description => &{$escape}($description),
2533 #pkgpart => $part_pkg->pkgpart,
2541 product_code => 'N/A',
2542 ext_description => [],
2545 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2546 $lines{"$phonenum $line"}{$desc}{calls}++;
2547 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2548 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2549 $detail->formatted('format' => $format);
2554 my %sectionmap = ();
2555 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2556 foreach ( keys %sections ) {
2557 my @header = @{ $sections{$_}{header} || [] };
2559 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2560 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2561 my $usage_class = $summary ? $simple : $usage_simple;
2562 my $ending = $summary ? ' usage charges' : '';
2565 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2567 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2568 'amount' => $sections{$_}{amount}, #subtotal
2569 'calls' => $sections{$_}{calls},
2570 'duration' => $sections{$_}{duration},
2572 'tax_section' => '',
2573 'phonenum' => $sections{$_}{phonenum},
2574 'sort_weight' => $sections{$_}{sort_weight},
2575 'post_total' => $summary, #inspire pagebreak
2577 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2578 qw( description_generator
2581 total_line_generator
2588 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2589 $a->{sort_weight} <=> $b->{sort_weight}
2594 foreach my $section ( keys %lines ) {
2595 foreach my $line ( keys %{$lines{$section}} ) {
2596 my $l = $lines{$section}{$line};
2597 $l->{section} = $sectionmap{$section};
2598 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2599 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2604 if($conf->exists('phone_usage_class_summary')) {
2605 # this only works with Latex
2609 # after this, we'll have only two sections per DID:
2610 # Calls Summary and Calls Detail
2611 foreach my $section ( @sections ) {
2612 if($section->{'post_total'}) {
2613 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2614 $section->{'total_line_generator'} = sub { '' };
2615 $section->{'total_generator'} = sub { '' };
2616 $section->{'header_generator'} = sub { '' };
2617 $section->{'description_generator'} = '';
2618 push @newsections, $section;
2619 my %calls_detail = %$section;
2620 $calls_detail{'post_total'} = '';
2621 $calls_detail{'sort_weight'} = '';
2622 $calls_detail{'description_generator'} = sub { '' };
2623 $calls_detail{'header_generator'} = sub {
2624 return ' & Date/Time & Called Number & Duration & Price'
2625 if $format eq 'latex';
2628 $calls_detail{'description'} = 'Calls Detail: '
2629 . $section->{'phonenum'};
2630 push @newsections, \%calls_detail;
2634 # after this, each usage class is collapsed/summarized into a single
2635 # line under the Calls Summary section
2636 foreach my $newsection ( @newsections ) {
2637 if($newsection->{'post_total'}) { # this means Calls Summary
2638 foreach my $section ( @sections ) {
2639 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2640 && !$section->{'post_total'});
2641 my $newdesc = $section->{'description'};
2642 my $tn = $section->{'phonenum'};
2643 $newdesc =~ s/$tn//g;
2644 my $line = { ext_description => [],
2648 calls => $section->{'calls'},
2649 section => $newsection,
2650 duration => $section->{'duration'},
2651 description => $newdesc,
2652 amount => sprintf("%.2f",$section->{'amount'}),
2653 product_code => 'N/A',
2655 push @newlines, $line;
2660 # after this, Calls Details is populated with all CDRs
2661 foreach my $newsection ( @newsections ) {
2662 if(!$newsection->{'post_total'}) { # this means Calls Details
2663 foreach my $line ( @lines ) {
2664 next unless (scalar(@{$line->{'ext_description'}}) &&
2665 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2667 my @extdesc = @{$line->{'ext_description'}};
2669 foreach my $extdesc ( @extdesc ) {
2670 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2671 push @newextdesc, $extdesc;
2673 $line->{'ext_description'} = \@newextdesc;
2674 $line->{'section'} = $newsection;
2675 push @newlines, $line;
2680 return(\@newsections, \@newlines);
2683 return(\@sections, \@lines);
2687 =sub _items_usage_class_summary OPTIONS
2689 Returns a list of detail items summarizing the usage charges on this
2690 invoice. Each one will have 'amount', 'description' (the usage charge name),
2691 and 'usage_classnum'.
2693 OPTIONS can include 'escape' (a function to escape the descriptions).
2697 sub _items_usage_class_summary {
2701 my $escape = $opt{escape} || sub { $_[0] };
2702 my $money_char = $opt{money_char};
2703 my $invnum = $self->invnum;
2704 my @classes = qsearch({
2705 'table' => 'usage_class',
2706 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2707 ' COUNT(*) AS calls, SUM(duration) AS duration',
2708 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2709 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2710 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2711 ' GROUP BY classnum, classname, weight'.
2712 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2713 ' ORDER BY weight ASC',
2717 description => &{$escape}($self->mt('Usage Summary')),
2721 foreach my $class (@classes) {
2722 $section->{subtotal} += $class->get('amount');
2724 'description' => &{$escape}($class->classname),
2725 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2726 'quantity' => $class->get('calls'),
2727 'duration' => $class->get('duration'),
2728 'usage_classnum' => $class->classnum,
2729 'section' => $section,
2732 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2736 sub _items_previous {
2738 my $conf = $self->conf;
2739 my $cust_main = $self->cust_main;
2740 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2742 foreach ( @pr_cust_bill ) {
2743 my $date = $conf->exists('invoice_show_prior_due_date')
2744 ? 'due '. $_->due_date2str('short')
2745 : $self->time2str_local('short', $_->_date);
2747 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2748 #'pkgpart' => 'N/A',
2750 'amount' => sprintf("%.2f", $_->owed),
2756 # 'description' => 'Previous Balance',
2757 # #'pkgpart' => 'N/A',
2758 # 'pkgnum' => 'N/A',
2759 # 'amount' => sprintf("%10.2f", $pr_total ),
2760 # 'ext_description' => [ map {
2761 # "Invoice ". $_->invnum.
2762 # " (". time2str("%x",$_->_date). ") ".
2763 # sprintf("%10.2f", $_->owed)
2764 # } @pr_cust_bill ],
2769 sub _items_credits {
2770 my( $self, %opt ) = @_;
2771 my $trim_len = $opt{'trim_len'} || 40;
2776 if ( $self->conf->exists('previous_balance-payments_since') ) {
2777 if ( $opt{'template'} eq 'statement' ) {
2778 # then the current bill is a "statement" (i.e. an invoice sent as
2779 # a payment receipt)
2780 # and in that case we want to see payments on or after THIS invoice
2781 @objects = qsearch('cust_credit', {
2782 'custnum' => $self->custnum,
2783 '_date' => {op => '>=', value => $self->_date},
2787 $date = $self->previous_bill->_date if $self->previous_bill;
2788 @objects = qsearch('cust_credit', {
2789 'custnum' => $self->custnum,
2790 '_date' => {op => '>=', value => $date},
2794 @objects = $self->cust_credited;
2797 foreach my $obj ( @objects ) {
2798 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2800 my $reason = substr($cust_credit->reason, 0, $trim_len);
2801 $reason .= '...' if length($reason) < length($cust_credit->reason);
2802 $reason = " ($reason) " if $reason;
2805 #'description' => 'Credit ref\#'. $_->crednum.
2806 # " (". time2str("%x",$_->cust_credit->_date) .")".
2808 'description' => $self->mt('Credit applied').' '.
2809 $self->time2str_local('short', $obj->_date). $reason,
2810 'amount' => sprintf("%.2f",$obj->amount),
2818 sub _items_payments {
2823 my $detailed = $self->conf->exists('invoice_payment_details');
2825 if ( $self->conf->exists('previous_balance-payments_since') ) {
2826 # then show payments dated on/after the previous bill...
2827 if ( $opt{'template'} eq 'statement' ) {
2828 # then the current bill is a "statement" (i.e. an invoice sent as
2829 # a payment receipt)
2830 # and in that case we want to see payments on or after THIS invoice
2831 @objects = qsearch('cust_pay', {
2832 'custnum' => $self->custnum,
2833 '_date' => {op => '>=', value => $self->_date},
2836 # the normal case: payments on or after the previous invoice
2838 $date = $self->previous_bill->_date if $self->previous_bill;
2839 @objects = qsearch('cust_pay', {
2840 'custnum' => $self->custnum,
2841 '_date' => {op => '>=', value => $date},
2843 # and before the current bill...
2844 @objects = grep { $_->_date < $self->_date } @objects;
2847 @objects = $self->cust_bill_pay;
2850 foreach my $obj (@objects) {
2851 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2852 my $desc = $self->mt('Payment received').' '.
2853 $self->time2str_local('short', $cust_pay->_date );
2854 $desc .= $self->mt(' via ') .
2855 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2859 'description' => $desc,
2860 'amount' => sprintf("%.2f", $obj->amount )
2870 my $conf = $self->conf;
2873 my ($pr_total) = $self->previous;
2874 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2876 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2877 # can we do some caching on this stuff? it's going to change infrequently
2879 $previous_charges_desc = $self->mt(
2880 $conf->config('previous_balance-text') || 'Previous Balance'
2883 # then return separate lines for previous balance and total new charges
2886 { total_item => $previous_charges_desc,
2887 total_amount => sprintf('%.2f',$pr_total)
2890 $new_charges_desc = $self->mt(
2891 $conf->config('previous_balance-text-total_new_charges')
2892 || 'Total New Charges'
2895 $new_charges_amount = $self->charged;
2899 $new_charges_desc = $self->mt('Total Charges');
2900 $new_charges_amount = sprintf('%.2f',$self->charged + $pr_total);
2904 if ( $conf->exists('invoice_show_prior_due_date') ) {
2905 # then the due date should be shown with Total New Charges,
2906 # and should NOT be shown with the Balance Due message.
2907 if ( $self->due_date ) {
2908 # localize the "Please pay by" message and the date itself
2909 # (grammar issues with this, yeah)
2910 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2911 $self->due_date2str('short');
2912 } elsif ( $self->terms ) {
2913 # phrases like "due on receipt" should be localized
2914 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2919 { total_item => $new_charges_desc,
2920 total_amount => $new_charges_amount,
2928 =item call_details [ OPTION => VALUE ... ]
2930 Returns an array of CSV strings representing the call details for this invoice
2931 The only option available is the boolean prepend_billed_number
2936 my ($self, %opt) = @_;
2938 my $format_function = sub { shift };
2940 if ($opt{prepend_billed_number}) {
2941 $format_function = sub {
2945 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2950 my @details = map { $_->details( 'format_function' => $format_function,
2951 'escape_function' => sub{ return() },
2955 $self->cust_bill_pkg;
2956 my $header = $details[0];
2957 ( $header, grep { $_ ne $header } @details );
2967 =item process_reprint
2971 sub process_reprint {
2972 process_re_X('print', @_);
2975 =item process_reemail
2979 sub process_reemail {
2980 process_re_X('email', @_);
2988 process_re_X('fax', @_);
2996 process_re_X('ftp', @_);
3003 sub process_respool {
3004 process_re_X('spool', @_);
3007 use Storable qw(thaw);
3011 my( $method, $job ) = ( shift, shift );
3012 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3014 my $param = thaw(decode_base64(shift));
3015 warn Dumper($param) if $DEBUG;
3025 # this is called from search/cust_bill.html and given all its search
3026 # parameters, so it needs to perform the same search.
3029 # spool_invoice ftp_invoice fax_invoice print_invoice
3030 my($method, $job, %param ) = @_;
3032 warn "re_X $method for job $job with param:\n".
3033 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3036 #some false laziness w/search/cust_bill.html
3037 $param{'order_by'} = 'cust_bill._date';
3039 my $query = FS::cust_bill->search(\%param);
3040 delete $query->{'count_query'};
3041 delete $query->{'count_addl'};
3043 $query->{debug} = 1; # was in here before, is obviously useful
3045 my @cust_bill = qsearch( $query );
3047 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3049 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3052 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3053 foreach my $cust_bill ( @cust_bill ) {
3054 $cust_bill->$method();
3056 if ( $job ) { #progressbar foo
3058 if ( time - $min_sec > $last ) {
3059 my $error = $job->update_statustext(
3060 int( 100 * $num / scalar(@cust_bill) )
3062 die $error if $error;
3073 =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