2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $DEBUG $me $date_format );
7 use Fcntl qw(:flock); #for spool_csv
9 use List::Util qw(min max sum);
13 use Storable qw( freeze thaw );
15 use FS::UID qw( datasrc );
16 use FS::Misc qw( send_email send_fax do_print );
17 use FS::Record qw( qsearch qsearchs dbh );
19 use FS::cust_statement;
20 use FS::cust_bill_pkg;
21 use FS::cust_bill_pkg_display;
22 use FS::cust_bill_pkg_detail;
26 use FS::cust_credit_bill;
28 use FS::cust_pay_batch;
29 use FS::cust_bill_event;
32 use FS::cust_bill_pay;
33 use FS::cust_bill_pay_batch;
34 use FS::part_bill_event;
37 use FS::cust_bill_batch;
38 use FS::cust_bill_pay_pkg;
39 use FS::cust_credit_bill_pkg;
40 use FS::discount_plan;
41 use FS::cust_bill_void;
45 $me = '[FS::cust_bill]';
47 #ask FS::UID to run this stuff for us later
48 FS::UID->install_callback( sub {
49 my $conf = new FS::Conf; #global
50 $date_format = $conf->config('date_format') || '%x'; #/YY
55 FS::cust_bill - Object methods for cust_bill records
61 $record = new FS::cust_bill \%hash;
62 $record = new FS::cust_bill { 'column' => 'value' };
64 $error = $record->insert;
66 $error = $new_record->replace($old_record);
68 $error = $record->delete;
70 $error = $record->check;
72 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
74 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
76 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
78 @cust_pay_objects = $cust_bill->cust_pay;
80 $tax_amount = $record->tax;
82 @lines = $cust_bill->print_text;
83 @lines = $cust_bill->print_text('time' => $time);
87 An FS::cust_bill object represents an invoice; a declaration that a customer
88 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
89 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
90 following fields are currently supported:
96 =item invnum - primary key (assigned automatically for new invoices)
98 =item custnum - customer (see L<FS::cust_main>)
100 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
101 L<Time::Local> and L<Date::Parse> for conversion functions.
103 =item charged - amount of this invoice
105 =item invoice_terms - optional terms override for this specific invoice
109 Customer info at invoice generation time
113 =item billing_balance - the customer's balance at the time the invoice was
114 generated (not including charges on this invoice)
116 =item previous_balance - the billing_balance of this customer's previous
117 invoice plus the charges on that invoice
125 =item printed - deprecated
133 =item closed - books closed flag, empty or `Y'
135 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
137 =item agent_invid - legacy invoice number
139 =item promised_date - customer promised payment date, for collection
149 Creates a new invoice. To add the invoice to the database, see L<"insert">.
150 Invoices are normally created by calling the bill method of a customer object
151 (see L<FS::cust_main>).
155 sub table { 'cust_bill'; }
157 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
158 # (except email_subject and invnum_date_pretty)
161 $self->conf->config('notice_name') || 'Invoice'
164 sub cust_linked { $_[0]->cust_main_custnum; }
165 sub cust_unlinked_msg {
167 "WARNING: can't find cust_main.custnum ". $self->custnum.
168 ' (cust_bill.invnum '. $self->invnum. ')';
173 Adds this invoice to the database ("Posts" the invoice). If there is an error,
174 returns the error, otherwise returns false.
180 warn "$me insert called\n" if $DEBUG;
182 local $SIG{HUP} = 'IGNORE';
183 local $SIG{INT} = 'IGNORE';
184 local $SIG{QUIT} = 'IGNORE';
185 local $SIG{TERM} = 'IGNORE';
186 local $SIG{TSTP} = 'IGNORE';
187 local $SIG{PIPE} = 'IGNORE';
189 my $oldAutoCommit = $FS::UID::AutoCommit;
190 local $FS::UID::AutoCommit = 0;
193 my $error = $self->SUPER::insert;
195 $dbh->rollback if $oldAutoCommit;
199 if ( $self->get('cust_bill_pkg') ) {
200 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
201 $cust_bill_pkg->invnum($self->invnum);
202 my $error = $cust_bill_pkg->insert;
204 $dbh->rollback if $oldAutoCommit;
205 return "can't create invoice line item: $error";
210 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
217 Voids this invoice: deletes the invoice and adds a record of the voided invoice
218 to the FS::cust_bill_void table (and related tables starting from
219 FS::cust_bill_pkg_void).
225 my $reason = scalar(@_) ? shift : '';
227 local $SIG{HUP} = 'IGNORE';
228 local $SIG{INT} = 'IGNORE';
229 local $SIG{QUIT} = 'IGNORE';
230 local $SIG{TERM} = 'IGNORE';
231 local $SIG{TSTP} = 'IGNORE';
232 local $SIG{PIPE} = 'IGNORE';
234 my $oldAutoCommit = $FS::UID::AutoCommit;
235 local $FS::UID::AutoCommit = 0;
238 my $cust_bill_void = new FS::cust_bill_void ( {
239 map { $_ => $self->get($_) } $self->fields
241 $cust_bill_void->reason($reason);
242 my $error = $cust_bill_void->insert;
244 $dbh->rollback if $oldAutoCommit;
248 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
249 my $error = $cust_bill_pkg->void($reason);
251 $dbh->rollback if $oldAutoCommit;
256 $error = $self->delete;
258 $dbh->rollback if $oldAutoCommit;
262 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
270 This method now works but you probably shouldn't use it. Instead, apply a
271 credit against the invoice, or use the new void method.
273 Using this method to delete invoices outright is really, really bad. There
274 would be no record you ever posted this invoice, and there are no check to
275 make sure charged = 0 or that there are no associated cust_bill_pkg records.
277 Really, don't use it.
283 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
285 local $SIG{HUP} = 'IGNORE';
286 local $SIG{INT} = 'IGNORE';
287 local $SIG{QUIT} = 'IGNORE';
288 local $SIG{TERM} = 'IGNORE';
289 local $SIG{TSTP} = 'IGNORE';
290 local $SIG{PIPE} = 'IGNORE';
292 my $oldAutoCommit = $FS::UID::AutoCommit;
293 local $FS::UID::AutoCommit = 0;
296 foreach my $table (qw(
307 foreach my $linked ( $self->$table() ) {
308 my $error = $linked->delete;
310 $dbh->rollback if $oldAutoCommit;
317 my $error = $self->SUPER::delete(@_);
319 $dbh->rollback if $oldAutoCommit;
323 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
329 =item replace [ OLD_RECORD ]
331 You can, but probably shouldn't modify invoices...
333 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
334 supplied, replaces this record. If there is an error, returns the error,
335 otherwise returns false.
339 #replace can be inherited from Record.pm
341 # replace_check is now the preferred way to #implement replace data checks
342 # (so $object->replace() works without an argument)
345 my( $new, $old ) = ( shift, shift );
346 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
347 #return "Can't change _date!" unless $old->_date eq $new->_date;
348 return "Can't change _date" unless $old->_date == $new->_date;
349 return "Can't change charged" unless $old->charged == $new->charged
350 || $old->charged == 0
351 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
357 =item add_cc_surcharge
363 sub add_cc_surcharge {
364 my ($self, $pkgnum, $amount) = (shift, shift, shift);
367 my $cust_bill_pkg = new FS::cust_bill_pkg({
368 'invnum' => $self->invnum,
372 $error = $cust_bill_pkg->insert;
373 return $error if $error;
375 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
376 $self->charged($self->charged+$amount);
377 $error = $self->replace;
378 return $error if $error;
380 $self->apply_payments_and_credits;
386 Checks all fields to make sure this is a valid invoice. If there is an error,
387 returns the error, otherwise returns false. Called by the insert and replace
396 $self->ut_numbern('invnum')
397 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
398 || $self->ut_numbern('_date')
399 || $self->ut_money('charged')
400 || $self->ut_numbern('printed')
401 || $self->ut_enum('closed', [ '', 'Y' ])
402 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
403 || $self->ut_numbern('agent_invid') #varchar?
405 return $error if $error;
407 $self->_date(time) unless $self->_date;
409 $self->printed(0) if $self->printed eq '';
416 Returns the displayed invoice number for this invoice: agent_invid if
417 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
423 my $conf = $self->conf;
424 if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
425 return $self->agent_invid;
427 return $self->invnum;
433 Returns the customer's last invoice before this one.
439 if ( !$self->get('previous_bill') ) {
440 $self->set('previous_bill', qsearchs({
441 'table' => 'cust_bill',
442 'hashref' => { 'custnum' => $self->custnum,
443 '_date' => { op=>'<', value=>$self->_date } },
444 'order_by' => 'ORDER BY _date DESC LIMIT 1',
447 $self->get('previous_bill');
452 Returns a list consisting of the total previous balance for this customer,
453 followed by the previous outstanding invoices (as FS::cust_bill objects also).
460 my @cust_bill = sort { $a->_date <=> $b->_date }
461 grep { $_->owed != 0 }
462 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
463 #'_date' => { op=>'<', value=>$self->_date },
464 'invnum' => { op=>'<', value=>$self->invnum },
467 foreach ( @cust_bill ) { $total += $_->owed; }
471 =item enable_previous
473 Whether to show the 'Previous Charges' section when printing this invoice.
474 The negation of the 'disable_previous_balance' config setting.
478 sub enable_previous {
480 my $agentnum = $self->cust_main->agentnum;
481 !$self->conf->exists('disable_previous_balance', $agentnum);
486 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
493 { 'table' => 'cust_bill_pkg',
494 'hashref' => { 'invnum' => $self->invnum },
495 'order_by' => 'ORDER BY billpkgnum',
500 =item cust_bill_pkg_pkgnum PKGNUM
502 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
507 sub cust_bill_pkg_pkgnum {
508 my( $self, $pkgnum ) = @_;
510 { 'table' => 'cust_bill_pkg',
511 'hashref' => { 'invnum' => $self->invnum,
514 'order_by' => 'ORDER BY billpkgnum',
521 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
528 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
529 $self->cust_bill_pkg;
531 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
536 Returns true if any of the packages (or their definitions) corresponding to the
537 line items for this invoice have the no_auto flag set.
543 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
546 =item open_cust_bill_pkg
548 Returns the open line items for this invoice.
550 Note that cust_bill_pkg with both setup and recur fees are returned as two
551 separate line items, each with only one fee.
555 # modeled after cust_main::open_cust_bill
556 sub open_cust_bill_pkg {
559 # grep { $_->owed > 0 } $self->cust_bill_pkg
561 my %other = ( 'recur' => 'setup',
562 'setup' => 'recur', );
564 foreach my $field ( qw( recur setup )) {
565 push @open, map { $_->set( $other{$field}, 0 ); $_; }
566 grep { $_->owed($field) > 0 }
567 $self->cust_bill_pkg;
573 =item cust_bill_event
575 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
579 sub cust_bill_event {
581 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
584 =item num_cust_bill_event
586 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
590 sub num_cust_bill_event {
593 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
594 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
595 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
596 $sth->fetchrow_arrayref->[0];
601 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
605 #false laziness w/cust_pkg.pm
609 'table' => 'cust_event',
610 'addl_from' => 'JOIN part_event USING ( eventpart )',
611 'hashref' => { 'tablenum' => $self->invnum },
612 'extra_sql' => " AND eventtable = 'cust_bill' ",
618 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
622 #false laziness w/cust_pkg.pm
626 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
627 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
628 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
629 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
630 $sth->fetchrow_arrayref->[0];
635 Returns the customer (see L<FS::cust_main>) for this invoice.
641 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
644 =item cust_suspend_if_balance_over AMOUNT
646 Suspends the customer associated with this invoice if the total amount owed on
647 this invoice and all older invoices is greater than the specified amount.
649 Returns a list: an empty list on success or a list of errors.
653 sub cust_suspend_if_balance_over {
654 my( $self, $amount ) = ( shift, shift );
655 my $cust_main = $self->cust_main;
656 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
659 $cust_main->suspend(@_);
665 Depreciated. See the cust_credited method.
667 #Returns a list consisting of the total previous credited (see
668 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
669 #outstanding credits (FS::cust_credit objects).
675 croak "FS::cust_bill->cust_credit depreciated; see ".
676 "FS::cust_bill->cust_credit_bill";
679 #my @cust_credit = sort { $a->_date <=> $b->_date }
680 # grep { $_->credited != 0 && $_->_date < $self->_date }
681 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
683 #foreach (@cust_credit) { $total += $_->credited; }
684 #$total, @cust_credit;
689 Depreciated. See the cust_bill_pay method.
691 #Returns all payments (see L<FS::cust_pay>) for this invoice.
697 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
699 #sort { $a->_date <=> $b->_date }
700 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
706 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
709 sub cust_bill_pay_batch {
711 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
716 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
722 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
723 sort { $a->_date <=> $b->_date }
724 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
729 =item cust_credit_bill
731 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
737 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
738 sort { $a->_date <=> $b->_date }
739 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
743 sub cust_credit_bill {
744 shift->cust_credited(@_);
747 #=item cust_bill_pay_pkgnum PKGNUM
749 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
750 #with matching pkgnum.
754 #sub cust_bill_pay_pkgnum {
755 # my( $self, $pkgnum ) = @_;
756 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
757 # sort { $a->_date <=> $b->_date }
758 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
759 # 'pkgnum' => $pkgnum,
764 =item cust_bill_pay_pkg PKGNUM
766 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
767 applied against the matching pkgnum.
771 sub cust_bill_pay_pkg {
772 my( $self, $pkgnum ) = @_;
775 'select' => 'cust_bill_pay_pkg.*',
776 'table' => 'cust_bill_pay_pkg',
777 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
778 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
779 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
780 " AND cust_bill_pkg.pkgnum = $pkgnum",
785 #=item cust_credited_pkgnum PKGNUM
787 #=item cust_credit_bill_pkgnum PKGNUM
789 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
790 #with matching pkgnum.
794 #sub cust_credited_pkgnum {
795 # my( $self, $pkgnum ) = @_;
796 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
797 # sort { $a->_date <=> $b->_date }
798 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
799 # 'pkgnum' => $pkgnum,
804 #sub cust_credit_bill_pkgnum {
805 # shift->cust_credited_pkgnum(@_);
808 =item cust_credit_bill_pkg PKGNUM
810 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
811 applied against the matching pkgnum.
815 sub cust_credit_bill_pkg {
816 my( $self, $pkgnum ) = @_;
819 'select' => 'cust_credit_bill_pkg.*',
820 'table' => 'cust_credit_bill_pkg',
821 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
822 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
823 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
824 " AND cust_bill_pkg.pkgnum = $pkgnum",
829 =item cust_bill_batch
831 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
835 sub cust_bill_batch {
837 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
842 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
843 hash keyed by term length.
849 FS::discount_plan->all($self);
854 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
861 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
863 foreach (@taxlines) { $total += $_->setup; }
869 Returns the amount owed (still outstanding) on this invoice, which is charged
870 minus all payment applications (see L<FS::cust_bill_pay>) and credit
871 applications (see L<FS::cust_credit_bill>).
877 my $balance = $self->charged;
878 $balance -= $_->amount foreach ( $self->cust_bill_pay );
879 $balance -= $_->amount foreach ( $self->cust_credited );
880 $balance = sprintf( "%.2f", $balance);
881 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
886 my( $self, $pkgnum ) = @_;
888 #my $balance = $self->charged;
890 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
892 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
893 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
895 $balance = sprintf( "%.2f", $balance);
896 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
902 Returns true if this invoice should be hidden. See the
903 selfservice-hide_invoices-taxclass configuraiton setting.
909 my $conf = $self->conf;
910 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
912 my @cust_bill_pkg = $self->cust_bill_pkg;
913 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
914 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
917 =item apply_payments_and_credits [ OPTION => VALUE ... ]
919 Applies unapplied payments and credits to this invoice.
921 A hash of optional arguments may be passed. Currently "manual" is supported.
922 If true, a payment receipt is sent instead of a statement when
923 'payment_receipt_email' configuration option is set.
925 If there is an error, returns the error, otherwise returns false.
929 sub apply_payments_and_credits {
930 my( $self, %options ) = @_;
931 my $conf = $self->conf;
933 local $SIG{HUP} = 'IGNORE';
934 local $SIG{INT} = 'IGNORE';
935 local $SIG{QUIT} = 'IGNORE';
936 local $SIG{TERM} = 'IGNORE';
937 local $SIG{TSTP} = 'IGNORE';
938 local $SIG{PIPE} = 'IGNORE';
940 my $oldAutoCommit = $FS::UID::AutoCommit;
941 local $FS::UID::AutoCommit = 0;
944 $self->select_for_update; #mutex
946 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
947 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
949 if ( $conf->exists('pkg-balances') ) {
950 # limit @payments & @credits to those w/ a pkgnum grepped from $self
951 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
952 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
953 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
956 while ( $self->owed > 0 and ( @payments || @credits ) ) {
959 if ( @payments && @credits ) {
961 #decide which goes first by weight of top (unapplied) line item
963 my @open_lineitems = $self->open_cust_bill_pkg;
966 max( map { $_->part_pkg->pay_weight || 0 }
971 my $max_credit_weight =
972 max( map { $_->part_pkg->credit_weight || 0 }
978 #if both are the same... payments first? it has to be something
979 if ( $max_pay_weight >= $max_credit_weight ) {
985 } elsif ( @payments ) {
987 } elsif ( @credits ) {
990 die "guru meditation #12 and 35";
994 if ( $app eq 'pay' ) {
996 my $payment = shift @payments;
997 $unapp_amount = $payment->unapplied;
998 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
999 $app->pkgnum( $payment->pkgnum )
1000 if $conf->exists('pkg-balances') && $payment->pkgnum;
1002 } elsif ( $app eq 'credit' ) {
1004 my $credit = shift @credits;
1005 $unapp_amount = $credit->credited;
1006 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1007 $app->pkgnum( $credit->pkgnum )
1008 if $conf->exists('pkg-balances') && $credit->pkgnum;
1011 die "guru meditation #12 and 35";
1015 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1016 warn "owed_pkgnum ". $app->pkgnum;
1017 $owed = $self->owed_pkgnum($app->pkgnum);
1019 $owed = $self->owed;
1021 next unless $owed > 0;
1023 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1024 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1026 $app->invnum( $self->invnum );
1028 my $error = $app->insert(%options);
1030 $dbh->rollback if $oldAutoCommit;
1031 return "Error inserting ". $app->table. " record: $error";
1033 die $error if $error;
1037 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1042 =item generate_email OPTION => VALUE ...
1050 sender address, required
1054 alternate template name, optional
1058 text attachment arrayref, optional
1062 email subject, optional
1066 notice name instead of "Invoice", optional
1070 Returns an argument list to be passed to L<FS::Misc::send_email>.
1076 sub generate_email {
1080 my $conf = $self->conf;
1082 my $me = '[FS::cust_bill::generate_email]';
1085 'from' => $args{'from'},
1086 'subject' => ($args{'subject'} || $self->email_subject),
1089 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1091 my $cust_main = $self->cust_main;
1093 if (ref($args{'to'}) eq 'ARRAY') {
1094 $return{'to'} = $args{'to'};
1096 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1097 $cust_main->invoicing_list
1101 if ( $conf->exists('invoice_html') ) {
1103 warn "$me creating HTML/text multipart message"
1106 $return{'nobody'} = 1;
1108 my $alternative = build MIME::Entity
1109 'Type' => 'multipart/alternative',
1110 #'Encoding' => '7bit',
1111 'Disposition' => 'inline'
1115 if ( $conf->exists('invoice_email_pdf')
1116 and scalar($conf->config('invoice_email_pdf_note')) ) {
1118 warn "$me using 'invoice_email_pdf_note' in multipart message"
1120 $data = [ map { $_ . "\n" }
1121 $conf->config('invoice_email_pdf_note')
1126 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1128 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1129 $data = $args{'print_text'};
1131 $data = [ $self->print_text(\%args) ];
1136 $alternative->attach(
1137 'Type' => 'text/plain',
1138 'Encoding' => 'quoted-printable',
1139 #'Encoding' => '7bit',
1141 'Disposition' => 'inline',
1148 if ( $conf->exists('invoice_email_pdf')
1149 and scalar($conf->config('invoice_email_pdf_note')) ) {
1151 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1155 $args{'from'} =~ /\@([\w\.\-]+)/;
1156 my $from = $1 || 'example.com';
1157 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1160 my $agentnum = $cust_main->agentnum;
1161 if ( defined($args{'template'}) && length($args{'template'})
1162 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1165 $logo = 'logo_'. $args{'template'}. '.png';
1169 my $image_data = $conf->config_binary( $logo, $agentnum);
1171 $image = build MIME::Entity
1172 'Type' => 'image/png',
1173 'Encoding' => 'base64',
1174 'Data' => $image_data,
1175 'Filename' => 'logo.png',
1176 'Content-ID' => "<$content_id>",
1179 if ($conf->exists('invoice-barcode')) {
1180 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1181 $barcode = build MIME::Entity
1182 'Type' => 'image/png',
1183 'Encoding' => 'base64',
1184 'Data' => $self->invoice_barcode(0),
1185 'Filename' => 'barcode.png',
1186 'Content-ID' => "<$barcode_content_id>",
1188 $args{'barcode_cid'} = $barcode_content_id;
1191 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1194 $alternative->attach(
1195 'Type' => 'text/html',
1196 'Encoding' => 'quoted-printable',
1197 'Data' => [ '<html>',
1200 ' '. encode_entities($return{'subject'}),
1203 ' <body bgcolor="#e8e8e8">',
1208 'Disposition' => 'inline',
1209 #'Filename' => 'invoice.pdf',
1213 my @otherparts = ();
1214 if ( $cust_main->email_csv_cdr ) {
1216 push @otherparts, build MIME::Entity
1217 'Type' => 'text/csv',
1218 'Encoding' => '7bit',
1219 'Data' => [ map { "$_\n" }
1220 $self->call_details('prepend_billed_number' => 1)
1222 'Disposition' => 'attachment',
1223 'Filename' => 'usage-'. $self->invnum. '.csv',
1228 if ( $conf->exists('invoice_email_pdf') ) {
1233 # multipart/alternative
1239 my $related = build MIME::Entity 'Type' => 'multipart/related',
1240 'Encoding' => '7bit';
1242 #false laziness w/Misc::send_email
1243 $related->head->replace('Content-type',
1244 $related->mime_type.
1245 '; boundary="'. $related->head->multipart_boundary. '"'.
1246 '; type=multipart/alternative'
1249 $related->add_part($alternative);
1251 $related->add_part($image) if $image;
1253 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1255 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1259 #no other attachment:
1261 # multipart/alternative
1266 $return{'content-type'} = 'multipart/related';
1267 if ($conf->exists('invoice-barcode') && $barcode) {
1268 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1270 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1272 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1273 #$return{'disposition'} = 'inline';
1279 if ( $conf->exists('invoice_email_pdf') ) {
1280 warn "$me creating PDF attachment"
1283 #mime parts arguments a la MIME::Entity->build().
1284 $return{'mimeparts'} = [
1285 { $self->mimebuild_pdf(\%args) }
1289 if ( $conf->exists('invoice_email_pdf')
1290 and scalar($conf->config('invoice_email_pdf_note')) ) {
1292 warn "$me using 'invoice_email_pdf_note'"
1294 $return{'body'} = [ map { $_ . "\n" }
1295 $conf->config('invoice_email_pdf_note')
1300 warn "$me not using 'invoice_email_pdf_note'"
1302 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1303 $return{'body'} = $args{'print_text'};
1305 $return{'body'} = [ $self->print_text(\%args) ];
1318 Returns a list suitable for passing to MIME::Entity->build(), representing
1319 this invoice as PDF attachment.
1326 'Type' => 'application/pdf',
1327 'Encoding' => 'base64',
1328 'Data' => [ $self->print_pdf(@_) ],
1329 'Disposition' => 'attachment',
1330 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1336 Sends this invoice to the destinations configured for this customer: sends
1337 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1339 Options can be passed as a hashref. Positional parameters are no longer
1342 I<template>: a suffix for alternate invoices
1344 I<agentnum>: obsolete, now does nothing.
1346 I<invoice_from> overrides the default email invoice From: address.
1348 I<amount>: obsolete, does nothing
1350 I<notice_name> overrides "Invoice" as the name of the sent document
1351 (templates from 10/2009 or newer required).
1353 I<lpr> overrides the system 'lpr' option as the command to print a document
1354 from standard input.
1360 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1361 my $conf = $self->conf;
1363 my $cust_main = $self->cust_main;
1365 my @invoicing_list = $cust_main->invoicing_list;
1368 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1369 && ! $self->invoice_noemail;
1372 if grep { $_ eq 'POST' } @invoicing_list; #postal
1374 #this has never been used post-$ORIGINAL_ISP afaik
1375 $self->fax_invoice($opt)
1376 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1382 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1384 Sends this invoice to the customer's email destination(s).
1386 Options must be passed as a hashref. Positional parameters are no longer
1389 I<template>, if specified, is the name of a suffix for alternate invoices.
1391 I<invoice_from>, if specified, overrides the default email invoice From:
1394 I<notice_name> is the name of the sent document.
1398 sub queueable_email {
1401 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1402 or die "invalid invoice number: " . $opt{invnum};
1404 my %args = map {$_ => $opt{$_}}
1406 qw( invoice_from notice_name no_coupon template );
1408 my $error = $self->email( \%args );
1409 die $error if $error;
1415 return if $self->hide;
1416 my $conf = $self->conf;
1417 my $opt = shift || {};
1418 if ($opt and !ref($opt)) {
1419 die "FS::cust_bill::email called with positional parameters";
1422 my $template = $opt->{template};
1423 my $from = delete $opt->{invoice_from};
1425 # this is where we set the From: address
1426 $from ||= $self->_agent_invoice_from || #XXX should go away
1427 $conf->config('invoice_from', $self->cust_main->agentnum );
1429 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1430 $self->cust_main->invoicing_list;
1432 if ( ! @invoicing_list ) { #no recipients
1433 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1434 die 'No recipients for customer #'. $self->custnum;
1436 #default: better to notify this person than silence
1437 @invoicing_list = ($from);
1441 # this is where we set the Subject:
1442 my $subject = $self->email_subject($template);
1444 my $error = send_email(
1445 $self->generate_email(
1447 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1448 'subject' => $subject,
1449 %$opt, # template, etc.
1452 die "can't email invoice: $error\n" if $error;
1453 #die "$error\n" if $error;
1459 my $conf = $self->conf;
1461 #my $template = scalar(@_) ? shift : '';
1464 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1467 my $cust_main = $self->cust_main;
1468 my $name = $cust_main->name;
1469 my $name_short = $cust_main->name_short;
1470 my $invoice_number = $self->invnum;
1471 my $invoice_date = $self->_date_pretty;
1473 eval qq("$subject");
1476 =item lpr_data HASHREF
1478 Returns the postscript or plaintext for this invoice as an arrayref.
1480 Options must be passed as a hashref. Positional parameters are no longer
1483 I<template>, if specified, is the name of a suffix for alternate invoices.
1485 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1491 my $conf = $self->conf;
1492 my $opt = shift || {};
1493 if ($opt and !ref($opt)) {
1494 # nobody does this anyway
1495 die "FS::cust_bill::lpr_data called with positional parameters";
1498 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1499 [ $self->$method( $opt ) ];
1504 Prints this invoice.
1506 Options must be passed as a hashref.
1508 I<template>, if specified, is the name of a suffix for alternate invoices.
1510 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1516 return if $self->hide;
1517 my $conf = $self->conf;
1518 my $opt = shift || {};
1519 if ($opt and !ref($opt)) {
1520 die "FS::cust_bill::print called with positional parameters";
1523 my $lpr = delete $opt->{lpr};
1524 if($conf->exists('invoice_print_pdf')) {
1525 # Add the invoice to the current batch.
1526 $self->batch_invoice($opt);
1530 $self->lpr_data($opt),
1531 'agentnum' => $self->cust_main->agentnum,
1537 =item fax_invoice HASHREF
1541 Options must be passed as a hashref.
1543 I<template>, if specified, is the name of a suffix for alternate invoices.
1545 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1551 return if $self->hide;
1552 my $conf = $self->conf;
1553 my $opt = shift || {};
1554 if ($opt and !ref($opt)) {
1555 die "FS::cust_bill::fax_invoice called with positional parameters";
1558 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1559 unless $conf->exists('invoice_latex');
1561 my $dialstring = $self->cust_main->getfield('fax');
1564 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1565 'dialstring' => $dialstring,
1567 die $error if $error;
1571 =item batch_invoice [ HASHREF ]
1573 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1574 isn't an open batch, one will be created.
1579 my ($self, $opt) = @_;
1580 my $bill_batch = $self->get_open_bill_batch;
1581 my $cust_bill_batch = FS::cust_bill_batch->new({
1582 batchnum => $bill_batch->batchnum,
1583 invnum => $self->invnum,
1585 return $cust_bill_batch->insert($opt);
1588 =item get_open_batch
1590 Returns the currently open batch as an FS::bill_batch object, creating a new
1591 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1596 sub get_open_bill_batch {
1598 my $conf = $self->conf;
1599 my $hashref = { status => 'O' };
1600 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1601 ? $self->cust_main->agentnum
1603 my $batch = qsearchs('bill_batch', $hashref);
1604 return $batch if $batch;
1605 $batch = FS::bill_batch->new($hashref);
1606 my $error = $batch->insert;
1607 die $error if $error;
1611 =item ftp_invoice [ TEMPLATENAME ]
1613 Sends this invoice data via FTP.
1615 TEMPLATENAME is unused?
1621 my $conf = $self->conf;
1622 my $template = scalar(@_) ? shift : '';
1625 'protocol' => 'ftp',
1626 'server' => $conf->config('cust_bill-ftpserver'),
1627 'username' => $conf->config('cust_bill-ftpusername'),
1628 'password' => $conf->config('cust_bill-ftppassword'),
1629 'dir' => $conf->config('cust_bill-ftpdir'),
1630 'format' => $conf->config('cust_bill-ftpformat'),
1634 =item spool_invoice [ TEMPLATENAME ]
1636 Spools this invoice data (see L<FS::spool_csv>)
1638 TEMPLATENAME is unused?
1644 my $conf = $self->conf;
1645 my $template = scalar(@_) ? shift : '';
1648 'format' => $conf->config('cust_bill-spoolformat'),
1649 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1653 =item send_csv OPTION => VALUE, ...
1655 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1659 protocol - currently only "ftp"
1665 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1666 and YYMMDDHHMMSS is a timestamp.
1668 See L</print_csv> for a description of the output format.
1673 my($self, %opt) = @_;
1677 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1678 mkdir $spooldir, 0700 unless -d $spooldir;
1680 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1681 my $file = "$spooldir/$tracctnum.csv";
1683 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1685 open(CSV, ">$file") or die "can't open $file: $!";
1693 if ( $opt{protocol} eq 'ftp' ) {
1694 eval "use Net::FTP;";
1696 $net = Net::FTP->new($opt{server}) or die @$;
1698 die "unknown protocol: $opt{protocol}";
1701 $net->login( $opt{username}, $opt{password} )
1702 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1704 $net->binary or die "can't set binary mode";
1706 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1708 $net->put($file) or die "can't put $file: $!";
1718 Spools CSV invoice data.
1724 =item format - any of FS::Misc::::Invoicing::spool_formats
1726 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1727 customer has the corresponding invoice destinations set (see
1728 L<FS::cust_main_invoice>).
1730 =item agent_spools - if set to a true value, will spool to per-agent files
1731 rather than a single global file
1733 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1734 append to that spool. L<FS::Cron::upload> will then send the spool file to
1737 =item balanceover - if set, only spools the invoice if the total amount owed on
1738 this invoice and all older invoices is greater than the specified amount.
1740 =item time - the "current time". Controls the printing of past due messages
1748 my($self, %opt) = @_;
1750 my $time = $opt{'time'} || time;
1751 my $cust_main = $self->cust_main;
1753 if ( $opt{'dest'} ) {
1754 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1755 $cust_main->invoicing_list;
1756 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1757 || ! keys %invoicing_list;
1760 if ( $opt{'balanceover'} ) {
1762 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1765 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1766 mkdir $spooldir, 0700 unless -d $spooldir;
1768 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1771 if ( $opt{'agent_spools'} ) {
1772 $file = 'agentnum'.$cust_main->agentnum;
1777 if ( $opt{'upload_targetnum'} ) {
1778 $spooldir .= '/target'.$opt{'upload_targetnum'};
1779 mkdir $spooldir, 0700 unless -d $spooldir;
1780 } # otherwise it just goes into export.xxx/cust_bill
1782 if ( lc($opt{'format'}) eq 'billco' ) {
1786 $file = "$spooldir/$file.csv";
1788 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1790 open(CSV, ">>$file") or die "can't open $file: $!";
1791 flock(CSV, LOCK_EX);
1796 if ( lc($opt{'format'}) eq 'billco' ) {
1798 flock(CSV, LOCK_UN);
1801 $file =~ s/-header.csv$/-detail.csv/;
1803 open(CSV,">>$file") or die "can't open $file: $!";
1804 flock(CSV, LOCK_EX);
1808 print CSV $detail if defined($detail);
1810 flock(CSV, LOCK_UN);
1817 =item print_csv OPTION => VALUE, ...
1819 Returns CSV data for this invoice.
1823 format - 'default', 'billco', 'oneline', 'bridgestone'
1825 Returns a list consisting of two scalars. The first is a single line of CSV
1826 header information for this invoice. The second is one or more lines of CSV
1827 detail information for this invoice.
1829 If I<format> is not specified or "default", the fields of the CSV file are as
1832 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1833 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1837 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1839 B<record_type> is C<cust_bill> for the initial header line only. The
1840 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1841 fields are filled in.
1843 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1844 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1847 =item invnum - invoice number
1849 =item custnum - customer number
1851 =item _date - invoice date
1853 =item charged - total invoice amount
1855 =item first - customer first name
1857 =item last - customer first name
1859 =item company - company name
1861 =item address1 - address line 1
1863 =item address2 - address line 1
1873 =item pkg - line item description
1875 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1877 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1879 =item sdate - start date for recurring fee
1881 =item edate - end date for recurring fee
1885 If I<format> is "billco", the fields of the header CSV file are as follows:
1887 +-------------------------------------------------------------------+
1888 | FORMAT HEADER FILE |
1889 |-------------------------------------------------------------------|
1890 | Field | Description | Name | Type | Width |
1891 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1892 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1893 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1894 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1895 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1896 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1897 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1898 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1899 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1900 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1901 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1902 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1903 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1904 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1905 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1906 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1907 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1908 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1909 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1910 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1911 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1912 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1913 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1914 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1915 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1916 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1917 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1918 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1919 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1920 +-------+-------------------------------+------------+------+-------+
1922 If I<format> is "billco", the fields of the detail CSV file are as follows:
1924 FORMAT FOR DETAIL FILE
1926 Field | Description | Name | Type | Width
1927 1 | N/A-Leave Empty | RC | CHAR | 2
1928 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1929 3 | Account Number | TRACCTNUM | CHAR | 15
1930 4 | Invoice Number | TRINVOICE | CHAR | 15
1931 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1932 6 | Transaction Detail | DETAILS | CHAR | 100
1933 7 | Amount | AMT | NUM* | 9
1934 8 | Line Format Control** | LNCTRL | CHAR | 2
1935 9 | Grouping Code | GROUP | CHAR | 2
1936 10 | User Defined | ACCT CODE | CHAR | 15
1938 If format is 'oneline', there is no detail file. Each invoice has a
1939 header line only, with the fields:
1941 Agent number, agent name, customer number, first name, last name, address
1942 line 1, address line 2, city, state, zip, invoice date, invoice number,
1943 amount charged, amount due, previous balance, due date.
1945 and then, for each line item, three columns containing the package number,
1946 description, and amount.
1948 If format is 'bridgestone', there is no detail file. Each invoice has a
1949 header line with the following fields in a fixed-width format:
1951 Customer number (in display format), date, name (first last), company,
1952 address 1, address 2, city, state, zip.
1954 This is a mailing list format, and has no per-invoice fields. To avoid
1955 sending redundant notices, the spooling event should have a "once" or
1956 "once_percust_every" condition.
1961 my($self, %opt) = @_;
1963 eval "use Text::CSV_XS";
1966 my $cust_main = $self->cust_main;
1968 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1969 my $format = lc($opt{'format'});
1971 my $time = $opt{'time'} || time;
1973 my $tracctnum = ''; #leaking out from billco-specific sections :/
1974 if ( $format eq 'billco' ) {
1977 $self->conf->config('billco-account_num', $cust_main->agentnum);
1979 $tracctnum = $account_num eq 'display_custnum'
1980 ? $cust_main->display_custnum
1981 : $opt{'tracctnum'};
1984 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1986 my $duedate = $self->due_date2str('%m/%d/%Y'); #date_format?
1988 my( $previous_balance, @unused ) = $self->previous; #previous balance
1990 my $pmt_cr_applied = 0;
1991 $pmt_cr_applied += $_->{'amount'}
1992 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1994 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1997 '', # 1 | N/A-Leave Empty CHAR 2
1998 '', # 2 | N/A-Leave Empty CHAR 15
1999 $tracctnum, # 3 | Transaction Account No CHAR 15
2000 $self->invnum, # 4 | Transaction Invoice No CHAR 15
2001 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
2002 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
2003 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
2004 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
2005 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
2006 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
2007 '', # 10 | Ancillary Billing Information CHAR 30
2008 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
2009 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
2012 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
2015 $duedate, # 14 | Bill Due Date CHAR 10
2017 $previous_balance, # 15 | Previous Balance NUM* 9
2018 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2019 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2020 $totaldue, # 18 | Total Amt Due NUM* 9
2021 $totaldue, # 19 | Total Amt Due NUM* 9
2022 '', # 20 | 30 Day Aging NUM* 9
2023 '', # 21 | 60 Day Aging NUM* 9
2024 '', # 22 | 90 Day Aging NUM* 9
2025 'N', # 23 | Y/N CHAR 1
2026 '', # 24 | Remittance automation CHAR 100
2027 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2028 $self->custnum, # 26 | Customer Reference Number CHAR 15
2029 '0', # 27 | Federal Tax*** NUM* 9
2030 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2031 '0', # 29 | Other Taxes & Fees*** NUM* 9
2034 } elsif ( $format eq 'oneline' ) { #name
2036 my ($previous_balance) = $self->previous;
2037 $previous_balance = sprintf('%.2f', $previous_balance);
2038 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2044 $self->_items_pkg, #_items_nontax? no sections or anything
2049 $cust_main->agentnum,
2050 $cust_main->agent->agent,
2054 $cust_main->company,
2055 $cust_main->address1,
2056 $cust_main->address2,
2062 time2str("%x", $self->_date),
2067 $self->due_date2str("%x"),
2072 } elsif ( $format eq 'bridgestone' ) {
2074 # bypass the CSV stuff and just return this
2075 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2076 my $zip = $cust_main->zip;
2078 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2082 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2084 $cust_main->display_custnum,
2086 uc(substr($cust_main->contact_firstlast,0,30)),
2087 uc(substr($cust_main->company ,0,30)),
2088 uc(substr($cust_main->address1 ,0,30)),
2089 uc(substr($cust_main->address2 ,0,30)),
2090 uc(substr($cust_main->city ,0,20)),
2091 uc($cust_main->state),
2097 } elsif ( $format eq 'ics' ) {
2099 my $bill = $cust_main->bill_location;
2100 my $zip = $bill->zip;
2104 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2109 # minor false laziness with print_generic
2110 my ($previous_balance) = $self->previous;
2111 my $balance_due = $self->owed + $previous_balance;
2112 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2113 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2116 if ( $self->due_date and $time >= $self->due_date ) {
2117 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2121 my $header = sprintf(
2122 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2123 $cust_main->display_custnum, #BID
2124 uc($cust_main->first), #FNAME
2125 uc($cust_main->last), #LNAME
2126 '00', #BATCH, should this ever be anything else?
2127 uc($cust_main->company), #COMP
2128 uc($bill->address1), #STREET1
2129 uc($bill->address2), #STREET2
2130 uc($bill->city), #CITY
2131 uc($bill->state), #STATE
2134 time2str('%Y%m%d', $self->_date), #BILL_DATE
2135 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2136 ( map {sprintf('%0.2f', $_)}
2137 $balance_due, #AMNT_DUE
2138 $previous_balance, #PREV_BAL
2139 $payment_total, #PYMT_RCVD
2140 $credit_total, #CREDITS
2141 $previous_balance, #BEG_BAL--is this correct?
2142 $self->charged, #NEW_CHRG
2145 $past_due, #PAST_MSG
2149 my %svc_class = ('' => ''); # maybe cache this more persistently?
2151 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2153 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2154 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2158 my @dates = ( $self->_date, undef );
2159 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2160 $dates[1] = $prev->sdate; #questionable
2163 # generate an 01 detail for each service
2164 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2165 foreach my $cust_svc ( @svcs ) {
2166 $show_pkgnum = ''; # hide it if we're showing svcnums
2168 my $svcpart = $cust_svc->svcpart;
2169 if (!exists($svc_class{$svcpart})) {
2170 my $classnum = $cust_svc->part_svc->classnum;
2171 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2173 $svc_class{$svcpart} = $part_svc_class ?
2174 $part_svc_class->classname :
2178 my @h_label = $cust_svc->label(@dates, 'I');
2179 push @details, sprintf('01%-9s%-20s%-47s',
2181 $svc_class{$svcpart},
2184 } #foreach $cust_svc
2187 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2188 if ($cust_bill_pkg->recur > 0) {
2189 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2190 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2192 push @details, sprintf('02%-6s%-60s%-10s',
2195 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2197 } #foreach $cust_bill_pkg
2199 # Tag this row so that we know whether this is one page (1), two pages
2200 # (2), # or "big" (B). The tag will be stripped off before uploading.
2201 if ( scalar(@details) < 12 ) {
2203 } elsif ( scalar(@details) < 58 ) {
2209 return join('', $header, @details, "\n");
2217 time2str("%x", $self->_date),
2218 sprintf("%.2f", $self->charged),
2219 ( map { $cust_main->getfield($_) }
2220 qw( first last company address1 address2 city state zip country ) ),
2222 ) or die "can't create csv";
2225 my $header = $csv->string. "\n";
2228 if ( lc($opt{'format'}) eq 'billco' ) {
2231 foreach my $item ( $self->_items_pkg ) {
2234 '', # 1 | N/A-Leave Empty CHAR 2
2235 '', # 2 | N/A-Leave Empty CHAR 15
2236 $tracctnum, # 3 | Account Number CHAR 15
2237 $self->invnum, # 4 | Invoice Number CHAR 15
2238 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2239 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2240 $item->{'amount'}, # 7 | Amount NUM* 9
2241 '', # 8 | Line Format Control** CHAR 2
2242 '', # 9 | Grouping Code CHAR 2
2243 '', # 10 | User Defined CHAR 15
2246 $detail .= $csv->string. "\n";
2250 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2256 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2258 my($pkg, $setup, $recur, $sdate, $edate);
2259 if ( $cust_bill_pkg->pkgnum ) {
2261 ($pkg, $setup, $recur, $sdate, $edate) = (
2262 $cust_bill_pkg->part_pkg->pkg,
2263 ( $cust_bill_pkg->setup != 0
2264 ? sprintf("%.2f", $cust_bill_pkg->setup )
2266 ( $cust_bill_pkg->recur != 0
2267 ? sprintf("%.2f", $cust_bill_pkg->recur )
2269 ( $cust_bill_pkg->sdate
2270 ? time2str("%x", $cust_bill_pkg->sdate)
2272 ($cust_bill_pkg->edate
2273 ?time2str("%x", $cust_bill_pkg->edate)
2277 } else { #pkgnum tax
2278 next unless $cust_bill_pkg->setup != 0;
2279 $pkg = $cust_bill_pkg->desc;
2280 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2281 ( $sdate, $edate ) = ( '', '' );
2287 ( map { '' } (1..11) ),
2288 ($pkg, $setup, $recur, $sdate, $edate)
2289 ) or die "can't create csv";
2291 $detail .= $csv->string. "\n";
2297 ( $header, $detail );
2303 Pays this invoice with a compliemntary payment. If there is an error,
2304 returns the error, otherwise returns false.
2310 my $cust_pay = new FS::cust_pay ( {
2311 'invnum' => $self->invnum,
2312 'paid' => $self->owed,
2315 'payinfo' => $self->cust_main->payinfo,
2323 Attempts to pay this invoice with a credit card payment via a
2324 Business::OnlinePayment realtime gateway. See
2325 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2326 for supported processors.
2332 $self->realtime_bop( 'CC', @_ );
2337 Attempts to pay this invoice with an electronic check (ACH) payment via a
2338 Business::OnlinePayment realtime gateway. See
2339 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2340 for supported processors.
2346 $self->realtime_bop( 'ECHECK', @_ );
2351 Attempts to pay this invoice with phone bill (LEC) payment via a
2352 Business::OnlinePayment realtime gateway. See
2353 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2354 for supported processors.
2360 $self->realtime_bop( 'LEC', @_ );
2364 my( $self, $method ) = (shift,shift);
2365 my $conf = $self->conf;
2368 my $cust_main = $self->cust_main;
2369 my $balance = $cust_main->balance;
2370 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2371 $amount = sprintf("%.2f", $amount);
2372 return "not run (balance $balance)" unless $amount > 0;
2374 my $description = 'Internet Services';
2375 if ( $conf->exists('business-onlinepayment-description') ) {
2376 my $dtempl = $conf->config('business-onlinepayment-description');
2378 my $agent_obj = $cust_main->agent
2379 or die "can't retreive agent for $cust_main (agentnum ".
2380 $cust_main->agentnum. ")";
2381 my $agent = $agent_obj->agent;
2382 my $pkgs = join(', ',
2383 map { $_->part_pkg->pkg }
2384 grep { $_->pkgnum } $self->cust_bill_pkg
2386 $description = eval qq("$dtempl");
2389 $cust_main->realtime_bop($method, $amount,
2390 'description' => $description,
2391 'invnum' => $self->invnum,
2392 #this didn't do what we want, it just calls apply_payments_and_credits
2394 'apply_to_invoice' => 1,
2397 #this changes application behavior: auto payments
2398 #triggered against a specific invoice are now applied
2399 #to that invoice instead of oldest open.
2405 =item batch_card OPTION => VALUE...
2407 Adds a payment for this invoice to the pending credit card batch (see
2408 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2409 runs the payment using a realtime gateway.
2414 my ($self, %options) = @_;
2415 my $cust_main = $self->cust_main;
2417 $options{invnum} = $self->invnum;
2419 $cust_main->batch_card(%options);
2422 sub _agent_template {
2424 $self->cust_main->agent_template;
2427 sub _agent_invoice_from {
2429 $self->cust_main->agent_invoice_from;
2432 =item invoice_barcode DIR_OR_FALSE
2434 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2435 it is taken as the temp directory where the PNG file will be generated and the
2436 PNG file name is returned. Otherwise, the PNG image itself is returned.
2440 sub invoice_barcode {
2441 my ($self, $dir) = (shift,shift);
2443 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2444 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2445 my $gd = $gdbar->plot(Height => 30);
2448 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2452 ) or die "can't open temp file: $!\n";
2453 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2454 my $png_file = $bh->filename;
2461 =item invnum_date_pretty
2463 Returns a string with the invoice number and date, for example:
2464 "Invoice #54 (3/20/2008)"
2468 sub invnum_date_pretty {
2470 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2473 #sub _items_extra_usage_sections {
2475 # my $escape = shift;
2477 # my %sections = ();
2479 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2480 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2482 # next unless $cust_bill_pkg->pkgnum > 0;
2484 # foreach my $section ( keys %usage_class ) {
2486 # my $usage = $cust_bill_pkg->usage($section);
2488 # next unless $usage && $usage > 0;
2490 # $sections{$section} ||= 0;
2491 # $sections{$section} += $usage;
2497 # map { { 'description' => &{$escape}($_),
2498 # 'subtotal' => $sections{$_},
2499 # 'summarized' => '',
2500 # 'tax_section' => '',
2503 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2507 sub _items_extra_usage_sections {
2509 my $conf = $self->conf;
2517 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2519 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2520 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2521 next unless $cust_bill_pkg->pkgnum > 0;
2523 foreach my $classnum ( keys %usage_class ) {
2524 my $section = $usage_class{$classnum}->classname;
2525 $classnums{$section} = $classnum;
2527 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2528 my $amount = $detail->amount;
2529 next unless $amount && $amount > 0;
2531 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2532 $sections{$section}{amount} += $amount; #subtotal
2533 $sections{$section}{calls}++;
2534 $sections{$section}{duration} += $detail->duration;
2536 my $desc = $detail->regionname;
2537 my $description = $desc;
2538 $description = substr($desc, 0, $maxlength). '...'
2539 if $format eq 'latex' && length($desc) > $maxlength;
2541 $lines{$section}{$desc} ||= {
2542 description => &{$escape}($description),
2543 #pkgpart => $part_pkg->pkgpart,
2544 pkgnum => $cust_bill_pkg->pkgnum,
2549 #unit_amount => $cust_bill_pkg->unitrecur,
2550 quantity => $cust_bill_pkg->quantity,
2551 product_code => 'N/A',
2552 ext_description => [],
2555 $lines{$section}{$desc}{amount} += $amount;
2556 $lines{$section}{$desc}{calls}++;
2557 $lines{$section}{$desc}{duration} += $detail->duration;
2563 my %sectionmap = ();
2564 foreach (keys %sections) {
2565 my $usage_class = $usage_class{$classnums{$_}};
2566 $sectionmap{$_} = { 'description' => &{$escape}($_),
2567 'amount' => $sections{$_}{amount}, #subtotal
2568 'calls' => $sections{$_}{calls},
2569 'duration' => $sections{$_}{duration},
2571 'tax_section' => '',
2572 'sort_weight' => $usage_class->weight,
2573 ( $usage_class->format
2574 ? ( map { $_ => $usage_class->$_($format) }
2575 qw( description_generator header_generator total_generator total_line_generator )
2582 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2586 foreach my $section ( keys %lines ) {
2587 foreach my $line ( keys %{$lines{$section}} ) {
2588 my $l = $lines{$section}{$line};
2589 $l->{section} = $sectionmap{$section};
2590 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2591 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2596 return(\@sections, \@lines);
2602 my $end = $self->_date;
2604 # start at date of previous invoice + 1 second or 0 if no previous invoice
2605 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2606 $start = 0 if !$start;
2609 my $cust_main = $self->cust_main;
2610 my @pkgs = $cust_main->all_pkgs;
2611 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2614 foreach my $pkg ( @pkgs ) {
2615 my @h_cust_svc = $pkg->h_cust_svc($end);
2616 foreach my $h_cust_svc ( @h_cust_svc ) {
2617 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2618 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2620 my $inserted = $h_cust_svc->date_inserted;
2621 my $deleted = $h_cust_svc->date_deleted;
2622 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2624 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2626 # DID either activated or ported in; cannot be both for same DID simultaneously
2627 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2628 && (!$phone_inserted->lnp_status
2629 || $phone_inserted->lnp_status eq ''
2630 || $phone_inserted->lnp_status eq 'native')) {
2633 else { # this one not so clean, should probably move to (h_)svc_phone
2634 my $phone_portedin = qsearchs( 'h_svc_phone',
2635 { 'svcnum' => $h_cust_svc->svcnum,
2636 'lnp_status' => 'portedin' },
2637 FS::h_svc_phone->sql_h_searchs($end),
2639 $num_portedin++ if $phone_portedin;
2642 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2643 if($deleted >= $start && $deleted <= $end && $phone_deleted
2644 && (!$phone_deleted->lnp_status
2645 || $phone_deleted->lnp_status ne 'portingout')) {
2648 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2649 && $phone_deleted->lnp_status
2650 && $phone_deleted->lnp_status eq 'portingout') {
2654 # increment usage minutes
2655 if ( $phone_inserted ) {
2656 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2657 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2660 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2663 # don't look at this service again
2664 push @seen, $h_cust_svc->svcnum;
2668 $minutes = sprintf("%d", $minutes);
2669 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2670 . "$num_deactivated Ported-Out: $num_portedout ",
2671 "Total Minutes: $minutes");
2674 sub _items_accountcode_cdr {
2679 my $section = { 'amount' => 0,
2682 'sort_weight' => '',
2684 'description' => 'Usage by Account Code',
2690 my %accountcodes = ();
2692 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2693 next unless $cust_bill_pkg->pkgnum > 0;
2695 my @header = $cust_bill_pkg->details_header;
2696 next unless scalar(@header);
2697 $section->{'header'} = join(',',@header);
2699 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2701 $section->{'header'} = $detail->formatted('format' => $format)
2702 if($detail->detail eq $section->{'header'});
2704 my $accountcode = $detail->accountcode;
2705 next unless $accountcode;
2707 my $amount = $detail->amount;
2708 next unless $amount && $amount > 0;
2710 $accountcodes{$accountcode} ||= {
2711 description => $accountcode,
2718 product_code => 'N/A',
2719 section => $section,
2720 ext_description => [ $section->{'header'} ],
2724 $section->{'amount'} += $amount;
2725 $accountcodes{$accountcode}{'amount'} += $amount;
2726 $accountcodes{$accountcode}{calls}++;
2727 $accountcodes{$accountcode}{duration} += $detail->duration;
2728 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2732 foreach my $l ( values %accountcodes ) {
2733 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2734 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2735 foreach my $sorted_detail ( @sorted_detail ) {
2736 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2738 delete $l->{detail_temp};
2742 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2744 return ($section,\@sorted_lines);
2747 sub _items_svc_phone_sections {
2749 my $conf = $self->conf;
2757 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2759 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2760 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2762 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2763 next unless $cust_bill_pkg->pkgnum > 0;
2765 my @header = $cust_bill_pkg->details_header;
2766 next unless scalar(@header);
2768 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2770 my $phonenum = $detail->phonenum;
2771 next unless $phonenum;
2773 my $amount = $detail->amount;
2774 next unless $amount && $amount > 0;
2776 $sections{$phonenum} ||= { 'amount' => 0,
2779 'sort_weight' => -1,
2780 'phonenum' => $phonenum,
2782 $sections{$phonenum}{amount} += $amount; #subtotal
2783 $sections{$phonenum}{calls}++;
2784 $sections{$phonenum}{duration} += $detail->duration;
2786 my $desc = $detail->regionname;
2787 my $description = $desc;
2788 $description = substr($desc, 0, $maxlength). '...'
2789 if $format eq 'latex' && length($desc) > $maxlength;
2791 $lines{$phonenum}{$desc} ||= {
2792 description => &{$escape}($description),
2793 #pkgpart => $part_pkg->pkgpart,
2801 product_code => 'N/A',
2802 ext_description => [],
2805 $lines{$phonenum}{$desc}{amount} += $amount;
2806 $lines{$phonenum}{$desc}{calls}++;
2807 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2809 my $line = $usage_class{$detail->classnum}->classname;
2810 $sections{"$phonenum $line"} ||=
2814 'sort_weight' => $usage_class{$detail->classnum}->weight,
2815 'phonenum' => $phonenum,
2816 'header' => [ @header ],
2818 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2819 $sections{"$phonenum $line"}{calls}++;
2820 $sections{"$phonenum $line"}{duration} += $detail->duration;
2822 $lines{"$phonenum $line"}{$desc} ||= {
2823 description => &{$escape}($description),
2824 #pkgpart => $part_pkg->pkgpart,
2832 product_code => 'N/A',
2833 ext_description => [],
2836 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2837 $lines{"$phonenum $line"}{$desc}{calls}++;
2838 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2839 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2840 $detail->formatted('format' => $format);
2845 my %sectionmap = ();
2846 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2847 foreach ( keys %sections ) {
2848 my @header = @{ $sections{$_}{header} || [] };
2850 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2851 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2852 my $usage_class = $summary ? $simple : $usage_simple;
2853 my $ending = $summary ? ' usage charges' : '';
2856 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2858 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2859 'amount' => $sections{$_}{amount}, #subtotal
2860 'calls' => $sections{$_}{calls},
2861 'duration' => $sections{$_}{duration},
2863 'tax_section' => '',
2864 'phonenum' => $sections{$_}{phonenum},
2865 'sort_weight' => $sections{$_}{sort_weight},
2866 'post_total' => $summary, #inspire pagebreak
2868 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2869 qw( description_generator
2872 total_line_generator
2879 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2880 $a->{sort_weight} <=> $b->{sort_weight}
2885 foreach my $section ( keys %lines ) {
2886 foreach my $line ( keys %{$lines{$section}} ) {
2887 my $l = $lines{$section}{$line};
2888 $l->{section} = $sectionmap{$section};
2889 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2890 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2895 if($conf->exists('phone_usage_class_summary')) {
2896 # this only works with Latex
2900 # after this, we'll have only two sections per DID:
2901 # Calls Summary and Calls Detail
2902 foreach my $section ( @sections ) {
2903 if($section->{'post_total'}) {
2904 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2905 $section->{'total_line_generator'} = sub { '' };
2906 $section->{'total_generator'} = sub { '' };
2907 $section->{'header_generator'} = sub { '' };
2908 $section->{'description_generator'} = '';
2909 push @newsections, $section;
2910 my %calls_detail = %$section;
2911 $calls_detail{'post_total'} = '';
2912 $calls_detail{'sort_weight'} = '';
2913 $calls_detail{'description_generator'} = sub { '' };
2914 $calls_detail{'header_generator'} = sub {
2915 return ' & Date/Time & Called Number & Duration & Price'
2916 if $format eq 'latex';
2919 $calls_detail{'description'} = 'Calls Detail: '
2920 . $section->{'phonenum'};
2921 push @newsections, \%calls_detail;
2925 # after this, each usage class is collapsed/summarized into a single
2926 # line under the Calls Summary section
2927 foreach my $newsection ( @newsections ) {
2928 if($newsection->{'post_total'}) { # this means Calls Summary
2929 foreach my $section ( @sections ) {
2930 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2931 && !$section->{'post_total'});
2932 my $newdesc = $section->{'description'};
2933 my $tn = $section->{'phonenum'};
2934 $newdesc =~ s/$tn//g;
2935 my $line = { ext_description => [],
2939 calls => $section->{'calls'},
2940 section => $newsection,
2941 duration => $section->{'duration'},
2942 description => $newdesc,
2943 amount => sprintf("%.2f",$section->{'amount'}),
2944 product_code => 'N/A',
2946 push @newlines, $line;
2951 # after this, Calls Details is populated with all CDRs
2952 foreach my $newsection ( @newsections ) {
2953 if(!$newsection->{'post_total'}) { # this means Calls Details
2954 foreach my $line ( @lines ) {
2955 next unless (scalar(@{$line->{'ext_description'}}) &&
2956 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2958 my @extdesc = @{$line->{'ext_description'}};
2960 foreach my $extdesc ( @extdesc ) {
2961 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2962 push @newextdesc, $extdesc;
2964 $line->{'ext_description'} = \@newextdesc;
2965 $line->{'section'} = $newsection;
2966 push @newlines, $line;
2971 return(\@newsections, \@newlines);
2974 return(\@sections, \@lines);
2978 sub _items_previous {
2980 my $conf = $self->conf;
2981 my $cust_main = $self->cust_main;
2982 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2984 foreach ( @pr_cust_bill ) {
2985 my $date = $conf->exists('invoice_show_prior_due_date')
2986 ? 'due '. $_->due_date2str($date_format)
2987 : time2str($date_format, $_->_date);
2989 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2990 #'pkgpart' => 'N/A',
2992 'amount' => sprintf("%.2f", $_->owed),
2998 # 'description' => 'Previous Balance',
2999 # #'pkgpart' => 'N/A',
3000 # 'pkgnum' => 'N/A',
3001 # 'amount' => sprintf("%10.2f", $pr_total ),
3002 # 'ext_description' => [ map {
3003 # "Invoice ". $_->invnum.
3004 # " (". time2str("%x",$_->_date). ") ".
3005 # sprintf("%10.2f", $_->owed)
3006 # } @pr_cust_bill ],
3011 sub _items_credits {
3012 my( $self, %opt ) = @_;
3013 my $trim_len = $opt{'trim_len'} || 60;
3018 if ( $self->conf->exists('previous_balance-payments_since') ) {
3019 if ( $opt{'template'} eq 'statement' ) {
3020 # then the current bill is a "statement" (i.e. an invoice sent as
3021 # a payment receipt)
3022 # and in that case we want to see payments on or after THIS invoice
3023 @objects = qsearch('cust_credit', {
3024 'custnum' => $self->custnum,
3025 '_date' => {op => '>=', value => $self->_date},
3029 $date = $self->previous_bill->_date if $self->previous_bill;
3030 @objects = qsearch('cust_credit', {
3031 'custnum' => $self->custnum,
3032 '_date' => {op => '>=', value => $date},
3036 @objects = $self->cust_credited;
3039 foreach my $obj ( @objects ) {
3040 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3042 my $reason = substr($cust_credit->reason, 0, $trim_len);
3043 $reason .= '...' if length($reason) < length($cust_credit->reason);
3044 $reason = " ($reason) " if $reason;
3047 #'description' => 'Credit ref\#'. $_->crednum.
3048 # " (". time2str("%x",$_->cust_credit->_date) .")".
3050 'description' => $self->mt('Credit applied').' '.
3051 time2str($date_format,$obj->_date). $reason,
3052 'amount' => sprintf("%.2f",$obj->amount),
3060 sub _items_payments {
3065 my $detailed = $self->conf->exists('invoice_payment_details');
3067 if ( $self->conf->exists('previous_balance-payments_since') ) {
3068 # then show payments dated on/after the previous bill...
3069 if ( $opt{'template'} eq 'statement' ) {
3070 # then the current bill is a "statement" (i.e. an invoice sent as
3071 # a payment receipt)
3072 # and in that case we want to see payments on or after THIS invoice
3073 @objects = qsearch('cust_pay', {
3074 'custnum' => $self->custnum,
3075 '_date' => {op => '>=', value => $self->_date},
3078 # the normal case: payments on or after the previous invoice
3080 $date = $self->previous_bill->_date if $self->previous_bill;
3081 @objects = qsearch('cust_pay', {
3082 'custnum' => $self->custnum,
3083 '_date' => {op => '>=', value => $date},
3085 # and before the current bill...
3086 @objects = grep { $_->_date < $self->_date } @objects;
3089 @objects = $self->cust_bill_pay;
3092 foreach my $obj (@objects) {
3093 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3094 my $desc = $self->mt('Payment received').' '.
3095 time2str($date_format, $cust_pay->_date );
3096 $desc .= $self->mt(' via ') .
3097 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3101 'description' => $desc,
3102 'amount' => sprintf("%.2f", $obj->amount )
3110 =item call_details [ OPTION => VALUE ... ]
3112 Returns an array of CSV strings representing the call details for this invoice
3113 The only option available is the boolean prepend_billed_number
3118 my ($self, %opt) = @_;
3120 my $format_function = sub { shift };
3122 if ($opt{prepend_billed_number}) {
3123 $format_function = sub {
3127 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3132 my @details = map { $_->details( 'format_function' => $format_function,
3133 'escape_function' => sub{ return() },
3137 $self->cust_bill_pkg;
3138 my $header = $details[0];
3139 ( $header, grep { $_ ne $header } @details );
3149 =item process_reprint
3153 sub process_reprint {
3154 process_re_X('print', @_);
3157 =item process_reemail
3161 sub process_reemail {
3162 process_re_X('email', @_);
3170 process_re_X('fax', @_);
3178 process_re_X('ftp', @_);
3185 sub process_respool {
3186 process_re_X('spool', @_);
3189 use Storable qw(thaw);
3193 my( $method, $job ) = ( shift, shift );
3194 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3196 my $param = thaw(decode_base64(shift));
3197 warn Dumper($param) if $DEBUG;
3208 # spool_invoice ftp_invoice fax_invoice print_invoice
3209 my($method, $job, %param ) = @_;
3211 warn "re_X $method for job $job with param:\n".
3212 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3215 #some false laziness w/search/cust_bill.html
3217 my $orderby = 'ORDER BY cust_bill._date';
3219 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3221 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3223 my @cust_bill = qsearch( {
3224 #'select' => "cust_bill.*",
3225 'table' => 'cust_bill',
3226 'addl_from' => $addl_from,
3228 'extra_sql' => $extra_sql,
3229 'order_by' => $orderby,
3233 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3235 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3238 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3239 foreach my $cust_bill ( @cust_bill ) {
3240 $cust_bill->$method();
3242 if ( $job ) { #progressbar foo
3244 if ( time - $min_sec > $last ) {
3245 my $error = $job->update_statustext(
3246 int( 100 * $num / scalar(@cust_bill) )
3248 die $error if $error;
3259 =head1 CLASS METHODS
3265 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3270 my ($class, $start, $end) = @_;
3272 $class->paid_sql($start, $end). ' - '.
3273 $class->credited_sql($start, $end);
3278 Returns an SQL fragment to retreive the net amount (charged minus credited).
3283 my ($class, $start, $end) = @_;
3284 'charged - '. $class->credited_sql($start, $end);
3289 Returns an SQL fragment to retreive the amount paid against this invoice.
3294 my ($class, $start, $end) = @_;
3295 $start &&= "AND cust_bill_pay._date <= $start";
3296 $end &&= "AND cust_bill_pay._date > $end";
3297 $start = '' unless defined($start);
3298 $end = '' unless defined($end);
3299 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3300 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3305 Returns an SQL fragment to retreive the amount credited against this invoice.
3310 my ($class, $start, $end) = @_;
3311 $start &&= "AND cust_credit_bill._date <= $start";
3312 $end &&= "AND cust_credit_bill._date > $end";
3313 $start = '' unless defined($start);
3314 $end = '' unless defined($end);
3315 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3316 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3321 Returns an SQL fragment to retrieve the due date of an invoice.
3322 Currently only supported on PostgreSQL.
3327 my $conf = new FS::Conf;
3331 cust_bill.invoice_terms,
3332 cust_main.invoice_terms,
3333 \''.($conf->config('invoice_default_terms') || '').'\'
3334 ), E\'Net (\\\\d+)\'
3336 ) * 86400 + cust_bill._date'
3339 =item search_sql_where HASHREF
3341 Class method which returns an SQL WHERE fragment to search for parameters
3342 specified in HASHREF. Valid parameters are
3348 List reference of start date, end date, as UNIX timestamps.
3358 List reference of charged limits (exclusive).
3362 List reference of charged limits (exclusive).
3366 flag, return open invoices only
3370 flag, return net invoices only
3374 =item newest_percust
3378 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3382 sub search_sql_where {
3383 my($class, $param) = @_;
3385 warn "$me search_sql_where called with params: \n".
3386 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3392 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3393 push @search, "cust_main.agentnum = $1";
3397 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3398 push @search, "cust_main.refnum = $1";
3402 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3403 push @search, "cust_bill.custnum = $1";
3406 #customer classnum (false laziness w/ cust_main/Search.pm)
3407 if ( $param->{'cust_classnum'} ) {
3409 my @classnum = ref( $param->{'cust_classnum'} )
3410 ? @{ $param->{'cust_classnum'} }
3411 : ( $param->{'cust_classnum'} );
3413 @classnum = grep /^(\d*)$/, @classnum;
3416 push @search, '( '. join(' OR ', map {
3417 $_ ? "cust_main.classnum = $_"
3418 : "cust_main.classnum IS NULL"
3428 if ( $param->{_date} ) {
3429 my($beginning, $ending) = @{$param->{_date}};
3431 push @search, "cust_bill._date >= $beginning",
3432 "cust_bill._date < $ending";
3436 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3437 push @search, "cust_bill.invnum >= $1";
3439 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3440 push @search, "cust_bill.invnum <= $1";
3444 if ( $param->{charged} ) {
3445 my @charged = ref($param->{charged})
3446 ? @{ $param->{charged} }
3447 : ($param->{charged});
3449 push @search, map { s/^charged/cust_bill.charged/; $_; }
3453 my $owed_sql = FS::cust_bill->owed_sql;
3456 if ( $param->{owed} ) {
3457 my @owed = ref($param->{owed})
3458 ? @{ $param->{owed} }
3460 push @search, map { s/^owed/$owed_sql/; $_; }
3465 push @search, "0 != $owed_sql"
3466 if $param->{'open'};
3467 push @search, '0 != '. FS::cust_bill->net_sql
3471 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3472 if $param->{'days'};
3475 if ( $param->{'newest_percust'} ) {
3477 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3478 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3480 my @newest_where = map { my $x = $_;
3481 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3484 grep ! /^cust_main./, @search;
3485 my $newest_where = scalar(@newest_where)
3486 ? ' AND '. join(' AND ', @newest_where)
3490 push @search, "cust_bill._date = (
3491 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3492 WHERE newest_cust_bill.custnum = cust_bill.custnum
3498 #promised_date - also has an option to accept nulls
3499 if ( $param->{promised_date} ) {
3500 my($beginning, $ending, $null) = @{$param->{promised_date}};
3502 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3503 "cust_bill.promised_date < $ending )" .
3504 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3507 #agent virtualization
3508 my $curuser = $FS::CurrentUser::CurrentUser;
3509 if ( $curuser->username eq 'fs_queue'
3510 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3512 my $newuser = qsearchs('access_user', {
3513 'username' => $username,
3517 $curuser = $newuser;
3519 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3522 push @search, $curuser->agentnums_sql;
3524 join(' AND ', @search );
3536 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3537 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base