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 : '';
218 my $reprocess_cdrs = scalar(@_) ? shift : '';
220 local $SIG{HUP} = 'IGNORE';
221 local $SIG{INT} = 'IGNORE';
222 local $SIG{QUIT} = 'IGNORE';
223 local $SIG{TERM} = 'IGNORE';
224 local $SIG{TSTP} = 'IGNORE';
225 local $SIG{PIPE} = 'IGNORE';
227 my $oldAutoCommit = $FS::UID::AutoCommit;
228 local $FS::UID::AutoCommit = 0;
231 my $cust_bill_void = new FS::cust_bill_void ( {
232 map { $_ => $self->get($_) } $self->fields
234 $cust_bill_void->reason($reason);
235 my $error = $cust_bill_void->insert;
237 $dbh->rollback if $oldAutoCommit;
241 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
242 my $error = $cust_bill_pkg->void($reason, $reprocess_cdrs);
244 $dbh->rollback if $oldAutoCommit;
249 $error = $self->delete;
251 $dbh->rollback if $oldAutoCommit;
255 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
263 This method now works but you probably shouldn't use it. Instead, apply a
264 credit against the invoice, or use the new void method.
266 Using this method to delete invoices outright is really, really bad. There
267 would be no record you ever posted this invoice, and there are no check to
268 make sure charged = 0 or that there are no associated cust_bill_pkg records.
270 Really, don't use it.
276 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
278 local $SIG{HUP} = 'IGNORE';
279 local $SIG{INT} = 'IGNORE';
280 local $SIG{QUIT} = 'IGNORE';
281 local $SIG{TERM} = 'IGNORE';
282 local $SIG{TSTP} = 'IGNORE';
283 local $SIG{PIPE} = 'IGNORE';
285 my $oldAutoCommit = $FS::UID::AutoCommit;
286 local $FS::UID::AutoCommit = 0;
289 foreach my $table (qw(
300 foreach my $linked ( $self->$table() ) {
301 my $error = $linked->delete;
303 $dbh->rollback if $oldAutoCommit;
310 my $error = $self->SUPER::delete(@_);
312 $dbh->rollback if $oldAutoCommit;
316 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
322 =item replace [ OLD_RECORD ]
324 You can, but probably shouldn't modify invoices...
326 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
327 supplied, replaces this record. If there is an error, returns the error,
328 otherwise returns false.
332 #replace can be inherited from Record.pm
334 # replace_check is now the preferred way to #implement replace data checks
335 # (so $object->replace() works without an argument)
338 my( $new, $old ) = ( shift, shift );
339 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
340 #return "Can't change _date!" unless $old->_date eq $new->_date;
341 return "Can't change _date" unless $old->_date == $new->_date;
342 return "Can't change charged" unless $old->charged == $new->charged
343 || $old->charged == 0
344 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
350 =item add_cc_surcharge
356 sub add_cc_surcharge {
357 my ($self, $pkgnum, $amount) = (shift, shift, shift);
360 my $cust_bill_pkg = new FS::cust_bill_pkg({
361 'invnum' => $self->invnum,
365 $error = $cust_bill_pkg->insert;
366 return $error if $error;
368 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
369 $self->charged($self->charged+$amount);
370 $error = $self->replace;
371 return $error if $error;
373 $self->apply_payments_and_credits;
379 Checks all fields to make sure this is a valid invoice. If there is an error,
380 returns the error, otherwise returns false. Called by the insert and replace
389 $self->ut_numbern('invnum')
390 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
391 || $self->ut_numbern('_date')
392 || $self->ut_money('charged')
393 || $self->ut_numbern('printed')
394 || $self->ut_enum('closed', [ '', 'Y' ])
395 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
396 || $self->ut_numbern('agent_invid') #varchar?
398 return $error if $error;
400 $self->_date(time) unless $self->_date;
402 $self->printed(0) if $self->printed eq '';
409 Returns the displayed invoice number for this invoice: agent_invid if
410 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
416 if ( $self->agent_invid
417 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
418 return $self->agent_invid;
420 return $self->invnum;
426 Returns the customer's last invoice before this one.
432 if ( !$self->get('previous_bill') ) {
433 $self->set('previous_bill', qsearchs({
434 'table' => 'cust_bill',
435 'hashref' => { 'custnum' => $self->custnum,
436 '_date' => { op=>'<', value=>$self->_date } },
437 'order_by' => 'ORDER BY _date DESC LIMIT 1',
440 $self->get('previous_bill');
445 Returns a list consisting of the total previous balance for this customer,
446 followed by the previous outstanding invoices (as FS::cust_bill objects also).
452 # simple memoize; we use this a lot
453 if (!$self->get('previous')) {
455 my @cust_bill = sort { $a->_date <=> $b->_date }
456 grep { $_->owed != 0 }
457 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
458 #'_date' => { op=>'<', value=>$self->_date },
459 'invnum' => { op=>'<', value=>$self->invnum },
462 foreach ( @cust_bill ) { $total += $_->owed; }
463 $self->set('previous', [$total, @cust_bill]);
465 return @{ $self->get('previous') };
468 =item enable_previous
470 Whether to show the 'Previous Charges' section when printing this invoice.
471 The negation of the 'disable_previous_balance' config setting.
475 sub enable_previous {
477 my $agentnum = $self->cust_main->agentnum;
478 !$self->conf->exists('disable_previous_balance', $agentnum);
483 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
491 'select' => 'cust_bill_pkg.*, pkg_category.categoryname',
492 'table' => 'cust_bill_pkg',
493 'addl_from' => ' LEFT JOIN cust_pkg USING ( pkgnum ) '.
494 ' LEFT JOIN part_pkg USING ( pkgpart ) '.
495 ' LEFT JOIN pkg_class USING ( classnum ) '.
496 ' LEFT JOIN pkg_category USING ( categorynum ) ',
497 'hashref' => { 'invnum' => $self->invnum },
498 'order_by' => 'ORDER BY billpkgnum',
503 =item cust_bill_pkg_pkgnum PKGNUM
505 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
510 sub cust_bill_pkg_pkgnum {
511 my( $self, $pkgnum ) = @_;
513 { 'table' => 'cust_bill_pkg',
514 'hashref' => { 'invnum' => $self->invnum,
517 'order_by' => 'ORDER BY billpkgnum',
524 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
531 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
532 $self->cust_bill_pkg;
534 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
539 Returns true if any of the packages (or their definitions) corresponding to the
540 line items for this invoice have the no_auto flag set.
546 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
549 =item open_cust_bill_pkg
551 Returns the open line items for this invoice.
553 Note that cust_bill_pkg with both setup and recur fees are returned as two
554 separate line items, each with only one fee.
558 # modeled after cust_main::open_cust_bill
559 sub open_cust_bill_pkg {
562 # grep { $_->owed > 0 } $self->cust_bill_pkg
564 my %other = ( 'recur' => 'setup',
565 'setup' => 'recur', );
567 foreach my $field ( qw( recur setup )) {
568 push @open, map { $_->set( $other{$field}, 0 ); $_; }
569 grep { $_->owed($field) > 0 }
570 $self->cust_bill_pkg;
576 =item cust_bill_event
578 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
582 sub cust_bill_event {
584 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
587 =item num_cust_bill_event
589 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
593 sub num_cust_bill_event {
596 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
597 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
598 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
599 $sth->fetchrow_arrayref->[0];
604 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
608 #false laziness w/cust_pkg.pm
612 'table' => 'cust_event',
613 'addl_from' => 'JOIN part_event USING ( eventpart )',
614 'hashref' => { 'tablenum' => $self->invnum },
615 'extra_sql' => " AND eventtable = 'cust_bill' ",
621 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
625 #false laziness w/cust_pkg.pm
629 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
630 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
631 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
632 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
633 $sth->fetchrow_arrayref->[0];
638 Returns the customer (see L<FS::cust_main>) for this invoice.
644 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
647 =item cust_suspend_if_balance_over AMOUNT
649 Suspends the customer associated with this invoice if the total amount owed on
650 this invoice and all older invoices is greater than the specified amount.
652 Returns a list: an empty list on success or a list of errors.
656 sub cust_suspend_if_balance_over {
657 my( $self, $amount ) = ( shift, shift );
658 my $cust_main = $self->cust_main;
659 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
662 $cust_main->suspend(@_);
668 Depreciated. See the cust_credited method.
670 #Returns a list consisting of the total previous credited (see
671 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
672 #outstanding credits (FS::cust_credit objects).
678 croak "FS::cust_bill->cust_credit depreciated; see ".
679 "FS::cust_bill->cust_credit_bill";
682 #my @cust_credit = sort { $a->_date <=> $b->_date }
683 # grep { $_->credited != 0 && $_->_date < $self->_date }
684 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
686 #foreach (@cust_credit) { $total += $_->credited; }
687 #$total, @cust_credit;
692 Depreciated. See the cust_bill_pay method.
694 #Returns all payments (see L<FS::cust_pay>) for this invoice.
700 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
702 #sort { $a->_date <=> $b->_date }
703 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
709 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
712 sub cust_bill_pay_batch {
714 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
719 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
725 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
726 sort { $a->_date <=> $b->_date }
727 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
732 =item cust_credit_bill
734 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
740 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
741 sort { $a->_date <=> $b->_date }
742 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
746 sub cust_credit_bill {
747 shift->cust_credited(@_);
750 #=item cust_bill_pay_pkgnum PKGNUM
752 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
753 #with matching pkgnum.
757 #sub cust_bill_pay_pkgnum {
758 # my( $self, $pkgnum ) = @_;
759 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
760 # sort { $a->_date <=> $b->_date }
761 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
762 # 'pkgnum' => $pkgnum,
767 =item cust_bill_pay_pkg PKGNUM
769 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
770 applied against the matching pkgnum.
774 sub cust_bill_pay_pkg {
775 my( $self, $pkgnum ) = @_;
778 'select' => 'cust_bill_pay_pkg.*',
779 'table' => 'cust_bill_pay_pkg',
780 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
781 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
782 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
783 " AND cust_bill_pkg.pkgnum = $pkgnum",
788 #=item cust_credited_pkgnum PKGNUM
790 #=item cust_credit_bill_pkgnum PKGNUM
792 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
793 #with matching pkgnum.
797 #sub cust_credited_pkgnum {
798 # my( $self, $pkgnum ) = @_;
799 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
800 # sort { $a->_date <=> $b->_date }
801 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
802 # 'pkgnum' => $pkgnum,
807 #sub cust_credit_bill_pkgnum {
808 # shift->cust_credited_pkgnum(@_);
811 =item cust_credit_bill_pkg PKGNUM
813 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
814 applied against the matching pkgnum.
818 sub cust_credit_bill_pkg {
819 my( $self, $pkgnum ) = @_;
822 'select' => 'cust_credit_bill_pkg.*',
823 'table' => 'cust_credit_bill_pkg',
824 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
825 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
826 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
827 " AND cust_bill_pkg.pkgnum = $pkgnum",
832 =item cust_bill_batch
834 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
838 sub cust_bill_batch {
840 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
845 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
846 hash keyed by term length.
852 FS::discount_plan->all($self);
857 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
864 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
866 foreach (@taxlines) { $total += $_->setup; }
872 Returns the amount owed (still outstanding) on this invoice, which is charged
873 minus all payment applications (see L<FS::cust_bill_pay>) and credit
874 applications (see L<FS::cust_credit_bill>).
880 my $balance = $self->charged;
881 $balance -= $_->amount foreach ( $self->cust_bill_pay );
882 $balance -= $_->amount foreach ( $self->cust_credited );
883 $balance = sprintf( "%.2f", $balance);
884 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
889 my( $self, $pkgnum ) = @_;
891 #my $balance = $self->charged;
893 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
895 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
896 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
898 $balance = sprintf( "%.2f", $balance);
899 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
905 Returns true if this invoice should be hidden. See the
906 selfservice-hide_invoices-taxclass configuraiton setting.
912 my $conf = $self->conf;
913 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
915 my @cust_bill_pkg = $self->cust_bill_pkg;
916 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
917 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
920 =item apply_payments_and_credits [ OPTION => VALUE ... ]
922 Applies unapplied payments and credits to this invoice.
923 Payments with the no_auto_apply flag set will not be applied.
925 A hash of optional arguments may be passed. Currently "manual" is supported.
926 If true, a payment receipt is sent instead of a statement when
927 'payment_receipt_email' configuration option is set.
929 If there is an error, returns the error, otherwise returns false.
933 sub apply_payments_and_credits {
934 my( $self, %options ) = @_;
935 my $conf = $self->conf;
937 local $SIG{HUP} = 'IGNORE';
938 local $SIG{INT} = 'IGNORE';
939 local $SIG{QUIT} = 'IGNORE';
940 local $SIG{TERM} = 'IGNORE';
941 local $SIG{TSTP} = 'IGNORE';
942 local $SIG{PIPE} = 'IGNORE';
944 my $oldAutoCommit = $FS::UID::AutoCommit;
945 local $FS::UID::AutoCommit = 0;
948 $self->select_for_update; #mutex
950 my @payments = grep { $_->unapplied > 0 }
951 grep { !$_->no_auto_apply }
952 $self->cust_main->cust_pay;
953 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
955 if ( $conf->exists('pkg-balances') ) {
956 # limit @payments & @credits to those w/ a pkgnum grepped from $self
957 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
958 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
959 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
962 while ( $self->owed > 0 and ( @payments || @credits ) ) {
965 if ( @payments && @credits ) {
967 #decide which goes first by weight of top (unapplied) line item
969 my @open_lineitems = $self->open_cust_bill_pkg;
972 max( map { $_->part_pkg->pay_weight || 0 }
977 my $max_credit_weight =
978 max( map { $_->part_pkg->credit_weight || 0 }
984 #if both are the same... payments first? it has to be something
985 if ( $max_pay_weight >= $max_credit_weight ) {
991 } elsif ( @payments ) {
993 } elsif ( @credits ) {
996 die "guru meditation #12 and 35";
1000 if ( $app eq 'pay' ) {
1002 my $payment = shift @payments;
1003 $unapp_amount = $payment->unapplied;
1004 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
1005 $app->pkgnum( $payment->pkgnum )
1006 if $conf->exists('pkg-balances') && $payment->pkgnum;
1008 } elsif ( $app eq 'credit' ) {
1010 my $credit = shift @credits;
1011 $unapp_amount = $credit->credited;
1012 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1013 $app->pkgnum( $credit->pkgnum )
1014 if $conf->exists('pkg-balances') && $credit->pkgnum;
1017 die "guru meditation #12 and 35";
1021 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1022 warn "owed_pkgnum ". $app->pkgnum;
1023 $owed = $self->owed_pkgnum($app->pkgnum);
1025 $owed = $self->owed;
1027 next unless $owed > 0;
1029 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1030 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1032 $app->invnum( $self->invnum );
1034 my $error = $app->insert(%options);
1036 $dbh->rollback if $oldAutoCommit;
1037 return "Error inserting ". $app->table. " record: $error";
1039 die $error if $error;
1043 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1050 Sends this invoice to the destinations configured for this customer: sends
1051 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1053 Options can be passed as a hashref. Positional parameters are no longer
1056 I<template>: a suffix for alternate invoices
1058 I<agentnum>: obsolete, now does nothing.
1060 I<from> overrides the default email invoice From: address.
1062 I<amount>: obsolete, does nothing
1064 I<notice_name> overrides "Invoice" as the name of the sent document
1065 (templates from 10/2009 or newer required).
1067 I<lpr> overrides the system 'lpr' option as the command to print a document
1068 from standard input.
1074 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1075 my $conf = $self->conf;
1077 my $cust_main = $self->cust_main;
1079 my @invoicing_list = $cust_main->invoicing_list;
1082 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1083 && ! $cust_main->invoice_noemail;
1086 if grep { $_ eq 'POST' } @invoicing_list; #postal
1088 #this has never been used post-$ORIGINAL_ISP afaik
1089 $self->fax_invoice($opt)
1090 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1098 my $opt = shift || {};
1099 if ($opt and !ref($opt)) {
1100 die ref($self). '->email called with positional parameters';
1103 my $conf = $self->conf;
1105 my $from = delete $opt->{from};
1107 # this is where we set the From: address
1108 $from ||= $self->_agent_invoice_from || #XXX should go away
1109 $conf->invoice_from_full( $self->cust_main->agentnum );
1111 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1113 if ( ! @invoicing_list ) { #no recipients
1114 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1115 die 'No recipients for customer #'. $self->custnum;
1117 #default: better to notify this person than silence
1118 @invoicing_list = ($from);
1122 $self->SUPER::email( {
1124 'to' => \@invoicing_list,
1130 #this stays here for now because its explicitly used as
1131 # FS::cust_bill::queueable_email
1132 sub queueable_email {
1135 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1136 or die "invalid invoice number: " . $opt{invnum};
1138 $self->set('mode', $opt{mode})
1141 my %args = map {$_ => $opt{$_}}
1143 qw( from notice_name no_coupon template );
1145 my $error = $self->email( \%args );
1146 die $error if $error;
1152 my $conf = $self->conf;
1154 #my $template = scalar(@_) ? shift : '';
1157 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1160 my $cust_main = $self->cust_main;
1161 my $name = $cust_main->name;
1162 my $name_short = $cust_main->name_short;
1163 my $invoice_number = $self->invnum;
1164 my $invoice_date = $self->_date_pretty;
1166 eval qq("$subject");
1169 =item lpr_data HASHREF
1171 Returns the postscript or plaintext for this invoice as an arrayref.
1173 Options must be passed as a hashref. Positional parameters are no longer
1176 I<template>, if specified, is the name of a suffix for alternate invoices.
1178 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1184 my $conf = $self->conf;
1185 my $opt = shift || {};
1186 if ($opt and !ref($opt)) {
1187 # nobody does this anyway
1188 die "FS::cust_bill::lpr_data called with positional parameters";
1191 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1192 [ $self->$method( $opt ) ];
1197 Prints this invoice.
1199 Options must be passed as a hashref.
1201 I<template>, if specified, is the name of a suffix for alternate invoices.
1203 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1209 return if $self->hide;
1210 my $conf = $self->conf;
1211 my $opt = shift || {};
1212 if ($opt and !ref($opt)) {
1213 die "FS::cust_bill::print called with positional parameters";
1216 my $lpr = delete $opt->{lpr};
1217 if($conf->exists('invoice_print_pdf')) {
1218 # Add the invoice to the current batch.
1219 $self->batch_invoice($opt);
1223 $self->lpr_data($opt),
1224 'agentnum' => $self->cust_main->agentnum,
1230 =item fax_invoice HASHREF
1234 Options must be passed as a hashref.
1236 I<template>, if specified, is the name of a suffix for alternate invoices.
1238 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1244 return if $self->hide;
1245 my $conf = $self->conf;
1246 my $opt = shift || {};
1247 if ($opt and !ref($opt)) {
1248 die "FS::cust_bill::fax_invoice called with positional parameters";
1251 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1252 unless $conf->exists('invoice_latex');
1254 my $dialstring = $self->cust_main->getfield('fax');
1257 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1258 'dialstring' => $dialstring,
1260 die $error if $error;
1264 =item batch_invoice [ HASHREF ]
1266 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1267 isn't an open batch, one will be created.
1269 HASHREF may contain any options to be passed to C<print_pdf>.
1274 my ($self, $opt) = @_;
1275 my $bill_batch = $self->get_open_bill_batch;
1276 my $cust_bill_batch = FS::cust_bill_batch->new({
1277 batchnum => $bill_batch->batchnum,
1278 invnum => $self->invnum,
1280 if ( $self->mode ) {
1281 $opt->{mode} ||= $self->mode;
1282 $opt->{mode} = $opt->{mode}->modenum if ref $opt->{mode};
1284 return $cust_bill_batch->insert($opt);
1287 =item get_open_batch
1289 Returns the currently open batch as an FS::bill_batch object, creating a new
1290 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1295 sub get_open_bill_batch {
1297 my $conf = $self->conf;
1298 my $hashref = { status => 'O' };
1299 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1300 ? $self->cust_main->agentnum
1302 my $batch = qsearchs('bill_batch', $hashref);
1303 return $batch if $batch;
1304 $batch = FS::bill_batch->new($hashref);
1305 my $error = $batch->insert;
1306 die $error if $error;
1310 =item ftp_invoice [ TEMPLATENAME ]
1312 Sends this invoice data via FTP.
1314 TEMPLATENAME is unused?
1320 my $conf = $self->conf;
1321 my $template = scalar(@_) ? shift : '';
1324 'protocol' => 'ftp',
1325 'server' => $conf->config('cust_bill-ftpserver'),
1326 'username' => $conf->config('cust_bill-ftpusername'),
1327 'password' => $conf->config('cust_bill-ftppassword'),
1328 'dir' => $conf->config('cust_bill-ftpdir'),
1329 'format' => $conf->config('cust_bill-ftpformat'),
1333 =item spool_invoice [ TEMPLATENAME ]
1335 Spools this invoice data (see L<FS::spool_csv>)
1337 TEMPLATENAME is unused?
1343 my $conf = $self->conf;
1344 my $template = scalar(@_) ? shift : '';
1347 'format' => $conf->config('cust_bill-spoolformat'),
1348 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1352 =item send_csv OPTION => VALUE, ...
1354 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1358 protocol - currently only "ftp"
1364 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1365 and YYMMDDHHMMSS is a timestamp.
1367 See L</print_csv> for a description of the output format.
1372 my($self, %opt) = @_;
1376 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1377 mkdir $spooldir, 0700 unless -d $spooldir;
1379 # don't localize dates here, they're a defined format
1380 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1381 my $file = "$spooldir/$tracctnum.csv";
1383 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1385 open(CSV, ">$file") or die "can't open $file: $!";
1393 if ( $opt{protocol} eq 'ftp' ) {
1394 eval "use Net::FTP;";
1396 $net = Net::FTP->new($opt{server}) or die @$;
1398 die "unknown protocol: $opt{protocol}";
1401 $net->login( $opt{username}, $opt{password} )
1402 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1404 $net->binary or die "can't set binary mode";
1406 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1408 $net->put($file) or die "can't put $file: $!";
1418 Spools CSV invoice data.
1424 =item format - any of FS::Misc::::Invoicing::spool_formats
1426 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1427 customer has the corresponding invoice destinations set (see
1428 L<FS::cust_main_invoice>).
1430 =item agent_spools - if set to a true value, will spool to per-agent files
1431 rather than a single global file
1433 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1434 append to that spool. L<FS::Cron::upload> will then send the spool file to
1437 =item balanceover - if set, only spools the invoice if the total amount owed on
1438 this invoice and all older invoices is greater than the specified amount.
1440 =item time - the "current time". Controls the printing of past due messages
1448 my($self, %opt) = @_;
1450 my $time = $opt{'time'} || time;
1451 my $cust_main = $self->cust_main;
1453 if ( $opt{'dest'} ) {
1454 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1455 $cust_main->invoicing_list;
1456 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1457 || ! keys %invoicing_list;
1460 if ( $opt{'balanceover'} ) {
1462 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1465 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1466 mkdir $spooldir, 0700 unless -d $spooldir;
1468 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1471 if ( $opt{'agent_spools'} ) {
1472 $file = 'agentnum'.$cust_main->agentnum;
1477 if ( $opt{'upload_targetnum'} ) {
1478 $spooldir .= '/target'.$opt{'upload_targetnum'};
1479 mkdir $spooldir, 0700 unless -d $spooldir;
1480 } # otherwise it just goes into export.xxx/cust_bill
1482 if ( lc($opt{'format'}) eq 'billco' ) {
1486 $file = "$spooldir/$file.csv";
1488 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1490 open(CSV, ">>$file") or die "can't open $file: $!";
1491 flock(CSV, LOCK_EX);
1496 if ( lc($opt{'format'}) eq 'billco' ) {
1498 flock(CSV, LOCK_UN);
1501 $file =~ s/-header.csv$/-detail.csv/;
1503 open(CSV,">>$file") or die "can't open $file: $!";
1504 flock(CSV, LOCK_EX);
1508 print CSV $detail if defined($detail);
1510 flock(CSV, LOCK_UN);
1517 =item print_csv OPTION => VALUE, ...
1519 Returns CSV data for this invoice.
1523 format - 'default', 'billco', 'oneline', 'bridgestone'
1525 Returns a list consisting of two scalars. The first is a single line of CSV
1526 header information for this invoice. The second is one or more lines of CSV
1527 detail information for this invoice.
1529 If I<format> is not specified or "default", the fields of the CSV file are as
1532 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1533 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1537 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1539 B<record_type> is C<cust_bill> for the initial header line only. The
1540 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1541 fields are filled in.
1543 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1544 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1547 =item invnum - invoice number
1549 =item custnum - customer number
1551 =item _date - invoice date
1553 =item charged - total invoice amount
1555 =item first - customer first name
1557 =item last - customer first name
1559 =item company - company name
1561 =item address1 - address line 1
1563 =item address2 - address line 1
1573 =item pkg - line item description
1575 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1577 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1579 =item sdate - start date for recurring fee
1581 =item edate - end date for recurring fee
1585 If I<format> is "billco", the fields of the header CSV file are as follows:
1587 +-------------------------------------------------------------------+
1588 | FORMAT HEADER FILE |
1589 |-------------------------------------------------------------------|
1590 | Field | Description | Name | Type | Width |
1591 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1592 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1593 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1594 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1595 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1596 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1597 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1598 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1599 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1600 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1601 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1602 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1603 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1604 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1605 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1606 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1607 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1608 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1609 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1610 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1611 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1612 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1613 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1614 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1615 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1616 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1617 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1618 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1619 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1620 +-------+-------------------------------+------------+------+-------+
1622 If I<format> is "billco", the fields of the detail CSV file are as follows:
1624 FORMAT FOR DETAIL FILE
1626 Field | Description | Name | Type | Width
1627 1 | N/A-Leave Empty | RC | CHAR | 2
1628 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1629 3 | Account Number | TRACCTNUM | CHAR | 15
1630 4 | Invoice Number | TRINVOICE | CHAR | 15
1631 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1632 6 | Transaction Detail | DETAILS | CHAR | 100
1633 7 | Amount | AMT | NUM* | 9
1634 8 | Line Format Control** | LNCTRL | CHAR | 2
1635 9 | Grouping Code | GROUP | CHAR | 2
1636 10 | User Defined | ACCT CODE | CHAR | 15
1638 If format is 'oneline', there is no detail file. Each invoice has a
1639 header line only, with the fields:
1641 Agent number, agent name, customer number, first name, last name, address
1642 line 1, address line 2, city, state, zip, invoice date, invoice number,
1643 amount charged, amount due, previous balance, due date.
1645 and then, for each line item, three columns containing the package number,
1646 description, and amount.
1648 If format is 'bridgestone', there is no detail file. Each invoice has a
1649 header line with the following fields in a fixed-width format:
1651 Customer number (in display format), date, name (first last), company,
1652 address 1, address 2, city, state, zip.
1654 This is a mailing list format, and has no per-invoice fields. To avoid
1655 sending redundant notices, the spooling event should have a "once" or
1656 "once_percust_every" condition.
1661 my($self, %opt) = @_;
1663 eval "use Text::CSV_XS";
1666 my $cust_main = $self->cust_main;
1668 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1669 my $format = lc($opt{'format'});
1671 my $time = $opt{'time'} || time;
1673 my $tracctnum = ''; #leaking out from billco-specific sections :/
1674 if ( $format eq 'billco' ) {
1677 $self->conf->config('billco-account_num', $cust_main->agentnum);
1679 $tracctnum = $account_num eq 'display_custnum'
1680 ? $cust_main->display_custnum
1681 : $opt{'tracctnum'};
1684 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1686 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1688 my( $previous_balance, @unused ) = $self->previous; #previous balance
1690 my $pmt_cr_applied = 0;
1691 $pmt_cr_applied += $_->{'amount'}
1692 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1694 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1697 '', # 1 | N/A-Leave Empty CHAR 2
1698 '', # 2 | N/A-Leave Empty CHAR 15
1699 $tracctnum, # 3 | Transaction Account No CHAR 15
1700 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1701 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1702 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1703 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1704 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1705 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1706 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1707 '', # 10 | Ancillary Billing Information CHAR 30
1708 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1709 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1712 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1715 $duedate, # 14 | Bill Due Date CHAR 10
1717 $previous_balance, # 15 | Previous Balance NUM* 9
1718 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1719 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1720 $totaldue, # 18 | Total Amt Due NUM* 9
1721 $totaldue, # 19 | Total Amt Due NUM* 9
1722 '', # 20 | 30 Day Aging NUM* 9
1723 '', # 21 | 60 Day Aging NUM* 9
1724 '', # 22 | 90 Day Aging NUM* 9
1725 'N', # 23 | Y/N CHAR 1
1726 '', # 24 | Remittance automation CHAR 100
1727 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1728 $self->custnum, # 26 | Customer Reference Number CHAR 15
1729 '0', # 27 | Federal Tax*** NUM* 9
1730 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1731 '0', # 29 | Other Taxes & Fees*** NUM* 9
1734 } elsif ( $format eq 'oneline' ) { #name
1736 my ($previous_balance) = $self->previous;
1737 $previous_balance = sprintf('%.2f', $previous_balance);
1738 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1744 $self->_items_pkg, #_items_nontax? no sections or anything
1749 $cust_main->agentnum,
1750 $cust_main->agent->agent,
1754 $cust_main->company,
1755 $cust_main->address1,
1756 $cust_main->address2,
1762 time2str("%x", $self->_date),
1767 $self->due_date2str("%x"),
1772 } elsif ( $format eq 'bridgestone' ) {
1774 # bypass the CSV stuff and just return this
1775 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1776 my $zip = $cust_main->zip;
1778 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1782 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1784 $cust_main->display_custnum,
1786 uc(substr($cust_main->contact_firstlast,0,30)),
1787 uc(substr($cust_main->company ,0,30)),
1788 uc(substr($cust_main->address1 ,0,30)),
1789 uc(substr($cust_main->address2 ,0,30)),
1790 uc(substr($cust_main->city ,0,20)),
1791 uc($cust_main->state),
1797 } elsif ( $format eq 'ics' ) {
1799 my $bill = $cust_main->bill_location;
1800 my $zip = $bill->zip;
1804 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1809 # minor false laziness with print_generic
1810 my ($previous_balance) = $self->previous;
1811 my $balance_due = $self->owed + $previous_balance;
1812 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1813 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1816 if ( $self->due_date and $time >= $self->due_date ) {
1817 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1821 my $header = sprintf(
1822 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1823 $cust_main->display_custnum, #BID
1824 uc($cust_main->first), #FNAME
1825 uc($cust_main->last), #LNAME
1826 '00', #BATCH, should this ever be anything else?
1827 uc($cust_main->company), #COMP
1828 uc($bill->address1), #STREET1
1829 uc($bill->address2), #STREET2
1830 uc($bill->city), #CITY
1831 uc($bill->state), #STATE
1834 time2str('%Y%m%d', $self->_date), #BILL_DATE
1835 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1836 ( map {sprintf('%0.2f', $_)}
1837 $balance_due, #AMNT_DUE
1838 $previous_balance, #PREV_BAL
1839 $payment_total, #PYMT_RCVD
1840 $credit_total, #CREDITS
1841 $previous_balance, #BEG_BAL--is this correct?
1842 $self->charged, #NEW_CHRG
1845 $past_due, #PAST_MSG
1849 my %svc_class = ('' => ''); # maybe cache this more persistently?
1851 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1853 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1854 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1858 my @dates = ( $self->_date, undef );
1859 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1860 $dates[1] = $prev->sdate; #questionable
1863 # generate an 01 detail for each service
1864 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1865 foreach my $cust_svc ( @svcs ) {
1866 $show_pkgnum = ''; # hide it if we're showing svcnums
1868 my $svcpart = $cust_svc->svcpart;
1869 if (!exists($svc_class{$svcpart})) {
1870 my $classnum = $cust_svc->part_svc->classnum;
1871 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1873 $svc_class{$svcpart} = $part_svc_class ?
1874 $part_svc_class->classname :
1878 my @h_label = $cust_svc->label(@dates, 'I');
1879 push @details, sprintf('01%-9s%-20s%-47s',
1881 $svc_class{$svcpart},
1884 } #foreach $cust_svc
1887 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1888 if ($cust_bill_pkg->recur > 0) {
1889 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1890 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1892 push @details, sprintf('02%-6s%-60s%-10s',
1895 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1897 } #foreach $cust_bill_pkg
1899 # Tag this row so that we know whether this is one page (1), two pages
1900 # (2), # or "big" (B). The tag will be stripped off before uploading.
1901 if ( scalar(@details) < 12 ) {
1903 } elsif ( scalar(@details) < 58 ) {
1909 return join('', $header, @details, "\n");
1917 time2str("%x", $self->_date),
1918 sprintf("%.2f", $self->charged),
1919 ( map { $cust_main->getfield($_) }
1920 qw( first last company address1 address2 city state zip country ) ),
1922 ) or die "can't create csv";
1925 my $header = $csv->string. "\n";
1928 if ( lc($opt{'format'}) eq 'billco' ) {
1931 my %items_opt = ( format => 'template',
1932 escape_function => sub { shift } );
1933 # I don't know what characters billco actually tolerates in spool entries.
1934 # Text::CSV will take care of delimiters, though.
1936 my @items = ( $self->_items_pkg(%items_opt),
1937 $self->_items_fee(%items_opt) );
1938 foreach my $item (@items) {
1940 my $description = $item->{'description'};
1941 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1942 $description .= ': ' . $item->{ext_description}[0];
1946 '', # 1 | N/A-Leave Empty CHAR 2
1947 '', # 2 | N/A-Leave Empty CHAR 15
1948 $tracctnum, # 3 | Account Number CHAR 15
1949 $self->invnum, # 4 | Invoice Number CHAR 15
1950 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1951 $description, # 6 | Transaction Detail CHAR 100
1952 $item->{'amount'}, # 7 | Amount NUM* 9
1953 '', # 8 | Line Format Control** CHAR 2
1954 '', # 9 | Grouping Code CHAR 2
1955 '', # 10 | User Defined CHAR 15
1958 $detail .= $csv->string. "\n";
1962 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1968 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1970 my($pkg, $setup, $recur, $sdate, $edate);
1971 if ( $cust_bill_pkg->pkgnum ) {
1973 ($pkg, $setup, $recur, $sdate, $edate) = (
1974 $cust_bill_pkg->part_pkg->pkg,
1975 ( $cust_bill_pkg->setup != 0
1976 ? sprintf("%.2f", $cust_bill_pkg->setup )
1978 ( $cust_bill_pkg->recur != 0
1979 ? sprintf("%.2f", $cust_bill_pkg->recur )
1981 ( $cust_bill_pkg->sdate
1982 ? time2str("%x", $cust_bill_pkg->sdate)
1984 ($cust_bill_pkg->edate
1985 ? time2str("%x", $cust_bill_pkg->edate)
1989 } else { #pkgnum tax
1990 next unless $cust_bill_pkg->setup != 0;
1991 $pkg = $cust_bill_pkg->desc;
1992 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1993 ( $sdate, $edate ) = ( '', '' );
1999 ( map { '' } (1..11) ),
2000 ($pkg, $setup, $recur, $sdate, $edate)
2001 ) or die "can't create csv";
2003 $detail .= $csv->string. "\n";
2009 ( $header, $detail );
2015 Pays this invoice with a compliemntary payment. If there is an error,
2016 returns the error, otherwise returns false.
2022 my $cust_pay = new FS::cust_pay ( {
2023 'invnum' => $self->invnum,
2024 'paid' => $self->owed,
2027 'payinfo' => $self->cust_main->payinfo,
2035 Attempts to pay this invoice with a credit card payment via a
2036 Business::OnlinePayment realtime gateway. See
2037 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2038 for supported processors.
2044 $self->realtime_bop( 'CC', @_ );
2049 Attempts to pay this invoice with an electronic check (ACH) payment via a
2050 Business::OnlinePayment realtime gateway. See
2051 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2052 for supported processors.
2058 $self->realtime_bop( 'ECHECK', @_ );
2063 Attempts to pay this invoice with phone bill (LEC) payment via a
2064 Business::OnlinePayment realtime gateway. See
2065 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2066 for supported processors.
2072 $self->realtime_bop( 'LEC', @_ );
2076 my( $self, $method ) = (shift,shift);
2077 my $conf = $self->conf;
2080 my $cust_main = $self->cust_main;
2081 my $balance = $cust_main->balance;
2082 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2083 $amount = sprintf("%.2f", $amount);
2084 return "not run (balance $balance)" unless $amount > 0;
2086 my $description = 'Internet Services';
2087 if ( $conf->exists('business-onlinepayment-description') ) {
2088 my $dtempl = $conf->config('business-onlinepayment-description');
2090 my $agent_obj = $cust_main->agent
2091 or die "can't retreive agent for $cust_main (agentnum ".
2092 $cust_main->agentnum. ")";
2093 my $agent = $agent_obj->agent;
2094 my $pkgs = join(', ',
2095 map { $_->part_pkg->pkg }
2096 grep { $_->pkgnum } $self->cust_bill_pkg
2098 $description = eval qq("$dtempl");
2101 $cust_main->realtime_bop($method, $amount,
2102 'description' => $description,
2103 'invnum' => $self->invnum,
2104 #this didn't do what we want, it just calls apply_payments_and_credits
2106 'apply_to_invoice' => 1,
2109 #this changes application behavior: auto payments
2110 #triggered against a specific invoice are now applied
2111 #to that invoice instead of oldest open.
2117 =item batch_card OPTION => VALUE...
2119 Adds a payment for this invoice to the pending credit card batch (see
2120 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2121 runs the payment using a realtime gateway.
2126 my ($self, %options) = @_;
2127 my $cust_main = $self->cust_main;
2129 $options{invnum} = $self->invnum;
2131 $cust_main->batch_card(%options);
2134 sub _agent_template {
2136 $self->cust_main->agent_template;
2139 sub _agent_invoice_from {
2141 $self->cust_main->agent_invoice_from;
2144 =item invoice_barcode DIR_OR_FALSE
2146 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2147 it is taken as the temp directory where the PNG file will be generated and the
2148 PNG file name is returned. Otherwise, the PNG image itself is returned.
2152 sub invoice_barcode {
2153 my ($self, $dir) = (shift,shift);
2155 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2156 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2157 my $gd = $gdbar->plot(Height => 30);
2160 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2164 ) or die "can't open temp file: $!\n";
2165 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2166 my $png_file = $bh->filename;
2173 =item invnum_date_pretty
2175 Returns a string with the invoice number and date, for example:
2176 "Invoice #54 (3/20/2008)".
2178 Intended for back-end context, with regard to translation and date formatting.
2182 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2183 # for backend use (and also does the wrong thing, localizing for end customer
2184 # instead of backoffice configured date format)
2185 sub invnum_date_pretty {
2187 #$self->mt('Invoice #').
2188 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2189 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2192 #sub _items_extra_usage_sections {
2194 # my $escape = shift;
2196 # my %sections = ();
2198 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2199 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2201 # next unless $cust_bill_pkg->pkgnum > 0;
2203 # foreach my $section ( keys %usage_class ) {
2205 # my $usage = $cust_bill_pkg->usage($section);
2207 # next unless $usage && $usage > 0;
2209 # $sections{$section} ||= 0;
2210 # $sections{$section} += $usage;
2216 # map { { 'description' => &{$escape}($_),
2217 # 'subtotal' => $sections{$_},
2218 # 'summarized' => '',
2219 # 'tax_section' => '',
2222 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2226 sub _items_extra_usage_sections {
2228 my $conf = $self->conf;
2236 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2238 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2239 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2240 next unless $cust_bill_pkg->pkgnum > 0;
2242 foreach my $classnum ( keys %usage_class ) {
2243 my $section = $usage_class{$classnum}->classname;
2244 $classnums{$section} = $classnum;
2246 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2247 my $amount = $detail->amount;
2248 next unless $amount && $amount > 0;
2250 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2251 $sections{$section}{amount} += $amount; #subtotal
2252 $sections{$section}{calls}++;
2253 $sections{$section}{duration} += $detail->duration;
2255 my $desc = $detail->regionname;
2256 my $description = $desc;
2257 $description = substr($desc, 0, $maxlength). '...'
2258 if $format eq 'latex' && length($desc) > $maxlength;
2260 $lines{$section}{$desc} ||= {
2261 description => &{$escape}($description),
2262 #pkgpart => $part_pkg->pkgpart,
2263 pkgnum => $cust_bill_pkg->pkgnum,
2268 #unit_amount => $cust_bill_pkg->unitrecur,
2269 quantity => $cust_bill_pkg->quantity,
2270 product_code => 'N/A',
2271 ext_description => [],
2274 $lines{$section}{$desc}{amount} += $amount;
2275 $lines{$section}{$desc}{calls}++;
2276 $lines{$section}{$desc}{duration} += $detail->duration;
2282 my %sectionmap = ();
2283 foreach (keys %sections) {
2284 my $usage_class = $usage_class{$classnums{$_}};
2285 $sectionmap{$_} = { 'description' => &{$escape}($_),
2286 'amount' => $sections{$_}{amount}, #subtotal
2287 'calls' => $sections{$_}{calls},
2288 'duration' => $sections{$_}{duration},
2290 'tax_section' => '',
2291 'sort_weight' => $usage_class->weight,
2292 ( $usage_class->format
2293 ? ( map { $_ => $usage_class->$_($format) }
2294 qw( description_generator header_generator total_generator total_line_generator )
2301 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2305 foreach my $section ( keys %lines ) {
2306 foreach my $line ( keys %{$lines{$section}} ) {
2307 my $l = $lines{$section}{$line};
2308 $l->{section} = $sectionmap{$section};
2309 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2310 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2315 return(\@sections, \@lines);
2321 my $end = $self->_date;
2323 # start at date of previous invoice + 1 second or 0 if no previous invoice
2324 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2325 $start = 0 if !$start;
2328 my $cust_main = $self->cust_main;
2329 my @pkgs = $cust_main->all_pkgs;
2330 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2333 foreach my $pkg ( @pkgs ) {
2334 my @h_cust_svc = $pkg->h_cust_svc($end);
2335 foreach my $h_cust_svc ( @h_cust_svc ) {
2336 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2337 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2339 my $inserted = $h_cust_svc->date_inserted;
2340 my $deleted = $h_cust_svc->date_deleted;
2341 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2343 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2345 # DID either activated or ported in; cannot be both for same DID simultaneously
2346 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2347 && (!$phone_inserted->lnp_status
2348 || $phone_inserted->lnp_status eq ''
2349 || $phone_inserted->lnp_status eq 'native')) {
2352 else { # this one not so clean, should probably move to (h_)svc_phone
2353 my $phone_portedin = qsearchs( 'h_svc_phone',
2354 { 'svcnum' => $h_cust_svc->svcnum,
2355 'lnp_status' => 'portedin' },
2356 FS::h_svc_phone->sql_h_searchs($end),
2358 $num_portedin++ if $phone_portedin;
2361 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2362 if($deleted >= $start && $deleted <= $end && $phone_deleted
2363 && (!$phone_deleted->lnp_status
2364 || $phone_deleted->lnp_status ne 'portingout')) {
2367 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2368 && $phone_deleted->lnp_status
2369 && $phone_deleted->lnp_status eq 'portingout') {
2373 # increment usage minutes
2374 if ( $phone_inserted ) {
2375 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2376 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2379 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2382 # don't look at this service again
2383 push @seen, $h_cust_svc->svcnum;
2387 $minutes = sprintf("%d", $minutes);
2388 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2389 . "$num_deactivated Ported-Out: $num_portedout ",
2390 "Total Minutes: $minutes");
2393 sub _items_accountcode_cdr {
2398 my $section = { 'amount' => 0,
2401 'sort_weight' => '',
2403 'description' => 'Usage by Account Code',
2409 my %accountcodes = ();
2411 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2412 next unless $cust_bill_pkg->pkgnum > 0;
2414 my @header = $cust_bill_pkg->details_header;
2415 next unless scalar(@header);
2416 $section->{'header'} = join(',',@header);
2418 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2420 $section->{'header'} = $detail->formatted('format' => $format)
2421 if($detail->detail eq $section->{'header'});
2423 my $accountcode = $detail->accountcode;
2424 next unless $accountcode;
2426 my $amount = $detail->amount;
2427 next unless $amount && $amount > 0;
2429 $accountcodes{$accountcode} ||= {
2430 description => $accountcode,
2437 product_code => 'N/A',
2438 section => $section,
2439 ext_description => [ $section->{'header'} ],
2443 $section->{'amount'} += $amount;
2444 $accountcodes{$accountcode}{'amount'} += $amount;
2445 $accountcodes{$accountcode}{calls}++;
2446 $accountcodes{$accountcode}{duration} += $detail->duration;
2447 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2451 foreach my $l ( values %accountcodes ) {
2452 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2453 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2454 foreach my $sorted_detail ( @sorted_detail ) {
2455 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2457 delete $l->{detail_temp};
2461 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2463 return ($section,\@sorted_lines);
2466 sub _items_svc_phone_sections {
2468 my $conf = $self->conf;
2476 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2478 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2479 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2481 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2482 next unless $cust_bill_pkg->pkgnum > 0;
2484 my @header = $cust_bill_pkg->details_header;
2485 next unless scalar(@header);
2487 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2489 my $phonenum = $detail->phonenum;
2490 next unless $phonenum;
2492 my $amount = $detail->amount;
2493 next unless $amount && $amount > 0;
2495 $sections{$phonenum} ||= { 'amount' => 0,
2498 'sort_weight' => -1,
2499 'phonenum' => $phonenum,
2501 $sections{$phonenum}{amount} += $amount; #subtotal
2502 $sections{$phonenum}{calls}++;
2503 $sections{$phonenum}{duration} += $detail->duration;
2505 my $desc = $detail->regionname;
2506 my $description = $desc;
2507 $description = substr($desc, 0, $maxlength). '...'
2508 if $format eq 'latex' && length($desc) > $maxlength;
2510 $lines{$phonenum}{$desc} ||= {
2511 description => &{$escape}($description),
2512 #pkgpart => $part_pkg->pkgpart,
2520 product_code => 'N/A',
2521 ext_description => [],
2524 $lines{$phonenum}{$desc}{amount} += $amount;
2525 $lines{$phonenum}{$desc}{calls}++;
2526 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2528 my $line = $usage_class{$detail->classnum}->classname;
2529 $sections{"$phonenum $line"} ||=
2533 'sort_weight' => $usage_class{$detail->classnum}->weight,
2534 'phonenum' => $phonenum,
2535 'header' => [ @header ],
2537 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2538 $sections{"$phonenum $line"}{calls}++;
2539 $sections{"$phonenum $line"}{duration} += $detail->duration;
2541 $lines{"$phonenum $line"}{$desc} ||= {
2542 description => &{$escape}($description),
2543 #pkgpart => $part_pkg->pkgpart,
2551 product_code => 'N/A',
2552 ext_description => [],
2555 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2556 $lines{"$phonenum $line"}{$desc}{calls}++;
2557 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2558 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2559 $detail->formatted('format' => $format);
2564 my %sectionmap = ();
2565 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2566 foreach ( keys %sections ) {
2567 my @header = @{ $sections{$_}{header} || [] };
2569 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2570 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2571 my $usage_class = $summary ? $simple : $usage_simple;
2572 my $ending = $summary ? ' usage charges' : '';
2575 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2577 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2578 'amount' => $sections{$_}{amount}, #subtotal
2579 'calls' => $sections{$_}{calls},
2580 'duration' => $sections{$_}{duration},
2582 'tax_section' => '',
2583 'phonenum' => $sections{$_}{phonenum},
2584 'sort_weight' => $sections{$_}{sort_weight},
2585 'post_total' => $summary, #inspire pagebreak
2587 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2588 qw( description_generator
2591 total_line_generator
2598 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2599 $a->{sort_weight} <=> $b->{sort_weight}
2604 foreach my $section ( keys %lines ) {
2605 foreach my $line ( keys %{$lines{$section}} ) {
2606 my $l = $lines{$section}{$line};
2607 $l->{section} = $sectionmap{$section};
2608 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2609 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2614 if($conf->exists('phone_usage_class_summary')) {
2615 # this only works with Latex
2619 # after this, we'll have only two sections per DID:
2620 # Calls Summary and Calls Detail
2621 foreach my $section ( @sections ) {
2622 if($section->{'post_total'}) {
2623 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2624 $section->{'total_line_generator'} = sub { '' };
2625 $section->{'total_generator'} = sub { '' };
2626 $section->{'header_generator'} = sub { '' };
2627 $section->{'description_generator'} = '';
2628 push @newsections, $section;
2629 my %calls_detail = %$section;
2630 $calls_detail{'post_total'} = '';
2631 $calls_detail{'sort_weight'} = '';
2632 $calls_detail{'description_generator'} = sub { '' };
2633 $calls_detail{'header_generator'} = sub {
2634 return ' & Date/Time & Called Number & Duration & Price'
2635 if $format eq 'latex';
2638 $calls_detail{'description'} = 'Calls Detail: '
2639 . $section->{'phonenum'};
2640 push @newsections, \%calls_detail;
2644 # after this, each usage class is collapsed/summarized into a single
2645 # line under the Calls Summary section
2646 foreach my $newsection ( @newsections ) {
2647 if($newsection->{'post_total'}) { # this means Calls Summary
2648 foreach my $section ( @sections ) {
2649 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2650 && !$section->{'post_total'});
2651 my $newdesc = $section->{'description'};
2652 my $tn = $section->{'phonenum'};
2653 $newdesc =~ s/$tn//g;
2654 my $line = { ext_description => [],
2658 calls => $section->{'calls'},
2659 section => $newsection,
2660 duration => $section->{'duration'},
2661 description => $newdesc,
2662 amount => sprintf("%.2f",$section->{'amount'}),
2663 product_code => 'N/A',
2665 push @newlines, $line;
2670 # after this, Calls Details is populated with all CDRs
2671 foreach my $newsection ( @newsections ) {
2672 if(!$newsection->{'post_total'}) { # this means Calls Details
2673 foreach my $line ( @lines ) {
2674 next unless (scalar(@{$line->{'ext_description'}}) &&
2675 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2677 my @extdesc = @{$line->{'ext_description'}};
2679 foreach my $extdesc ( @extdesc ) {
2680 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2681 push @newextdesc, $extdesc;
2683 $line->{'ext_description'} = \@newextdesc;
2684 $line->{'section'} = $newsection;
2685 push @newlines, $line;
2690 return(\@newsections, \@newlines);
2693 return(\@sections, \@lines);
2697 =sub _items_usage_class_summary OPTIONS
2699 Returns a list of detail items summarizing the usage charges on this
2700 invoice. Each one will have 'amount', 'description' (the usage charge name),
2701 and 'usage_classnum'.
2703 OPTIONS can include 'escape' (a function to escape the descriptions).
2707 sub _items_usage_class_summary {
2711 my $escape = $opt{escape} || sub { $_[0] };
2712 my $money_char = $opt{money_char};
2713 my $invnum = $self->invnum;
2714 my @classes = qsearch({
2715 'table' => 'usage_class',
2716 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2717 ' COUNT(*) AS calls, SUM(duration) AS duration',
2718 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2719 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2720 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2721 ' GROUP BY classnum, classname, weight'.
2722 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2723 ' ORDER BY weight ASC',
2727 description => &{$escape}($self->mt('Usage Summary')),
2731 foreach my $class (@classes) {
2732 $section->{subtotal} += $class->get('amount');
2734 'description' => &{$escape}($class->classname),
2735 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2736 'quantity' => $class->get('calls'),
2737 'duration' => $class->get('duration'),
2738 'usage_classnum' => $class->classnum,
2739 'section' => $section,
2742 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2746 sub _items_previous {
2748 my $conf = $self->conf;
2749 my $cust_main = $self->cust_main;
2750 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2752 foreach ( @pr_cust_bill ) {
2753 my $date = $conf->exists('invoice_show_prior_due_date')
2754 ? 'due '. $_->due_date2str('short')
2755 : $self->time2str_local('short', $_->_date);
2757 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2758 #'pkgpart' => 'N/A',
2760 'amount' => sprintf("%.2f", $_->owed),
2766 # 'description' => 'Previous Balance',
2767 # #'pkgpart' => 'N/A',
2768 # 'pkgnum' => 'N/A',
2769 # 'amount' => sprintf("%10.2f", $pr_total ),
2770 # 'ext_description' => [ map {
2771 # "Invoice ". $_->invnum.
2772 # " (". time2str("%x",$_->_date). ") ".
2773 # sprintf("%10.2f", $_->owed)
2774 # } @pr_cust_bill ],
2779 sub _items_credits {
2780 my( $self, %opt ) = @_;
2781 my $trim_len = $opt{'trim_len'} || 40;
2786 if ( $self->conf->exists('previous_balance-payments_since') ) {
2787 if ( $opt{'template'} eq 'statement' ) {
2788 # then the current bill is a "statement" (i.e. an invoice sent as
2789 # a payment receipt)
2790 # and in that case we want to see payments on or after THIS invoice
2791 @objects = qsearch('cust_credit', {
2792 'custnum' => $self->custnum,
2793 '_date' => {op => '>=', value => $self->_date},
2797 $date = $self->previous_bill->_date if $self->previous_bill;
2798 @objects = qsearch('cust_credit', {
2799 'custnum' => $self->custnum,
2800 '_date' => {op => '>=', value => $date},
2804 @objects = $self->cust_credited;
2807 foreach my $obj ( @objects ) {
2808 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2810 my $reason = substr($cust_credit->reason, 0, $trim_len);
2811 $reason .= '...' if length($reason) < length($cust_credit->reason);
2812 $reason = " ($reason) " if $reason;
2815 #'description' => 'Credit ref\#'. $_->crednum.
2816 # " (". time2str("%x",$_->cust_credit->_date) .")".
2818 'description' => $self->mt('Credit applied').' '.
2819 $self->time2str_local('short', $obj->_date). $reason,
2820 'amount' => sprintf("%.2f",$obj->amount),
2828 sub _items_payments {
2833 my $detailed = $self->conf->exists('invoice_payment_details');
2835 if ( $self->conf->exists('previous_balance-payments_since') ) {
2836 # then show payments dated on/after the previous bill...
2837 if ( $opt{'template'} eq 'statement' ) {
2838 # then the current bill is a "statement" (i.e. an invoice sent as
2839 # a payment receipt)
2840 # and in that case we want to see payments on or after THIS invoice
2841 @objects = qsearch('cust_pay', {
2842 'custnum' => $self->custnum,
2843 '_date' => {op => '>=', value => $self->_date},
2846 # the normal case: payments on or after the previous invoice
2848 $date = $self->previous_bill->_date if $self->previous_bill;
2849 @objects = qsearch('cust_pay', {
2850 'custnum' => $self->custnum,
2851 '_date' => {op => '>=', value => $date},
2853 # and before the current bill...
2854 @objects = grep { $_->_date < $self->_date } @objects;
2857 @objects = $self->cust_bill_pay;
2860 foreach my $obj (@objects) {
2861 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2862 my $desc = $self->mt('Payment received').' '.
2863 $self->time2str_local('short', $cust_pay->_date );
2864 $desc .= $self->mt(' via ') .
2865 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2869 'description' => $desc,
2870 'amount' => sprintf("%.2f", $obj->amount )
2880 my $conf = $self->conf;
2883 my ($pr_total) = $self->previous;
2884 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2886 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2887 # if enabled, specifically add a line for the previous balance total
2888 $previous_charges_desc = $self->mt(
2889 $conf->config('previous_balance-text') || 'Previous Balance'
2892 # then return separate lines for previous balance and total new charges
2895 { total_item => $previous_charges_desc,
2896 total_amount => sprintf('%.2f',$pr_total)
2901 if ( $conf->exists('previous_balance-exclude_from_total')
2902 or !$self->enable_previous ) {
2903 # show new charges only
2905 $new_charges_desc = $self->mt(
2906 $conf->config('previous_balance-text-total_new_charges')
2907 || 'Total New Charges'
2910 $new_charges_amount = $self->charged;
2913 # show new charges + previous invoice total
2915 $new_charges_desc = $self->mt('Total Charges');
2916 if ( $self->enable_previous ) {
2917 $new_charges_amount = sprintf('%.2f', $self->charged + $pr_total);
2919 $new_charges_amount = sprintf('%.2f', $self->charged);
2924 if ( $conf->exists('invoice_show_prior_due_date') ) {
2925 # then the due date should be shown with Total New Charges,
2926 # and should NOT be shown with the Balance Due message.
2927 if ( $self->due_date ) {
2928 # localize the "Please pay by" message and the date itself
2929 # (grammar issues with this, yeah)
2930 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2931 $self->due_date2str('short');
2932 } elsif ( $self->terms ) {
2933 # phrases like "due on receipt" should be localized
2934 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2939 { total_item => $new_charges_desc,
2940 total_amount => $new_charges_amount,
2948 =item has_call_details
2950 Returns true if this invoice has call details.
2954 sub has_call_details {
2957 SELECT 1 FROM cust_bill_pkg_detail
2958 LEFT JOIN cust_bill_pkg USING (billpkgnum)
2959 WHERE cust_bill_pkg_detail.format = 'C'
2960 AND cust_bill_pkg.invnum = ?
2965 =item call_details [ OPTION => VALUE ... ]
2967 Returns an array of CSV strings representing the call details for this invoice
2968 The only option available is the boolean prepend_billed_number
2973 my ($self, %opt) = @_;
2975 my $format_function = sub { shift };
2977 if ($opt{prepend_billed_number}) {
2978 $format_function = sub {
2982 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2987 my @details = map { $_->details( 'format_function' => $format_function,
2988 'escape_function' => sub{ return() },
2992 $self->cust_bill_pkg;
2993 my $header = $details[0];
2994 ( $header, grep { $_ ne $header } @details );
3004 =item process_reprint
3008 sub process_reprint {
3009 process_re_X('print', @_);
3012 =item process_reemail
3016 sub process_reemail {
3017 process_re_X('email', @_);
3025 process_re_X('fax', @_);
3033 process_re_X('ftp', @_);
3040 sub process_respool {
3041 process_re_X('spool', @_);
3044 use Storable qw(thaw);
3048 my( $method, $job ) = ( shift, shift );
3049 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3051 my $param = thaw(decode_base64(shift));
3052 warn Dumper($param) if $DEBUG;
3062 # this is called from search/cust_bill.html and given all its search
3063 # parameters, so it needs to perform the same search.
3066 # spool_invoice ftp_invoice fax_invoice print_invoice
3067 my($method, $job, %param ) = @_;
3069 warn "re_X $method for job $job with param:\n".
3070 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3073 #some false laziness w/search/cust_bill.html
3074 $param{'order_by'} = 'cust_bill._date';
3076 my $query = FS::cust_bill->search(\%param);
3077 delete $query->{'count_query'};
3078 delete $query->{'count_addl'};
3080 $query->{debug} = 1; # was in here before, is obviously useful
3082 my @cust_bill = qsearch( $query );
3084 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3086 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3089 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3090 foreach my $cust_bill ( @cust_bill ) {
3091 $cust_bill->$method();
3093 if ( $job ) { #progressbar foo
3095 if ( time - $min_sec > $last ) {
3096 my $error = $job->update_statustext(
3097 int( 100 * $num / scalar(@cust_bill) )
3099 die $error if $error;
3110 =head1 CLASS METHODS
3116 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3121 my ($class, $start, $end) = @_;
3123 $class->paid_sql($start, $end). ' - '.
3124 $class->credited_sql($start, $end);
3129 Returns an SQL fragment to retreive the net amount (charged minus credited).
3134 my ($class, $start, $end) = @_;
3135 'charged - '. $class->credited_sql($start, $end);
3140 Returns an SQL fragment to retreive the amount paid against this invoice.
3145 my ($class, $start, $end) = @_;
3146 $start &&= "AND cust_bill_pay._date <= $start";
3147 $end &&= "AND cust_bill_pay._date > $end";
3148 $start = '' unless defined($start);
3149 $end = '' unless defined($end);
3150 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3151 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3156 Returns an SQL fragment to retreive the amount credited against this invoice.
3161 my ($class, $start, $end) = @_;
3162 $start &&= "AND cust_credit_bill._date <= $start";
3163 $end &&= "AND cust_credit_bill._date > $end";
3164 $start = '' unless defined($start);
3165 $end = '' unless defined($end);
3166 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3167 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3172 Returns an SQL fragment to retrieve the due date of an invoice.
3173 Currently only supported on PostgreSQL.
3178 die "don't use: doesn't account for agent-specific invoice_default_terms";
3180 #we're passed a $conf but not a specific customer (that's in the query), so
3181 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3182 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3185 my $conf = new FS::Conf;
3189 cust_bill.invoice_terms,
3190 cust_main.invoice_terms,
3191 \''.($conf->config('invoice_default_terms') || '').'\'
3192 ), E\'Net (\\\\d+)\'
3194 ) * 86400 + cust_bill._date'
3205 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3206 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base