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).
452 my @cust_bill = sort { $a->_date <=> $b->_date }
453 grep { $_->owed != 0 }
454 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
455 #'_date' => { op=>'<', value=>$self->_date },
456 'invnum' => { op=>'<', value=>$self->invnum },
459 foreach ( @cust_bill ) { $total += $_->owed; }
463 =item enable_previous
465 Whether to show the 'Previous Charges' section when printing this invoice.
466 The negation of the 'disable_previous_balance' config setting.
470 sub enable_previous {
472 my $agentnum = $self->cust_main->agentnum;
473 !$self->conf->exists('disable_previous_balance', $agentnum);
478 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
485 { 'table' => 'cust_bill_pkg',
486 'hashref' => { 'invnum' => $self->invnum },
487 'order_by' => 'ORDER BY billpkgnum',
492 =item cust_bill_pkg_pkgnum PKGNUM
494 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
499 sub cust_bill_pkg_pkgnum {
500 my( $self, $pkgnum ) = @_;
502 { 'table' => 'cust_bill_pkg',
503 'hashref' => { 'invnum' => $self->invnum,
506 'order_by' => 'ORDER BY billpkgnum',
513 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
520 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
521 $self->cust_bill_pkg;
523 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
528 Returns true if any of the packages (or their definitions) corresponding to the
529 line items for this invoice have the no_auto flag set.
535 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
538 =item open_cust_bill_pkg
540 Returns the open line items for this invoice.
542 Note that cust_bill_pkg with both setup and recur fees are returned as two
543 separate line items, each with only one fee.
547 # modeled after cust_main::open_cust_bill
548 sub open_cust_bill_pkg {
551 # grep { $_->owed > 0 } $self->cust_bill_pkg
553 my %other = ( 'recur' => 'setup',
554 'setup' => 'recur', );
556 foreach my $field ( qw( recur setup )) {
557 push @open, map { $_->set( $other{$field}, 0 ); $_; }
558 grep { $_->owed($field) > 0 }
559 $self->cust_bill_pkg;
565 =item cust_bill_event
567 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
571 sub cust_bill_event {
573 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
576 =item num_cust_bill_event
578 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
582 sub num_cust_bill_event {
585 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
586 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
587 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
588 $sth->fetchrow_arrayref->[0];
593 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
597 #false laziness w/cust_pkg.pm
601 'table' => 'cust_event',
602 'addl_from' => 'JOIN part_event USING ( eventpart )',
603 'hashref' => { 'tablenum' => $self->invnum },
604 'extra_sql' => " AND eventtable = 'cust_bill' ",
610 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
614 #false laziness w/cust_pkg.pm
618 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
619 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
620 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
621 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
622 $sth->fetchrow_arrayref->[0];
627 Returns the customer (see L<FS::cust_main>) for this invoice.
633 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
636 =item cust_suspend_if_balance_over AMOUNT
638 Suspends the customer associated with this invoice if the total amount owed on
639 this invoice and all older invoices is greater than the specified amount.
641 Returns a list: an empty list on success or a list of errors.
645 sub cust_suspend_if_balance_over {
646 my( $self, $amount ) = ( shift, shift );
647 my $cust_main = $self->cust_main;
648 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
651 $cust_main->suspend(@_);
657 Depreciated. See the cust_credited method.
659 #Returns a list consisting of the total previous credited (see
660 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
661 #outstanding credits (FS::cust_credit objects).
667 croak "FS::cust_bill->cust_credit depreciated; see ".
668 "FS::cust_bill->cust_credit_bill";
671 #my @cust_credit = sort { $a->_date <=> $b->_date }
672 # grep { $_->credited != 0 && $_->_date < $self->_date }
673 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
675 #foreach (@cust_credit) { $total += $_->credited; }
676 #$total, @cust_credit;
681 Depreciated. See the cust_bill_pay method.
683 #Returns all payments (see L<FS::cust_pay>) for this invoice.
689 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
691 #sort { $a->_date <=> $b->_date }
692 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
698 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
701 sub cust_bill_pay_batch {
703 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
708 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
714 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
715 sort { $a->_date <=> $b->_date }
716 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
721 =item cust_credit_bill
723 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
729 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
730 sort { $a->_date <=> $b->_date }
731 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
735 sub cust_credit_bill {
736 shift->cust_credited(@_);
739 #=item cust_bill_pay_pkgnum PKGNUM
741 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
742 #with matching pkgnum.
746 #sub cust_bill_pay_pkgnum {
747 # my( $self, $pkgnum ) = @_;
748 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
749 # sort { $a->_date <=> $b->_date }
750 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
751 # 'pkgnum' => $pkgnum,
756 =item cust_bill_pay_pkg PKGNUM
758 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
759 applied against the matching pkgnum.
763 sub cust_bill_pay_pkg {
764 my( $self, $pkgnum ) = @_;
767 'select' => 'cust_bill_pay_pkg.*',
768 'table' => 'cust_bill_pay_pkg',
769 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
770 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
771 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
772 " AND cust_bill_pkg.pkgnum = $pkgnum",
777 #=item cust_credited_pkgnum PKGNUM
779 #=item cust_credit_bill_pkgnum PKGNUM
781 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
782 #with matching pkgnum.
786 #sub cust_credited_pkgnum {
787 # my( $self, $pkgnum ) = @_;
788 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
789 # sort { $a->_date <=> $b->_date }
790 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
791 # 'pkgnum' => $pkgnum,
796 #sub cust_credit_bill_pkgnum {
797 # shift->cust_credited_pkgnum(@_);
800 =item cust_credit_bill_pkg PKGNUM
802 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
803 applied against the matching pkgnum.
807 sub cust_credit_bill_pkg {
808 my( $self, $pkgnum ) = @_;
811 'select' => 'cust_credit_bill_pkg.*',
812 'table' => 'cust_credit_bill_pkg',
813 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
814 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
815 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
816 " AND cust_bill_pkg.pkgnum = $pkgnum",
821 =item cust_bill_batch
823 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
827 sub cust_bill_batch {
829 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
834 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
835 hash keyed by term length.
841 FS::discount_plan->all($self);
846 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
853 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
855 foreach (@taxlines) { $total += $_->setup; }
861 Returns the amount owed (still outstanding) on this invoice, which is charged
862 minus all payment applications (see L<FS::cust_bill_pay>) and credit
863 applications (see L<FS::cust_credit_bill>).
869 my $balance = $self->charged;
870 $balance -= $_->amount foreach ( $self->cust_bill_pay );
871 $balance -= $_->amount foreach ( $self->cust_credited );
872 $balance = sprintf( "%.2f", $balance);
873 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
878 my( $self, $pkgnum ) = @_;
880 #my $balance = $self->charged;
882 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
884 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
885 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
887 $balance = sprintf( "%.2f", $balance);
888 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
894 Returns true if this invoice should be hidden. See the
895 selfservice-hide_invoices-taxclass configuraiton setting.
901 my $conf = $self->conf;
902 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
904 my @cust_bill_pkg = $self->cust_bill_pkg;
905 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
906 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
909 =item apply_payments_and_credits [ OPTION => VALUE ... ]
911 Applies unapplied payments and credits to this invoice.
913 A hash of optional arguments may be passed. Currently "manual" is supported.
914 If true, a payment receipt is sent instead of a statement when
915 'payment_receipt_email' configuration option is set.
917 If there is an error, returns the error, otherwise returns false.
921 sub apply_payments_and_credits {
922 my( $self, %options ) = @_;
923 my $conf = $self->conf;
925 local $SIG{HUP} = 'IGNORE';
926 local $SIG{INT} = 'IGNORE';
927 local $SIG{QUIT} = 'IGNORE';
928 local $SIG{TERM} = 'IGNORE';
929 local $SIG{TSTP} = 'IGNORE';
930 local $SIG{PIPE} = 'IGNORE';
932 my $oldAutoCommit = $FS::UID::AutoCommit;
933 local $FS::UID::AutoCommit = 0;
936 $self->select_for_update; #mutex
938 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
939 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
941 if ( $conf->exists('pkg-balances') ) {
942 # limit @payments & @credits to those w/ a pkgnum grepped from $self
943 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
944 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
945 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
948 while ( $self->owed > 0 and ( @payments || @credits ) ) {
951 if ( @payments && @credits ) {
953 #decide which goes first by weight of top (unapplied) line item
955 my @open_lineitems = $self->open_cust_bill_pkg;
958 max( map { $_->part_pkg->pay_weight || 0 }
963 my $max_credit_weight =
964 max( map { $_->part_pkg->credit_weight || 0 }
970 #if both are the same... payments first? it has to be something
971 if ( $max_pay_weight >= $max_credit_weight ) {
977 } elsif ( @payments ) {
979 } elsif ( @credits ) {
982 die "guru meditation #12 and 35";
986 if ( $app eq 'pay' ) {
988 my $payment = shift @payments;
989 $unapp_amount = $payment->unapplied;
990 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
991 $app->pkgnum( $payment->pkgnum )
992 if $conf->exists('pkg-balances') && $payment->pkgnum;
994 } elsif ( $app eq 'credit' ) {
996 my $credit = shift @credits;
997 $unapp_amount = $credit->credited;
998 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
999 $app->pkgnum( $credit->pkgnum )
1000 if $conf->exists('pkg-balances') && $credit->pkgnum;
1003 die "guru meditation #12 and 35";
1007 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1008 warn "owed_pkgnum ". $app->pkgnum;
1009 $owed = $self->owed_pkgnum($app->pkgnum);
1011 $owed = $self->owed;
1013 next unless $owed > 0;
1015 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1016 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1018 $app->invnum( $self->invnum );
1020 my $error = $app->insert(%options);
1022 $dbh->rollback if $oldAutoCommit;
1023 return "Error inserting ". $app->table. " record: $error";
1025 die $error if $error;
1029 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1036 Sends this invoice to the destinations configured for this customer: sends
1037 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1039 Options can be passed as a hashref. Positional parameters are no longer
1042 I<template>: a suffix for alternate invoices
1044 I<agentnum>: obsolete, now does nothing.
1046 I<from> overrides the default email invoice From: address.
1048 I<amount>: obsolete, does nothing
1050 I<notice_name> overrides "Invoice" as the name of the sent document
1051 (templates from 10/2009 or newer required).
1053 I<lpr> overrides the system 'lpr' option as the command to print a document
1054 from standard input.
1060 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1061 my $conf = $self->conf;
1063 my $cust_main = $self->cust_main;
1065 my @invoicing_list = $cust_main->invoicing_list;
1068 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1069 && ! $cust_main->invoice_noemail;
1072 if grep { $_ eq 'POST' } @invoicing_list; #postal
1074 #this has never been used post-$ORIGINAL_ISP afaik
1075 $self->fax_invoice($opt)
1076 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1084 my $opt = shift || {};
1085 if ($opt and !ref($opt)) {
1086 die ref($self). '->email called with positional parameters';
1089 my $conf = $self->conf;
1091 my $from = delete $opt->{from};
1093 # this is where we set the From: address
1094 $from ||= $self->_agent_invoice_from || #XXX should go away
1095 $conf->invoice_from_full( $self->cust_main->agentnum );
1097 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1099 if ( ! @invoicing_list ) { #no recipients
1100 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1101 die 'No recipients for customer #'. $self->custnum;
1103 #default: better to notify this person than silence
1104 @invoicing_list = ($from);
1108 $self->SUPER::email( {
1110 'to' => \@invoicing_list,
1116 #this stays here for now because its explicitly used as
1117 # FS::cust_bill::queueable_email
1118 sub queueable_email {
1121 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1122 or die "invalid invoice number: " . $opt{invnum};
1124 my %args = map {$_ => $opt{$_}}
1126 qw( from notice_name no_coupon template );
1128 my $error = $self->email( \%args );
1129 die $error if $error;
1135 my $conf = $self->conf;
1137 #my $template = scalar(@_) ? shift : '';
1140 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1143 my $cust_main = $self->cust_main;
1144 my $name = $cust_main->name;
1145 my $name_short = $cust_main->name_short;
1146 my $invoice_number = $self->invnum;
1147 my $invoice_date = $self->_date_pretty;
1149 eval qq("$subject");
1152 =item lpr_data HASHREF
1154 Returns the postscript or plaintext for this invoice as an arrayref.
1156 Options must be passed as a hashref. Positional parameters are no longer
1159 I<template>, if specified, is the name of a suffix for alternate invoices.
1161 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1167 my $conf = $self->conf;
1168 my $opt = shift || {};
1169 if ($opt and !ref($opt)) {
1170 # nobody does this anyway
1171 die "FS::cust_bill::lpr_data called with positional parameters";
1174 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1175 [ $self->$method( $opt ) ];
1180 Prints this invoice.
1182 Options must be passed as a hashref.
1184 I<template>, if specified, is the name of a suffix for alternate invoices.
1186 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1192 return if $self->hide;
1193 my $conf = $self->conf;
1194 my $opt = shift || {};
1195 if ($opt and !ref($opt)) {
1196 die "FS::cust_bill::print called with positional parameters";
1199 my $lpr = delete $opt->{lpr};
1200 if($conf->exists('invoice_print_pdf')) {
1201 # Add the invoice to the current batch.
1202 $self->batch_invoice($opt);
1206 $self->lpr_data($opt),
1207 'agentnum' => $self->cust_main->agentnum,
1213 =item fax_invoice HASHREF
1217 Options must be passed as a hashref.
1219 I<template>, if specified, is the name of a suffix for alternate invoices.
1221 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1227 return if $self->hide;
1228 my $conf = $self->conf;
1229 my $opt = shift || {};
1230 if ($opt and !ref($opt)) {
1231 die "FS::cust_bill::fax_invoice called with positional parameters";
1234 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1235 unless $conf->exists('invoice_latex');
1237 my $dialstring = $self->cust_main->getfield('fax');
1240 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1241 'dialstring' => $dialstring,
1243 die $error if $error;
1247 =item batch_invoice [ HASHREF ]
1249 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1250 isn't an open batch, one will be created.
1252 HASHREF may contain any options to be passed to C<print_pdf>.
1257 my ($self, $opt) = @_;
1258 my $bill_batch = $self->get_open_bill_batch;
1259 my $cust_bill_batch = FS::cust_bill_batch->new({
1260 batchnum => $bill_batch->batchnum,
1261 invnum => $self->invnum,
1263 return $cust_bill_batch->insert($opt);
1266 =item get_open_batch
1268 Returns the currently open batch as an FS::bill_batch object, creating a new
1269 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1274 sub get_open_bill_batch {
1276 my $conf = $self->conf;
1277 my $hashref = { status => 'O' };
1278 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1279 ? $self->cust_main->agentnum
1281 my $batch = qsearchs('bill_batch', $hashref);
1282 return $batch if $batch;
1283 $batch = FS::bill_batch->new($hashref);
1284 my $error = $batch->insert;
1285 die $error if $error;
1289 =item ftp_invoice [ TEMPLATENAME ]
1291 Sends this invoice data via FTP.
1293 TEMPLATENAME is unused?
1299 my $conf = $self->conf;
1300 my $template = scalar(@_) ? shift : '';
1303 'protocol' => 'ftp',
1304 'server' => $conf->config('cust_bill-ftpserver'),
1305 'username' => $conf->config('cust_bill-ftpusername'),
1306 'password' => $conf->config('cust_bill-ftppassword'),
1307 'dir' => $conf->config('cust_bill-ftpdir'),
1308 'format' => $conf->config('cust_bill-ftpformat'),
1312 =item spool_invoice [ TEMPLATENAME ]
1314 Spools this invoice data (see L<FS::spool_csv>)
1316 TEMPLATENAME is unused?
1322 my $conf = $self->conf;
1323 my $template = scalar(@_) ? shift : '';
1326 'format' => $conf->config('cust_bill-spoolformat'),
1327 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1331 =item send_csv OPTION => VALUE, ...
1333 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1337 protocol - currently only "ftp"
1343 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1344 and YYMMDDHHMMSS is a timestamp.
1346 See L</print_csv> for a description of the output format.
1351 my($self, %opt) = @_;
1355 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1356 mkdir $spooldir, 0700 unless -d $spooldir;
1358 # don't localize dates here, they're a defined format
1359 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1360 my $file = "$spooldir/$tracctnum.csv";
1362 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1364 open(CSV, ">$file") or die "can't open $file: $!";
1372 if ( $opt{protocol} eq 'ftp' ) {
1373 eval "use Net::FTP;";
1375 $net = Net::FTP->new($opt{server}) or die @$;
1377 die "unknown protocol: $opt{protocol}";
1380 $net->login( $opt{username}, $opt{password} )
1381 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1383 $net->binary or die "can't set binary mode";
1385 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1387 $net->put($file) or die "can't put $file: $!";
1397 Spools CSV invoice data.
1403 =item format - any of FS::Misc::::Invoicing::spool_formats
1405 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1406 customer has the corresponding invoice destinations set (see
1407 L<FS::cust_main_invoice>).
1409 =item agent_spools - if set to a true value, will spool to per-agent files
1410 rather than a single global file
1412 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1413 append to that spool. L<FS::Cron::upload> will then send the spool file to
1416 =item balanceover - if set, only spools the invoice if the total amount owed on
1417 this invoice and all older invoices is greater than the specified amount.
1419 =item time - the "current time". Controls the printing of past due messages
1427 my($self, %opt) = @_;
1429 my $time = $opt{'time'} || time;
1430 my $cust_main = $self->cust_main;
1432 if ( $opt{'dest'} ) {
1433 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1434 $cust_main->invoicing_list;
1435 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1436 || ! keys %invoicing_list;
1439 if ( $opt{'balanceover'} ) {
1441 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1444 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1445 mkdir $spooldir, 0700 unless -d $spooldir;
1447 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1450 if ( $opt{'agent_spools'} ) {
1451 $file = 'agentnum'.$cust_main->agentnum;
1456 if ( $opt{'upload_targetnum'} ) {
1457 $spooldir .= '/target'.$opt{'upload_targetnum'};
1458 mkdir $spooldir, 0700 unless -d $spooldir;
1459 } # otherwise it just goes into export.xxx/cust_bill
1461 if ( lc($opt{'format'}) eq 'billco' ) {
1465 $file = "$spooldir/$file.csv";
1467 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1469 open(CSV, ">>$file") or die "can't open $file: $!";
1470 flock(CSV, LOCK_EX);
1475 if ( lc($opt{'format'}) eq 'billco' ) {
1477 flock(CSV, LOCK_UN);
1480 $file =~ s/-header.csv$/-detail.csv/;
1482 open(CSV,">>$file") or die "can't open $file: $!";
1483 flock(CSV, LOCK_EX);
1487 print CSV $detail if defined($detail);
1489 flock(CSV, LOCK_UN);
1496 =item print_csv OPTION => VALUE, ...
1498 Returns CSV data for this invoice.
1502 format - 'default', 'billco', 'oneline', 'bridgestone'
1504 Returns a list consisting of two scalars. The first is a single line of CSV
1505 header information for this invoice. The second is one or more lines of CSV
1506 detail information for this invoice.
1508 If I<format> is not specified or "default", the fields of the CSV file are as
1511 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1512 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1516 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1518 B<record_type> is C<cust_bill> for the initial header line only. The
1519 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1520 fields are filled in.
1522 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1523 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1526 =item invnum - invoice number
1528 =item custnum - customer number
1530 =item _date - invoice date
1532 =item charged - total invoice amount
1534 =item first - customer first name
1536 =item last - customer first name
1538 =item company - company name
1540 =item address1 - address line 1
1542 =item address2 - address line 1
1552 =item pkg - line item description
1554 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1556 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1558 =item sdate - start date for recurring fee
1560 =item edate - end date for recurring fee
1564 If I<format> is "billco", the fields of the header CSV file are as follows:
1566 +-------------------------------------------------------------------+
1567 | FORMAT HEADER FILE |
1568 |-------------------------------------------------------------------|
1569 | Field | Description | Name | Type | Width |
1570 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1571 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1572 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1573 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1574 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1575 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1576 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1577 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1578 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1579 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1580 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1581 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1582 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1583 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1584 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1585 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1586 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1587 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1588 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1589 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1590 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1591 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1592 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1593 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1594 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1595 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1596 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1597 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1598 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1599 +-------+-------------------------------+------------+------+-------+
1601 If I<format> is "billco", the fields of the detail CSV file are as follows:
1603 FORMAT FOR DETAIL FILE
1605 Field | Description | Name | Type | Width
1606 1 | N/A-Leave Empty | RC | CHAR | 2
1607 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1608 3 | Account Number | TRACCTNUM | CHAR | 15
1609 4 | Invoice Number | TRINVOICE | CHAR | 15
1610 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1611 6 | Transaction Detail | DETAILS | CHAR | 100
1612 7 | Amount | AMT | NUM* | 9
1613 8 | Line Format Control** | LNCTRL | CHAR | 2
1614 9 | Grouping Code | GROUP | CHAR | 2
1615 10 | User Defined | ACCT CODE | CHAR | 15
1617 If format is 'oneline', there is no detail file. Each invoice has a
1618 header line only, with the fields:
1620 Agent number, agent name, customer number, first name, last name, address
1621 line 1, address line 2, city, state, zip, invoice date, invoice number,
1622 amount charged, amount due, previous balance, due date.
1624 and then, for each line item, three columns containing the package number,
1625 description, and amount.
1627 If format is 'bridgestone', there is no detail file. Each invoice has a
1628 header line with the following fields in a fixed-width format:
1630 Customer number (in display format), date, name (first last), company,
1631 address 1, address 2, city, state, zip.
1633 This is a mailing list format, and has no per-invoice fields. To avoid
1634 sending redundant notices, the spooling event should have a "once" or
1635 "once_percust_every" condition.
1640 my($self, %opt) = @_;
1642 eval "use Text::CSV_XS";
1645 my $cust_main = $self->cust_main;
1647 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1648 my $format = lc($opt{'format'});
1650 my $time = $opt{'time'} || time;
1652 my $tracctnum = ''; #leaking out from billco-specific sections :/
1653 if ( $format eq 'billco' ) {
1656 $self->conf->config('billco-account_num', $cust_main->agentnum);
1658 $tracctnum = $account_num eq 'display_custnum'
1659 ? $cust_main->display_custnum
1660 : $opt{'tracctnum'};
1663 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1665 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1667 my( $previous_balance, @unused ) = $self->previous; #previous balance
1669 my $pmt_cr_applied = 0;
1670 $pmt_cr_applied += $_->{'amount'}
1671 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1673 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1676 '', # 1 | N/A-Leave Empty CHAR 2
1677 '', # 2 | N/A-Leave Empty CHAR 15
1678 $tracctnum, # 3 | Transaction Account No CHAR 15
1679 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1680 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1681 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1682 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1683 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1684 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1685 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1686 '', # 10 | Ancillary Billing Information CHAR 30
1687 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1688 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1691 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1694 $duedate, # 14 | Bill Due Date CHAR 10
1696 $previous_balance, # 15 | Previous Balance NUM* 9
1697 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1698 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1699 $totaldue, # 18 | Total Amt Due NUM* 9
1700 $totaldue, # 19 | Total Amt Due NUM* 9
1701 '', # 20 | 30 Day Aging NUM* 9
1702 '', # 21 | 60 Day Aging NUM* 9
1703 '', # 22 | 90 Day Aging NUM* 9
1704 'N', # 23 | Y/N CHAR 1
1705 '', # 24 | Remittance automation CHAR 100
1706 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1707 $self->custnum, # 26 | Customer Reference Number CHAR 15
1708 '0', # 27 | Federal Tax*** NUM* 9
1709 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1710 '0', # 29 | Other Taxes & Fees*** NUM* 9
1713 } elsif ( $format eq 'oneline' ) { #name
1715 my ($previous_balance) = $self->previous;
1716 $previous_balance = sprintf('%.2f', $previous_balance);
1717 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1723 $self->_items_pkg, #_items_nontax? no sections or anything
1728 $cust_main->agentnum,
1729 $cust_main->agent->agent,
1733 $cust_main->company,
1734 $cust_main->address1,
1735 $cust_main->address2,
1741 time2str("%x", $self->_date),
1746 $self->due_date2str("%x"),
1751 } elsif ( $format eq 'bridgestone' ) {
1753 # bypass the CSV stuff and just return this
1754 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1755 my $zip = $cust_main->zip;
1757 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1761 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1763 $cust_main->display_custnum,
1765 uc(substr($cust_main->contact_firstlast,0,30)),
1766 uc(substr($cust_main->company ,0,30)),
1767 uc(substr($cust_main->address1 ,0,30)),
1768 uc(substr($cust_main->address2 ,0,30)),
1769 uc(substr($cust_main->city ,0,20)),
1770 uc($cust_main->state),
1776 } elsif ( $format eq 'ics' ) {
1778 my $bill = $cust_main->bill_location;
1779 my $zip = $bill->zip;
1783 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1788 # minor false laziness with print_generic
1789 my ($previous_balance) = $self->previous;
1790 my $balance_due = $self->owed + $previous_balance;
1791 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1792 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1795 if ( $self->due_date and $time >= $self->due_date ) {
1796 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1800 my $header = sprintf(
1801 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1802 $cust_main->display_custnum, #BID
1803 uc($cust_main->first), #FNAME
1804 uc($cust_main->last), #LNAME
1805 '00', #BATCH, should this ever be anything else?
1806 uc($cust_main->company), #COMP
1807 uc($bill->address1), #STREET1
1808 uc($bill->address2), #STREET2
1809 uc($bill->city), #CITY
1810 uc($bill->state), #STATE
1813 time2str('%Y%m%d', $self->_date), #BILL_DATE
1814 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1815 ( map {sprintf('%0.2f', $_)}
1816 $balance_due, #AMNT_DUE
1817 $previous_balance, #PREV_BAL
1818 $payment_total, #PYMT_RCVD
1819 $credit_total, #CREDITS
1820 $previous_balance, #BEG_BAL--is this correct?
1821 $self->charged, #NEW_CHRG
1824 $past_due, #PAST_MSG
1828 my %svc_class = ('' => ''); # maybe cache this more persistently?
1830 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1832 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1833 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1837 my @dates = ( $self->_date, undef );
1838 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1839 $dates[1] = $prev->sdate; #questionable
1842 # generate an 01 detail for each service
1843 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1844 foreach my $cust_svc ( @svcs ) {
1845 $show_pkgnum = ''; # hide it if we're showing svcnums
1847 my $svcpart = $cust_svc->svcpart;
1848 if (!exists($svc_class{$svcpart})) {
1849 my $classnum = $cust_svc->part_svc->classnum;
1850 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1852 $svc_class{$svcpart} = $part_svc_class ?
1853 $part_svc_class->classname :
1857 my @h_label = $cust_svc->label(@dates, 'I');
1858 push @details, sprintf('01%-9s%-20s%-47s',
1860 $svc_class{$svcpart},
1863 } #foreach $cust_svc
1866 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1867 if ($cust_bill_pkg->recur > 0) {
1868 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1869 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1871 push @details, sprintf('02%-6s%-60s%-10s',
1874 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1876 } #foreach $cust_bill_pkg
1878 # Tag this row so that we know whether this is one page (1), two pages
1879 # (2), # or "big" (B). The tag will be stripped off before uploading.
1880 if ( scalar(@details) < 12 ) {
1882 } elsif ( scalar(@details) < 58 ) {
1888 return join('', $header, @details, "\n");
1896 time2str("%x", $self->_date),
1897 sprintf("%.2f", $self->charged),
1898 ( map { $cust_main->getfield($_) }
1899 qw( first last company address1 address2 city state zip country ) ),
1901 ) or die "can't create csv";
1904 my $header = $csv->string. "\n";
1907 if ( lc($opt{'format'}) eq 'billco' ) {
1910 my %items_opt = ( format => 'template',
1911 escape_function => sub { shift } );
1912 # I don't know what characters billco actually tolerates in spool entries.
1913 # Text::CSV will take care of delimiters, though.
1915 my @items = ( $self->_items_pkg(%items_opt),
1916 $self->_items_fee(%items_opt) );
1917 foreach my $item (@items) {
1919 my $description = $item->{'description'};
1920 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1921 $description .= ': ' . $item->{ext_description}[0];
1925 '', # 1 | N/A-Leave Empty CHAR 2
1926 '', # 2 | N/A-Leave Empty CHAR 15
1927 $tracctnum, # 3 | Account Number CHAR 15
1928 $self->invnum, # 4 | Invoice Number CHAR 15
1929 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1930 $description, # 6 | Transaction Detail CHAR 100
1931 $item->{'amount'}, # 7 | Amount NUM* 9
1932 '', # 8 | Line Format Control** CHAR 2
1933 '', # 9 | Grouping Code CHAR 2
1934 '', # 10 | User Defined CHAR 15
1937 $detail .= $csv->string. "\n";
1941 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1947 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1949 my($pkg, $setup, $recur, $sdate, $edate);
1950 if ( $cust_bill_pkg->pkgnum ) {
1952 ($pkg, $setup, $recur, $sdate, $edate) = (
1953 $cust_bill_pkg->part_pkg->pkg,
1954 ( $cust_bill_pkg->setup != 0
1955 ? sprintf("%.2f", $cust_bill_pkg->setup )
1957 ( $cust_bill_pkg->recur != 0
1958 ? sprintf("%.2f", $cust_bill_pkg->recur )
1960 ( $cust_bill_pkg->sdate
1961 ? time2str("%x", $cust_bill_pkg->sdate)
1963 ($cust_bill_pkg->edate
1964 ? time2str("%x", $cust_bill_pkg->edate)
1968 } else { #pkgnum tax
1969 next unless $cust_bill_pkg->setup != 0;
1970 $pkg = $cust_bill_pkg->desc;
1971 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1972 ( $sdate, $edate ) = ( '', '' );
1978 ( map { '' } (1..11) ),
1979 ($pkg, $setup, $recur, $sdate, $edate)
1980 ) or die "can't create csv";
1982 $detail .= $csv->string. "\n";
1988 ( $header, $detail );
1994 Pays this invoice with a compliemntary payment. If there is an error,
1995 returns the error, otherwise returns false.
2001 my $cust_pay = new FS::cust_pay ( {
2002 'invnum' => $self->invnum,
2003 'paid' => $self->owed,
2006 'payinfo' => $self->cust_main->payinfo,
2014 Attempts to pay this invoice with a credit card payment via a
2015 Business::OnlinePayment realtime gateway. See
2016 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2017 for supported processors.
2023 $self->realtime_bop( 'CC', @_ );
2028 Attempts to pay this invoice with an electronic check (ACH) payment via a
2029 Business::OnlinePayment realtime gateway. See
2030 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2031 for supported processors.
2037 $self->realtime_bop( 'ECHECK', @_ );
2042 Attempts to pay this invoice with phone bill (LEC) payment via a
2043 Business::OnlinePayment realtime gateway. See
2044 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2045 for supported processors.
2051 $self->realtime_bop( 'LEC', @_ );
2055 my( $self, $method ) = (shift,shift);
2056 my $conf = $self->conf;
2059 my $cust_main = $self->cust_main;
2060 my $balance = $cust_main->balance;
2061 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2062 $amount = sprintf("%.2f", $amount);
2063 return "not run (balance $balance)" unless $amount > 0;
2065 my $description = 'Internet Services';
2066 if ( $conf->exists('business-onlinepayment-description') ) {
2067 my $dtempl = $conf->config('business-onlinepayment-description');
2069 my $agent_obj = $cust_main->agent
2070 or die "can't retreive agent for $cust_main (agentnum ".
2071 $cust_main->agentnum. ")";
2072 my $agent = $agent_obj->agent;
2073 my $pkgs = join(', ',
2074 map { $_->part_pkg->pkg }
2075 grep { $_->pkgnum } $self->cust_bill_pkg
2077 $description = eval qq("$dtempl");
2080 $cust_main->realtime_bop($method, $amount,
2081 'description' => $description,
2082 'invnum' => $self->invnum,
2083 #this didn't do what we want, it just calls apply_payments_and_credits
2085 'apply_to_invoice' => 1,
2088 #this changes application behavior: auto payments
2089 #triggered against a specific invoice are now applied
2090 #to that invoice instead of oldest open.
2096 =item batch_card OPTION => VALUE...
2098 Adds a payment for this invoice to the pending credit card batch (see
2099 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2100 runs the payment using a realtime gateway.
2105 my ($self, %options) = @_;
2106 my $cust_main = $self->cust_main;
2108 $options{invnum} = $self->invnum;
2110 $cust_main->batch_card(%options);
2113 sub _agent_template {
2115 $self->cust_main->agent_template;
2118 sub _agent_invoice_from {
2120 $self->cust_main->agent_invoice_from;
2123 =item invoice_barcode DIR_OR_FALSE
2125 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2126 it is taken as the temp directory where the PNG file will be generated and the
2127 PNG file name is returned. Otherwise, the PNG image itself is returned.
2131 sub invoice_barcode {
2132 my ($self, $dir) = (shift,shift);
2134 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2135 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2136 my $gd = $gdbar->plot(Height => 30);
2139 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2143 ) or die "can't open temp file: $!\n";
2144 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2145 my $png_file = $bh->filename;
2152 =item invnum_date_pretty
2154 Returns a string with the invoice number and date, for example:
2155 "Invoice #54 (3/20/2008)".
2157 Intended for back-end context, with regard to translation and date formatting.
2161 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2162 # for backend use (and also does the wrong thing, localizing for end customer
2163 # instead of backoffice configured date format)
2164 sub invnum_date_pretty {
2166 #$self->mt('Invoice #').
2167 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2168 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2171 #sub _items_extra_usage_sections {
2173 # my $escape = shift;
2175 # my %sections = ();
2177 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2178 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2180 # next unless $cust_bill_pkg->pkgnum > 0;
2182 # foreach my $section ( keys %usage_class ) {
2184 # my $usage = $cust_bill_pkg->usage($section);
2186 # next unless $usage && $usage > 0;
2188 # $sections{$section} ||= 0;
2189 # $sections{$section} += $usage;
2195 # map { { 'description' => &{$escape}($_),
2196 # 'subtotal' => $sections{$_},
2197 # 'summarized' => '',
2198 # 'tax_section' => '',
2201 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2205 sub _items_extra_usage_sections {
2207 my $conf = $self->conf;
2215 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2217 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2218 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2219 next unless $cust_bill_pkg->pkgnum > 0;
2221 foreach my $classnum ( keys %usage_class ) {
2222 my $section = $usage_class{$classnum}->classname;
2223 $classnums{$section} = $classnum;
2225 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2226 my $amount = $detail->amount;
2227 next unless $amount && $amount > 0;
2229 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2230 $sections{$section}{amount} += $amount; #subtotal
2231 $sections{$section}{calls}++;
2232 $sections{$section}{duration} += $detail->duration;
2234 my $desc = $detail->regionname;
2235 my $description = $desc;
2236 $description = substr($desc, 0, $maxlength). '...'
2237 if $format eq 'latex' && length($desc) > $maxlength;
2239 $lines{$section}{$desc} ||= {
2240 description => &{$escape}($description),
2241 #pkgpart => $part_pkg->pkgpart,
2242 pkgnum => $cust_bill_pkg->pkgnum,
2247 #unit_amount => $cust_bill_pkg->unitrecur,
2248 quantity => $cust_bill_pkg->quantity,
2249 product_code => 'N/A',
2250 ext_description => [],
2253 $lines{$section}{$desc}{amount} += $amount;
2254 $lines{$section}{$desc}{calls}++;
2255 $lines{$section}{$desc}{duration} += $detail->duration;
2261 my %sectionmap = ();
2262 foreach (keys %sections) {
2263 my $usage_class = $usage_class{$classnums{$_}};
2264 $sectionmap{$_} = { 'description' => &{$escape}($_),
2265 'amount' => $sections{$_}{amount}, #subtotal
2266 'calls' => $sections{$_}{calls},
2267 'duration' => $sections{$_}{duration},
2269 'tax_section' => '',
2270 'sort_weight' => $usage_class->weight,
2271 ( $usage_class->format
2272 ? ( map { $_ => $usage_class->$_($format) }
2273 qw( description_generator header_generator total_generator total_line_generator )
2280 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2284 foreach my $section ( keys %lines ) {
2285 foreach my $line ( keys %{$lines{$section}} ) {
2286 my $l = $lines{$section}{$line};
2287 $l->{section} = $sectionmap{$section};
2288 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2289 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2294 return(\@sections, \@lines);
2300 my $end = $self->_date;
2302 # start at date of previous invoice + 1 second or 0 if no previous invoice
2303 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2304 $start = 0 if !$start;
2307 my $cust_main = $self->cust_main;
2308 my @pkgs = $cust_main->all_pkgs;
2309 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2312 foreach my $pkg ( @pkgs ) {
2313 my @h_cust_svc = $pkg->h_cust_svc($end);
2314 foreach my $h_cust_svc ( @h_cust_svc ) {
2315 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2316 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2318 my $inserted = $h_cust_svc->date_inserted;
2319 my $deleted = $h_cust_svc->date_deleted;
2320 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2322 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2324 # DID either activated or ported in; cannot be both for same DID simultaneously
2325 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2326 && (!$phone_inserted->lnp_status
2327 || $phone_inserted->lnp_status eq ''
2328 || $phone_inserted->lnp_status eq 'native')) {
2331 else { # this one not so clean, should probably move to (h_)svc_phone
2332 my $phone_portedin = qsearchs( 'h_svc_phone',
2333 { 'svcnum' => $h_cust_svc->svcnum,
2334 'lnp_status' => 'portedin' },
2335 FS::h_svc_phone->sql_h_searchs($end),
2337 $num_portedin++ if $phone_portedin;
2340 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2341 if($deleted >= $start && $deleted <= $end && $phone_deleted
2342 && (!$phone_deleted->lnp_status
2343 || $phone_deleted->lnp_status ne 'portingout')) {
2346 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2347 && $phone_deleted->lnp_status
2348 && $phone_deleted->lnp_status eq 'portingout') {
2352 # increment usage minutes
2353 if ( $phone_inserted ) {
2354 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2355 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2358 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2361 # don't look at this service again
2362 push @seen, $h_cust_svc->svcnum;
2366 $minutes = sprintf("%d", $minutes);
2367 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2368 . "$num_deactivated Ported-Out: $num_portedout ",
2369 "Total Minutes: $minutes");
2372 sub _items_accountcode_cdr {
2377 my $section = { 'amount' => 0,
2380 'sort_weight' => '',
2382 'description' => 'Usage by Account Code',
2388 my %accountcodes = ();
2390 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2391 next unless $cust_bill_pkg->pkgnum > 0;
2393 my @header = $cust_bill_pkg->details_header;
2394 next unless scalar(@header);
2395 $section->{'header'} = join(',',@header);
2397 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2399 $section->{'header'} = $detail->formatted('format' => $format)
2400 if($detail->detail eq $section->{'header'});
2402 my $accountcode = $detail->accountcode;
2403 next unless $accountcode;
2405 my $amount = $detail->amount;
2406 next unless $amount && $amount > 0;
2408 $accountcodes{$accountcode} ||= {
2409 description => $accountcode,
2416 product_code => 'N/A',
2417 section => $section,
2418 ext_description => [ $section->{'header'} ],
2422 $section->{'amount'} += $amount;
2423 $accountcodes{$accountcode}{'amount'} += $amount;
2424 $accountcodes{$accountcode}{calls}++;
2425 $accountcodes{$accountcode}{duration} += $detail->duration;
2426 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2430 foreach my $l ( values %accountcodes ) {
2431 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2432 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2433 foreach my $sorted_detail ( @sorted_detail ) {
2434 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2436 delete $l->{detail_temp};
2440 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2442 return ($section,\@sorted_lines);
2445 sub _items_svc_phone_sections {
2447 my $conf = $self->conf;
2455 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2457 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2458 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2460 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2461 next unless $cust_bill_pkg->pkgnum > 0;
2463 my @header = $cust_bill_pkg->details_header;
2464 next unless scalar(@header);
2466 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2468 my $phonenum = $detail->phonenum;
2469 next unless $phonenum;
2471 my $amount = $detail->amount;
2472 next unless $amount && $amount > 0;
2474 $sections{$phonenum} ||= { 'amount' => 0,
2477 'sort_weight' => -1,
2478 'phonenum' => $phonenum,
2480 $sections{$phonenum}{amount} += $amount; #subtotal
2481 $sections{$phonenum}{calls}++;
2482 $sections{$phonenum}{duration} += $detail->duration;
2484 my $desc = $detail->regionname;
2485 my $description = $desc;
2486 $description = substr($desc, 0, $maxlength). '...'
2487 if $format eq 'latex' && length($desc) > $maxlength;
2489 $lines{$phonenum}{$desc} ||= {
2490 description => &{$escape}($description),
2491 #pkgpart => $part_pkg->pkgpart,
2499 product_code => 'N/A',
2500 ext_description => [],
2503 $lines{$phonenum}{$desc}{amount} += $amount;
2504 $lines{$phonenum}{$desc}{calls}++;
2505 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2507 my $line = $usage_class{$detail->classnum}->classname;
2508 $sections{"$phonenum $line"} ||=
2512 'sort_weight' => $usage_class{$detail->classnum}->weight,
2513 'phonenum' => $phonenum,
2514 'header' => [ @header ],
2516 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2517 $sections{"$phonenum $line"}{calls}++;
2518 $sections{"$phonenum $line"}{duration} += $detail->duration;
2520 $lines{"$phonenum $line"}{$desc} ||= {
2521 description => &{$escape}($description),
2522 #pkgpart => $part_pkg->pkgpart,
2530 product_code => 'N/A',
2531 ext_description => [],
2534 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2535 $lines{"$phonenum $line"}{$desc}{calls}++;
2536 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2537 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2538 $detail->formatted('format' => $format);
2543 my %sectionmap = ();
2544 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2545 foreach ( keys %sections ) {
2546 my @header = @{ $sections{$_}{header} || [] };
2548 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2549 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2550 my $usage_class = $summary ? $simple : $usage_simple;
2551 my $ending = $summary ? ' usage charges' : '';
2554 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2556 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2557 'amount' => $sections{$_}{amount}, #subtotal
2558 'calls' => $sections{$_}{calls},
2559 'duration' => $sections{$_}{duration},
2561 'tax_section' => '',
2562 'phonenum' => $sections{$_}{phonenum},
2563 'sort_weight' => $sections{$_}{sort_weight},
2564 'post_total' => $summary, #inspire pagebreak
2566 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2567 qw( description_generator
2570 total_line_generator
2577 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2578 $a->{sort_weight} <=> $b->{sort_weight}
2583 foreach my $section ( keys %lines ) {
2584 foreach my $line ( keys %{$lines{$section}} ) {
2585 my $l = $lines{$section}{$line};
2586 $l->{section} = $sectionmap{$section};
2587 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2588 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2593 if($conf->exists('phone_usage_class_summary')) {
2594 # this only works with Latex
2598 # after this, we'll have only two sections per DID:
2599 # Calls Summary and Calls Detail
2600 foreach my $section ( @sections ) {
2601 if($section->{'post_total'}) {
2602 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2603 $section->{'total_line_generator'} = sub { '' };
2604 $section->{'total_generator'} = sub { '' };
2605 $section->{'header_generator'} = sub { '' };
2606 $section->{'description_generator'} = '';
2607 push @newsections, $section;
2608 my %calls_detail = %$section;
2609 $calls_detail{'post_total'} = '';
2610 $calls_detail{'sort_weight'} = '';
2611 $calls_detail{'description_generator'} = sub { '' };
2612 $calls_detail{'header_generator'} = sub {
2613 return ' & Date/Time & Called Number & Duration & Price'
2614 if $format eq 'latex';
2617 $calls_detail{'description'} = 'Calls Detail: '
2618 . $section->{'phonenum'};
2619 push @newsections, \%calls_detail;
2623 # after this, each usage class is collapsed/summarized into a single
2624 # line under the Calls Summary section
2625 foreach my $newsection ( @newsections ) {
2626 if($newsection->{'post_total'}) { # this means Calls Summary
2627 foreach my $section ( @sections ) {
2628 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2629 && !$section->{'post_total'});
2630 my $newdesc = $section->{'description'};
2631 my $tn = $section->{'phonenum'};
2632 $newdesc =~ s/$tn//g;
2633 my $line = { ext_description => [],
2637 calls => $section->{'calls'},
2638 section => $newsection,
2639 duration => $section->{'duration'},
2640 description => $newdesc,
2641 amount => sprintf("%.2f",$section->{'amount'}),
2642 product_code => 'N/A',
2644 push @newlines, $line;
2649 # after this, Calls Details is populated with all CDRs
2650 foreach my $newsection ( @newsections ) {
2651 if(!$newsection->{'post_total'}) { # this means Calls Details
2652 foreach my $line ( @lines ) {
2653 next unless (scalar(@{$line->{'ext_description'}}) &&
2654 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2656 my @extdesc = @{$line->{'ext_description'}};
2658 foreach my $extdesc ( @extdesc ) {
2659 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2660 push @newextdesc, $extdesc;
2662 $line->{'ext_description'} = \@newextdesc;
2663 $line->{'section'} = $newsection;
2664 push @newlines, $line;
2669 return(\@newsections, \@newlines);
2672 return(\@sections, \@lines);
2676 =sub _items_usage_class_summary OPTIONS
2678 Returns a list of detail items summarizing the usage charges on this
2679 invoice. Each one will have 'amount', 'description' (the usage charge name),
2680 and 'usage_classnum'.
2682 OPTIONS can include 'escape' (a function to escape the descriptions).
2686 sub _items_usage_class_summary {
2690 my $escape = $opt{escape} || sub { $_[0] };
2691 my $invnum = $self->invnum;
2692 my @classes = qsearch({
2693 'table' => 'usage_class',
2694 'select' => 'classnum, classname, SUM(amount) AS amount',
2695 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2696 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2697 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2698 ' GROUP BY classnum, classname, weight'.
2699 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2700 ' ORDER BY weight ASC',
2704 description => &{$escape}($self->mt('Usage Summary')),
2708 foreach my $class (@classes) {
2710 'description' => &{$escape}($class->classname),
2711 'amount' => sprintf('%.2f', $class->amount),
2712 'usage_classnum' => $class->classnum,
2713 'section' => $section,
2719 sub _items_previous {
2721 my $conf = $self->conf;
2722 my $cust_main = $self->cust_main;
2723 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2725 foreach ( @pr_cust_bill ) {
2726 my $date = $conf->exists('invoice_show_prior_due_date')
2727 ? 'due '. $_->due_date2str('short')
2728 : $self->time2str_local('short', $_->_date);
2730 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2731 #'pkgpart' => 'N/A',
2733 'amount' => sprintf("%.2f", $_->owed),
2739 # 'description' => 'Previous Balance',
2740 # #'pkgpart' => 'N/A',
2741 # 'pkgnum' => 'N/A',
2742 # 'amount' => sprintf("%10.2f", $pr_total ),
2743 # 'ext_description' => [ map {
2744 # "Invoice ". $_->invnum.
2745 # " (". time2str("%x",$_->_date). ") ".
2746 # sprintf("%10.2f", $_->owed)
2747 # } @pr_cust_bill ],
2752 sub _items_credits {
2753 my( $self, %opt ) = @_;
2754 my $trim_len = $opt{'trim_len'} || 60;
2759 if ( $self->conf->exists('previous_balance-payments_since') ) {
2760 if ( $opt{'template'} eq 'statement' ) {
2761 # then the current bill is a "statement" (i.e. an invoice sent as
2762 # a payment receipt)
2763 # and in that case we want to see payments on or after THIS invoice
2764 @objects = qsearch('cust_credit', {
2765 'custnum' => $self->custnum,
2766 '_date' => {op => '>=', value => $self->_date},
2770 $date = $self->previous_bill->_date if $self->previous_bill;
2771 @objects = qsearch('cust_credit', {
2772 'custnum' => $self->custnum,
2773 '_date' => {op => '>=', value => $date},
2777 @objects = $self->cust_credited;
2780 foreach my $obj ( @objects ) {
2781 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2783 my $reason = substr($cust_credit->reason, 0, $trim_len);
2784 $reason .= '...' if length($reason) < length($cust_credit->reason);
2785 $reason = " ($reason) " if $reason;
2788 #'description' => 'Credit ref\#'. $_->crednum.
2789 # " (". time2str("%x",$_->cust_credit->_date) .")".
2791 'description' => $self->mt('Credit applied').' '.
2792 $self->time2str_local('short', $obj->_date). $reason,
2793 'amount' => sprintf("%.2f",$obj->amount),
2801 sub _items_payments {
2806 my $detailed = $self->conf->exists('invoice_payment_details');
2808 if ( $self->conf->exists('previous_balance-payments_since') ) {
2809 # then show payments dated on/after the previous bill...
2810 if ( $opt{'template'} eq 'statement' ) {
2811 # then the current bill is a "statement" (i.e. an invoice sent as
2812 # a payment receipt)
2813 # and in that case we want to see payments on or after THIS invoice
2814 @objects = qsearch('cust_pay', {
2815 'custnum' => $self->custnum,
2816 '_date' => {op => '>=', value => $self->_date},
2819 # the normal case: payments on or after the previous invoice
2821 $date = $self->previous_bill->_date if $self->previous_bill;
2822 @objects = qsearch('cust_pay', {
2823 'custnum' => $self->custnum,
2824 '_date' => {op => '>=', value => $date},
2826 # and before the current bill...
2827 @objects = grep { $_->_date < $self->_date } @objects;
2830 @objects = $self->cust_bill_pay;
2833 foreach my $obj (@objects) {
2834 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2835 my $desc = $self->mt('Payment received').' '.
2836 $self->time2str_local('short', $cust_pay->_date );
2837 $desc .= $self->mt(' via ') .
2838 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2842 'description' => $desc,
2843 'amount' => sprintf("%.2f", $obj->amount )
2851 =item call_details [ OPTION => VALUE ... ]
2853 Returns an array of CSV strings representing the call details for this invoice
2854 The only option available is the boolean prepend_billed_number
2859 my ($self, %opt) = @_;
2861 my $format_function = sub { shift };
2863 if ($opt{prepend_billed_number}) {
2864 $format_function = sub {
2868 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2873 my @details = map { $_->details( 'format_function' => $format_function,
2874 'escape_function' => sub{ return() },
2878 $self->cust_bill_pkg;
2879 my $header = $details[0];
2880 ( $header, grep { $_ ne $header } @details );
2890 =item process_reprint
2894 sub process_reprint {
2895 process_re_X('print', @_);
2898 =item process_reemail
2902 sub process_reemail {
2903 process_re_X('email', @_);
2911 process_re_X('fax', @_);
2919 process_re_X('ftp', @_);
2926 sub process_respool {
2927 process_re_X('spool', @_);
2930 use Storable qw(thaw);
2934 my( $method, $job ) = ( shift, shift );
2935 warn "$me process_re_X $method for job $job\n" if $DEBUG;
2937 my $param = thaw(decode_base64(shift));
2938 warn Dumper($param) if $DEBUG;
2949 # spool_invoice ftp_invoice fax_invoice print_invoice
2950 my($method, $job, %param ) = @_;
2952 warn "re_X $method for job $job with param:\n".
2953 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
2956 #some false laziness w/search/cust_bill.html
2958 my $orderby = 'ORDER BY cust_bill._date';
2960 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
2962 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
2964 my @cust_bill = qsearch( {
2965 #'select' => "cust_bill.*",
2966 'table' => 'cust_bill',
2967 'addl_from' => $addl_from,
2969 'extra_sql' => $extra_sql,
2970 'order_by' => $orderby,
2974 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
2976 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
2979 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
2980 foreach my $cust_bill ( @cust_bill ) {
2981 $cust_bill->$method();
2983 if ( $job ) { #progressbar foo
2985 if ( time - $min_sec > $last ) {
2986 my $error = $job->update_statustext(
2987 int( 100 * $num / scalar(@cust_bill) )
2989 die $error if $error;
3000 =head1 CLASS METHODS
3006 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3011 my ($class, $start, $end) = @_;
3013 $class->paid_sql($start, $end). ' - '.
3014 $class->credited_sql($start, $end);
3019 Returns an SQL fragment to retreive the net amount (charged minus credited).
3024 my ($class, $start, $end) = @_;
3025 'charged - '. $class->credited_sql($start, $end);
3030 Returns an SQL fragment to retreive the amount paid against this invoice.
3035 my ($class, $start, $end) = @_;
3036 $start &&= "AND cust_bill_pay._date <= $start";
3037 $end &&= "AND cust_bill_pay._date > $end";
3038 $start = '' unless defined($start);
3039 $end = '' unless defined($end);
3040 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3041 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3046 Returns an SQL fragment to retreive the amount credited against this invoice.
3051 my ($class, $start, $end) = @_;
3052 $start &&= "AND cust_credit_bill._date <= $start";
3053 $end &&= "AND cust_credit_bill._date > $end";
3054 $start = '' unless defined($start);
3055 $end = '' unless defined($end);
3056 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3057 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3062 Returns an SQL fragment to retrieve the due date of an invoice.
3063 Currently only supported on PostgreSQL.
3068 die "don't use: doesn't account for agent-specific invoice_default_terms";
3070 #we're passed a $conf but not a specific customer (that's in the query), so
3071 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3072 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3075 my $conf = new FS::Conf;
3079 cust_bill.invoice_terms,
3080 cust_main.invoice_terms,
3081 \''.($conf->config('invoice_default_terms') || '').'\'
3082 ), E\'Net (\\\\d+)\'
3084 ) * 86400 + cust_bill._date'
3095 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3096 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base