2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $DEBUG $me );
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]';
49 FS::cust_bill - Object methods for cust_bill records
55 $record = new FS::cust_bill \%hash;
56 $record = new FS::cust_bill { 'column' => 'value' };
58 $error = $record->insert;
60 $error = $new_record->replace($old_record);
62 $error = $record->delete;
64 $error = $record->check;
66 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
68 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
70 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
72 @cust_pay_objects = $cust_bill->cust_pay;
74 $tax_amount = $record->tax;
76 @lines = $cust_bill->print_text;
77 @lines = $cust_bill->print_text('time' => $time);
81 An FS::cust_bill object represents an invoice; a declaration that a customer
82 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
83 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
84 following fields are currently supported:
90 =item invnum - primary key (assigned automatically for new invoices)
92 =item custnum - customer (see L<FS::cust_main>)
94 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
95 L<Time::Local> and L<Date::Parse> for conversion functions.
97 =item charged - amount of this invoice
99 =item invoice_terms - optional terms override for this specific invoice
103 Customer info at invoice generation time
107 =item billing_balance - the customer's balance at the time the invoice was
108 generated (not including charges on this invoice)
110 =item previous_balance - the billing_balance of this customer's previous
111 invoice plus the charges on that invoice
119 =item printed - deprecated
127 =item closed - books closed flag, empty or `Y'
129 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
131 =item agent_invid - legacy invoice number
133 =item promised_date - customer promised payment date, for collection
143 Creates a new invoice. To add the invoice to the database, see L<"insert">.
144 Invoices are normally created by calling the bill method of a customer object
145 (see L<FS::cust_main>).
149 sub table { 'cust_bill'; }
151 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
152 # (except email_subject and invnum_date_pretty)
155 $self->conf->config('notice_name') || 'Invoice'
158 sub cust_linked { $_[0]->cust_main_custnum; }
159 sub cust_unlinked_msg {
161 "WARNING: can't find cust_main.custnum ". $self->custnum.
162 ' (cust_bill.invnum '. $self->invnum. ')';
167 Adds this invoice to the database ("Posts" the invoice). If there is an error,
168 returns the error, otherwise returns false.
174 warn "$me insert called\n" if $DEBUG;
176 local $SIG{HUP} = 'IGNORE';
177 local $SIG{INT} = 'IGNORE';
178 local $SIG{QUIT} = 'IGNORE';
179 local $SIG{TERM} = 'IGNORE';
180 local $SIG{TSTP} = 'IGNORE';
181 local $SIG{PIPE} = 'IGNORE';
183 my $oldAutoCommit = $FS::UID::AutoCommit;
184 local $FS::UID::AutoCommit = 0;
187 my $error = $self->SUPER::insert;
189 $dbh->rollback if $oldAutoCommit;
193 if ( $self->get('cust_bill_pkg') ) {
194 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
195 $cust_bill_pkg->invnum($self->invnum);
196 my $error = $cust_bill_pkg->insert;
198 $dbh->rollback if $oldAutoCommit;
199 return "can't create invoice line item: $error";
204 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
211 Voids this invoice: deletes the invoice and adds a record of the voided invoice
212 to the FS::cust_bill_void table (and related tables starting from
213 FS::cust_bill_pkg_void).
219 my $reason = scalar(@_) ? shift : '';
221 local $SIG{HUP} = 'IGNORE';
222 local $SIG{INT} = 'IGNORE';
223 local $SIG{QUIT} = 'IGNORE';
224 local $SIG{TERM} = 'IGNORE';
225 local $SIG{TSTP} = 'IGNORE';
226 local $SIG{PIPE} = 'IGNORE';
228 my $oldAutoCommit = $FS::UID::AutoCommit;
229 local $FS::UID::AutoCommit = 0;
232 my $cust_bill_void = new FS::cust_bill_void ( {
233 map { $_ => $self->get($_) } $self->fields
235 $cust_bill_void->reason($reason);
236 my $error = $cust_bill_void->insert;
238 $dbh->rollback if $oldAutoCommit;
242 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
243 my $error = $cust_bill_pkg->void($reason);
245 $dbh->rollback if $oldAutoCommit;
250 $error = $self->delete;
252 $dbh->rollback if $oldAutoCommit;
256 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
264 This method now works but you probably shouldn't use it. Instead, apply a
265 credit against the invoice, or use the new void method.
267 Using this method to delete invoices outright is really, really bad. There
268 would be no record you ever posted this invoice, and there are no check to
269 make sure charged = 0 or that there are no associated cust_bill_pkg records.
271 Really, don't use it.
277 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
279 local $SIG{HUP} = 'IGNORE';
280 local $SIG{INT} = 'IGNORE';
281 local $SIG{QUIT} = 'IGNORE';
282 local $SIG{TERM} = 'IGNORE';
283 local $SIG{TSTP} = 'IGNORE';
284 local $SIG{PIPE} = 'IGNORE';
286 my $oldAutoCommit = $FS::UID::AutoCommit;
287 local $FS::UID::AutoCommit = 0;
290 foreach my $table (qw(
301 foreach my $linked ( $self->$table() ) {
302 my $error = $linked->delete;
304 $dbh->rollback if $oldAutoCommit;
311 my $error = $self->SUPER::delete(@_);
313 $dbh->rollback if $oldAutoCommit;
317 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
323 =item replace [ OLD_RECORD ]
325 You can, but probably shouldn't modify invoices...
327 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
328 supplied, replaces this record. If there is an error, returns the error,
329 otherwise returns false.
333 #replace can be inherited from Record.pm
335 # replace_check is now the preferred way to #implement replace data checks
336 # (so $object->replace() works without an argument)
339 my( $new, $old ) = ( shift, shift );
340 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
341 #return "Can't change _date!" unless $old->_date eq $new->_date;
342 return "Can't change _date" unless $old->_date == $new->_date;
343 return "Can't change charged" unless $old->charged == $new->charged
344 || $old->charged == 0
345 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
351 =item add_cc_surcharge
357 sub add_cc_surcharge {
358 my ($self, $pkgnum, $amount) = (shift, shift, shift);
361 my $cust_bill_pkg = new FS::cust_bill_pkg({
362 'invnum' => $self->invnum,
366 $error = $cust_bill_pkg->insert;
367 return $error if $error;
369 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
370 $self->charged($self->charged+$amount);
371 $error = $self->replace;
372 return $error if $error;
374 $self->apply_payments_and_credits;
380 Checks all fields to make sure this is a valid invoice. If there is an error,
381 returns the error, otherwise returns false. Called by the insert and replace
390 $self->ut_numbern('invnum')
391 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
392 || $self->ut_numbern('_date')
393 || $self->ut_money('charged')
394 || $self->ut_numbern('printed')
395 || $self->ut_enum('closed', [ '', 'Y' ])
396 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
397 || $self->ut_numbern('agent_invid') #varchar?
399 return $error if $error;
401 $self->_date(time) unless $self->_date;
403 $self->printed(0) if $self->printed eq '';
410 Returns the displayed invoice number for this invoice: agent_invid if
411 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
417 if ( $self->agent_invid
418 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
419 return $self->agent_invid;
421 return $self->invnum;
427 Returns the customer's last invoice before this one.
433 if ( !$self->get('previous_bill') ) {
434 $self->set('previous_bill', qsearchs({
435 'table' => 'cust_bill',
436 'hashref' => { 'custnum' => $self->custnum,
437 '_date' => { op=>'<', value=>$self->_date } },
438 'order_by' => 'ORDER BY _date DESC LIMIT 1',
441 $self->get('previous_bill');
446 Returns a list consisting of the total previous balance for this customer,
447 followed by the previous outstanding invoices (as FS::cust_bill objects also).
454 my @cust_bill = sort { $a->_date <=> $b->_date }
455 grep { $_->owed != 0 }
456 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
457 #'_date' => { op=>'<', value=>$self->_date },
458 'invnum' => { op=>'<', value=>$self->invnum },
461 foreach ( @cust_bill ) { $total += $_->owed; }
465 =item enable_previous
467 Whether to show the 'Previous Charges' section when printing this invoice.
468 The negation of the 'disable_previous_balance' config setting.
472 sub enable_previous {
474 my $agentnum = $self->cust_main->agentnum;
475 !$self->conf->exists('disable_previous_balance', $agentnum);
480 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
487 { 'table' => 'cust_bill_pkg',
488 'hashref' => { 'invnum' => $self->invnum },
489 'order_by' => 'ORDER BY billpkgnum',
494 =item cust_bill_pkg_pkgnum PKGNUM
496 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
501 sub cust_bill_pkg_pkgnum {
502 my( $self, $pkgnum ) = @_;
504 { 'table' => 'cust_bill_pkg',
505 'hashref' => { 'invnum' => $self->invnum,
508 'order_by' => 'ORDER BY billpkgnum',
515 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
522 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
523 $self->cust_bill_pkg;
525 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
530 Returns true if any of the packages (or their definitions) corresponding to the
531 line items for this invoice have the no_auto flag set.
537 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
540 =item open_cust_bill_pkg
542 Returns the open line items for this invoice.
544 Note that cust_bill_pkg with both setup and recur fees are returned as two
545 separate line items, each with only one fee.
549 # modeled after cust_main::open_cust_bill
550 sub open_cust_bill_pkg {
553 # grep { $_->owed > 0 } $self->cust_bill_pkg
555 my %other = ( 'recur' => 'setup',
556 'setup' => 'recur', );
558 foreach my $field ( qw( recur setup )) {
559 push @open, map { $_->set( $other{$field}, 0 ); $_; }
560 grep { $_->owed($field) > 0 }
561 $self->cust_bill_pkg;
567 =item cust_bill_event
569 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
573 sub cust_bill_event {
575 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
578 =item num_cust_bill_event
580 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
584 sub num_cust_bill_event {
587 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
588 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
589 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
590 $sth->fetchrow_arrayref->[0];
595 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
599 #false laziness w/cust_pkg.pm
603 'table' => 'cust_event',
604 'addl_from' => 'JOIN part_event USING ( eventpart )',
605 'hashref' => { 'tablenum' => $self->invnum },
606 'extra_sql' => " AND eventtable = 'cust_bill' ",
612 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
616 #false laziness w/cust_pkg.pm
620 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
621 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
622 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
623 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
624 $sth->fetchrow_arrayref->[0];
629 Returns the customer (see L<FS::cust_main>) for this invoice.
635 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
638 =item cust_suspend_if_balance_over AMOUNT
640 Suspends the customer associated with this invoice if the total amount owed on
641 this invoice and all older invoices is greater than the specified amount.
643 Returns a list: an empty list on success or a list of errors.
647 sub cust_suspend_if_balance_over {
648 my( $self, $amount ) = ( shift, shift );
649 my $cust_main = $self->cust_main;
650 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
653 $cust_main->suspend(@_);
659 Depreciated. See the cust_credited method.
661 #Returns a list consisting of the total previous credited (see
662 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
663 #outstanding credits (FS::cust_credit objects).
669 croak "FS::cust_bill->cust_credit depreciated; see ".
670 "FS::cust_bill->cust_credit_bill";
673 #my @cust_credit = sort { $a->_date <=> $b->_date }
674 # grep { $_->credited != 0 && $_->_date < $self->_date }
675 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
677 #foreach (@cust_credit) { $total += $_->credited; }
678 #$total, @cust_credit;
683 Depreciated. See the cust_bill_pay method.
685 #Returns all payments (see L<FS::cust_pay>) for this invoice.
691 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
693 #sort { $a->_date <=> $b->_date }
694 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
700 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
703 sub cust_bill_pay_batch {
705 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
710 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
716 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
717 sort { $a->_date <=> $b->_date }
718 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
723 =item cust_credit_bill
725 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
731 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
732 sort { $a->_date <=> $b->_date }
733 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
737 sub cust_credit_bill {
738 shift->cust_credited(@_);
741 #=item cust_bill_pay_pkgnum PKGNUM
743 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
744 #with matching pkgnum.
748 #sub cust_bill_pay_pkgnum {
749 # my( $self, $pkgnum ) = @_;
750 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
751 # sort { $a->_date <=> $b->_date }
752 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
753 # 'pkgnum' => $pkgnum,
758 =item cust_bill_pay_pkg PKGNUM
760 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
761 applied against the matching pkgnum.
765 sub cust_bill_pay_pkg {
766 my( $self, $pkgnum ) = @_;
769 'select' => 'cust_bill_pay_pkg.*',
770 'table' => 'cust_bill_pay_pkg',
771 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
772 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
773 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
774 " AND cust_bill_pkg.pkgnum = $pkgnum",
779 #=item cust_credited_pkgnum PKGNUM
781 #=item cust_credit_bill_pkgnum PKGNUM
783 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
784 #with matching pkgnum.
788 #sub cust_credited_pkgnum {
789 # my( $self, $pkgnum ) = @_;
790 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
791 # sort { $a->_date <=> $b->_date }
792 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
793 # 'pkgnum' => $pkgnum,
798 #sub cust_credit_bill_pkgnum {
799 # shift->cust_credited_pkgnum(@_);
802 =item cust_credit_bill_pkg PKGNUM
804 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
805 applied against the matching pkgnum.
809 sub cust_credit_bill_pkg {
810 my( $self, $pkgnum ) = @_;
813 'select' => 'cust_credit_bill_pkg.*',
814 'table' => 'cust_credit_bill_pkg',
815 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
816 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
817 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
818 " AND cust_bill_pkg.pkgnum = $pkgnum",
823 =item cust_bill_batch
825 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
829 sub cust_bill_batch {
831 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
836 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
837 hash keyed by term length.
843 FS::discount_plan->all($self);
848 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
855 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
857 foreach (@taxlines) { $total += $_->setup; }
863 Returns the amount owed (still outstanding) on this invoice, which is charged
864 minus all payment applications (see L<FS::cust_bill_pay>) and credit
865 applications (see L<FS::cust_credit_bill>).
871 my $balance = $self->charged;
872 $balance -= $_->amount foreach ( $self->cust_bill_pay );
873 $balance -= $_->amount foreach ( $self->cust_credited );
874 $balance = sprintf( "%.2f", $balance);
875 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
880 my( $self, $pkgnum ) = @_;
882 #my $balance = $self->charged;
884 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
886 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
887 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
889 $balance = sprintf( "%.2f", $balance);
890 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
896 Returns true if this invoice should be hidden. See the
897 selfservice-hide_invoices-taxclass configuraiton setting.
903 my $conf = $self->conf;
904 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
906 my @cust_bill_pkg = $self->cust_bill_pkg;
907 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
908 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
911 =item apply_payments_and_credits [ OPTION => VALUE ... ]
913 Applies unapplied payments and credits to this invoice.
915 A hash of optional arguments may be passed. Currently "manual" is supported.
916 If true, a payment receipt is sent instead of a statement when
917 'payment_receipt_email' configuration option is set.
919 If there is an error, returns the error, otherwise returns false.
923 sub apply_payments_and_credits {
924 my( $self, %options ) = @_;
925 my $conf = $self->conf;
927 local $SIG{HUP} = 'IGNORE';
928 local $SIG{INT} = 'IGNORE';
929 local $SIG{QUIT} = 'IGNORE';
930 local $SIG{TERM} = 'IGNORE';
931 local $SIG{TSTP} = 'IGNORE';
932 local $SIG{PIPE} = 'IGNORE';
934 my $oldAutoCommit = $FS::UID::AutoCommit;
935 local $FS::UID::AutoCommit = 0;
938 $self->select_for_update; #mutex
940 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
941 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
943 if ( $conf->exists('pkg-balances') ) {
944 # limit @payments & @credits to those w/ a pkgnum grepped from $self
945 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
946 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
947 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
950 while ( $self->owed > 0 and ( @payments || @credits ) ) {
953 if ( @payments && @credits ) {
955 #decide which goes first by weight of top (unapplied) line item
957 my @open_lineitems = $self->open_cust_bill_pkg;
960 max( map { $_->part_pkg->pay_weight || 0 }
965 my $max_credit_weight =
966 max( map { $_->part_pkg->credit_weight || 0 }
972 #if both are the same... payments first? it has to be something
973 if ( $max_pay_weight >= $max_credit_weight ) {
979 } elsif ( @payments ) {
981 } elsif ( @credits ) {
984 die "guru meditation #12 and 35";
988 if ( $app eq 'pay' ) {
990 my $payment = shift @payments;
991 $unapp_amount = $payment->unapplied;
992 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
993 $app->pkgnum( $payment->pkgnum )
994 if $conf->exists('pkg-balances') && $payment->pkgnum;
996 } elsif ( $app eq 'credit' ) {
998 my $credit = shift @credits;
999 $unapp_amount = $credit->credited;
1000 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1001 $app->pkgnum( $credit->pkgnum )
1002 if $conf->exists('pkg-balances') && $credit->pkgnum;
1005 die "guru meditation #12 and 35";
1009 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1010 warn "owed_pkgnum ". $app->pkgnum;
1011 $owed = $self->owed_pkgnum($app->pkgnum);
1013 $owed = $self->owed;
1015 next unless $owed > 0;
1017 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1018 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1020 $app->invnum( $self->invnum );
1022 my $error = $app->insert(%options);
1024 $dbh->rollback if $oldAutoCommit;
1025 return "Error inserting ". $app->table. " record: $error";
1027 die $error if $error;
1031 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1036 =item generate_email OPTION => VALUE ...
1044 sender address, required
1048 alternate template name, optional
1052 text attachment arrayref, optional
1056 email subject, optional
1060 notice name instead of "Invoice", optional
1064 Returns an argument list to be passed to L<FS::Misc::send_email>.
1070 sub generate_email {
1074 my $conf = $self->conf;
1076 my $me = '[FS::cust_bill::generate_email]';
1079 'from' => $args{'from'},
1080 'subject' => ($args{'subject'} || $self->email_subject),
1081 'custnum' => $self->custnum,
1082 'msgtype' => 'invoice',
1085 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1087 my $cust_main = $self->cust_main;
1089 if (ref($args{'to'}) eq 'ARRAY') {
1090 $return{'to'} = $args{'to'};
1092 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1093 $cust_main->invoicing_list
1097 if ( $conf->exists('invoice_html') ) {
1099 warn "$me creating HTML/text multipart message"
1102 $return{'nobody'} = 1;
1104 my $alternative = build MIME::Entity
1105 'Type' => 'multipart/alternative',
1106 #'Encoding' => '7bit',
1107 'Disposition' => 'inline'
1111 if ( $conf->exists('invoice_email_pdf')
1112 and scalar($conf->config('invoice_email_pdf_note')) ) {
1114 warn "$me using 'invoice_email_pdf_note' in multipart message"
1116 $data = [ map { $_ . "\n" }
1117 $conf->config('invoice_email_pdf_note')
1122 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1124 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1125 $data = $args{'print_text'};
1127 $data = [ $self->print_text(\%args) ];
1132 $alternative->attach(
1133 'Type' => 'text/plain',
1134 'Encoding' => 'quoted-printable',
1135 #'Encoding' => '7bit',
1137 'Disposition' => 'inline',
1144 if ( $conf->exists('invoice_email_pdf')
1145 and scalar($conf->config('invoice_email_pdf_note')) ) {
1147 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1151 $args{'from'} =~ /\@([\w\.\-]+)/;
1152 my $from = $1 || 'example.com';
1153 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1156 my $agentnum = $cust_main->agentnum;
1157 if ( defined($args{'template'}) && length($args{'template'})
1158 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1161 $logo = 'logo_'. $args{'template'}. '.png';
1165 my $image_data = $conf->config_binary( $logo, $agentnum);
1167 $image = build MIME::Entity
1168 'Type' => 'image/png',
1169 'Encoding' => 'base64',
1170 'Data' => $image_data,
1171 'Filename' => 'logo.png',
1172 'Content-ID' => "<$content_id>",
1175 if ($conf->exists('invoice-barcode')) {
1176 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1177 $barcode = build MIME::Entity
1178 'Type' => 'image/png',
1179 'Encoding' => 'base64',
1180 'Data' => $self->invoice_barcode(0),
1181 'Filename' => 'barcode.png',
1182 'Content-ID' => "<$barcode_content_id>",
1184 $args{'barcode_cid'} = $barcode_content_id;
1187 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1190 $alternative->attach(
1191 'Type' => 'text/html',
1192 'Encoding' => 'quoted-printable',
1193 'Data' => [ '<html>',
1196 ' '. encode_entities($return{'subject'}),
1199 ' <body bgcolor="#e8e8e8">',
1204 'Disposition' => 'inline',
1205 #'Filename' => 'invoice.pdf',
1209 my @otherparts = ();
1210 if ( $cust_main->email_csv_cdr ) {
1212 push @otherparts, build MIME::Entity
1213 'Type' => 'text/csv',
1214 'Encoding' => '7bit',
1215 'Data' => [ map { "$_\n" }
1216 $self->call_details('prepend_billed_number' => 1)
1218 'Disposition' => 'attachment',
1219 'Filename' => 'usage-'. $self->invnum. '.csv',
1224 if ( $conf->exists('invoice_email_pdf') ) {
1229 # multipart/alternative
1235 my $related = build MIME::Entity 'Type' => 'multipart/related',
1236 'Encoding' => '7bit';
1238 #false laziness w/Misc::send_email
1239 $related->head->replace('Content-type',
1240 $related->mime_type.
1241 '; boundary="'. $related->head->multipart_boundary. '"'.
1242 '; type=multipart/alternative'
1245 $related->add_part($alternative);
1247 $related->add_part($image) if $image;
1249 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1251 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1255 #no other attachment:
1257 # multipart/alternative
1262 $return{'content-type'} = 'multipart/related';
1263 if ($conf->exists('invoice-barcode') && $barcode) {
1264 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1266 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1268 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1269 #$return{'disposition'} = 'inline';
1275 if ( $conf->exists('invoice_email_pdf') ) {
1276 warn "$me creating PDF attachment"
1279 #mime parts arguments a la MIME::Entity->build().
1280 $return{'mimeparts'} = [
1281 { $self->mimebuild_pdf(\%args) }
1285 if ( $conf->exists('invoice_email_pdf')
1286 and scalar($conf->config('invoice_email_pdf_note')) ) {
1288 warn "$me using 'invoice_email_pdf_note'"
1290 $return{'body'} = [ map { $_ . "\n" }
1291 $conf->config('invoice_email_pdf_note')
1296 warn "$me not using 'invoice_email_pdf_note'"
1298 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1299 $return{'body'} = $args{'print_text'};
1301 $return{'body'} = [ $self->print_text(\%args) ];
1314 Returns a list suitable for passing to MIME::Entity->build(), representing
1315 this invoice as PDF attachment.
1322 'Type' => 'application/pdf',
1323 'Encoding' => 'base64',
1324 'Data' => [ $self->print_pdf(@_) ],
1325 'Disposition' => 'attachment',
1326 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1332 Sends this invoice to the destinations configured for this customer: sends
1333 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1335 Options can be passed as a hashref. Positional parameters are no longer
1338 I<template>: a suffix for alternate invoices
1340 I<agentnum>: obsolete, now does nothing.
1342 I<invoice_from> overrides the default email invoice From: address.
1344 I<amount>: obsolete, does nothing
1346 I<notice_name> overrides "Invoice" as the name of the sent document
1347 (templates from 10/2009 or newer required).
1349 I<lpr> overrides the system 'lpr' option as the command to print a document
1350 from standard input.
1356 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1357 my $conf = $self->conf;
1359 my $cust_main = $self->cust_main;
1361 my @invoicing_list = $cust_main->invoicing_list;
1364 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1365 && ! $self->invoice_noemail;
1368 if grep { $_ eq 'POST' } @invoicing_list; #postal
1370 #this has never been used post-$ORIGINAL_ISP afaik
1371 $self->fax_invoice($opt)
1372 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1378 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1380 Sends this invoice to the customer's email destination(s).
1382 Options must be passed as a hashref. Positional parameters are no longer
1385 I<template>, if specified, is the name of a suffix for alternate invoices.
1387 I<invoice_from>, if specified, overrides the default email invoice From:
1390 I<notice_name> is the name of the sent document.
1394 sub queueable_email {
1397 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1398 or die "invalid invoice number: " . $opt{invnum};
1400 my %args = map {$_ => $opt{$_}}
1402 qw( invoice_from notice_name no_coupon template );
1404 my $error = $self->email( \%args );
1405 die $error if $error;
1411 return if $self->hide;
1412 my $conf = $self->conf;
1413 my $opt = shift || {};
1414 if ($opt and !ref($opt)) {
1415 die "FS::cust_bill::email called with positional parameters";
1418 my $template = $opt->{template};
1419 my $from = delete $opt->{invoice_from};
1421 # this is where we set the From: address
1422 $from ||= $self->_agent_invoice_from || #XXX should go away
1423 $conf->config('invoice_from', $self->cust_main->agentnum );
1425 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1426 $self->cust_main->invoicing_list;
1428 if ( ! @invoicing_list ) { #no recipients
1429 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1430 die 'No recipients for customer #'. $self->custnum;
1432 #default: better to notify this person than silence
1433 @invoicing_list = ($from);
1437 # this is where we set the Subject:
1438 my $subject = $self->email_subject($template);
1440 my $error = send_email(
1441 $self->generate_email(
1443 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1444 'subject' => $subject,
1445 %$opt, # template, etc.
1448 die "can't email invoice: $error\n" if $error;
1449 #die "$error\n" if $error;
1455 my $conf = $self->conf;
1457 #my $template = scalar(@_) ? shift : '';
1460 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1463 my $cust_main = $self->cust_main;
1464 my $name = $cust_main->name;
1465 my $name_short = $cust_main->name_short;
1466 my $invoice_number = $self->invnum;
1467 my $invoice_date = $self->_date_pretty;
1469 eval qq("$subject");
1472 =item lpr_data HASHREF
1474 Returns the postscript or plaintext for this invoice as an arrayref.
1476 Options must be passed as a hashref. Positional parameters are no longer
1479 I<template>, if specified, is the name of a suffix for alternate invoices.
1481 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1487 my $conf = $self->conf;
1488 my $opt = shift || {};
1489 if ($opt and !ref($opt)) {
1490 # nobody does this anyway
1491 die "FS::cust_bill::lpr_data called with positional parameters";
1494 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1495 [ $self->$method( $opt ) ];
1500 Prints this invoice.
1502 Options must be passed as a hashref.
1504 I<template>, if specified, is the name of a suffix for alternate invoices.
1506 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1512 return if $self->hide;
1513 my $conf = $self->conf;
1514 my $opt = shift || {};
1515 if ($opt and !ref($opt)) {
1516 die "FS::cust_bill::print called with positional parameters";
1519 my $lpr = delete $opt->{lpr};
1520 if($conf->exists('invoice_print_pdf')) {
1521 # Add the invoice to the current batch.
1522 $self->batch_invoice($opt);
1526 $self->lpr_data($opt),
1527 'agentnum' => $self->cust_main->agentnum,
1533 =item fax_invoice HASHREF
1537 Options must be passed as a hashref.
1539 I<template>, if specified, is the name of a suffix for alternate invoices.
1541 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1547 return if $self->hide;
1548 my $conf = $self->conf;
1549 my $opt = shift || {};
1550 if ($opt and !ref($opt)) {
1551 die "FS::cust_bill::fax_invoice called with positional parameters";
1554 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1555 unless $conf->exists('invoice_latex');
1557 my $dialstring = $self->cust_main->getfield('fax');
1560 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1561 'dialstring' => $dialstring,
1563 die $error if $error;
1567 =item batch_invoice [ HASHREF ]
1569 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1570 isn't an open batch, one will be created.
1575 my ($self, $opt) = @_;
1576 my $bill_batch = $self->get_open_bill_batch;
1577 my $cust_bill_batch = FS::cust_bill_batch->new({
1578 batchnum => $bill_batch->batchnum,
1579 invnum => $self->invnum,
1581 return $cust_bill_batch->insert($opt);
1584 =item get_open_batch
1586 Returns the currently open batch as an FS::bill_batch object, creating a new
1587 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1592 sub get_open_bill_batch {
1594 my $conf = $self->conf;
1595 my $hashref = { status => 'O' };
1596 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1597 ? $self->cust_main->agentnum
1599 my $batch = qsearchs('bill_batch', $hashref);
1600 return $batch if $batch;
1601 $batch = FS::bill_batch->new($hashref);
1602 my $error = $batch->insert;
1603 die $error if $error;
1607 =item ftp_invoice [ TEMPLATENAME ]
1609 Sends this invoice data via FTP.
1611 TEMPLATENAME is unused?
1617 my $conf = $self->conf;
1618 my $template = scalar(@_) ? shift : '';
1621 'protocol' => 'ftp',
1622 'server' => $conf->config('cust_bill-ftpserver'),
1623 'username' => $conf->config('cust_bill-ftpusername'),
1624 'password' => $conf->config('cust_bill-ftppassword'),
1625 'dir' => $conf->config('cust_bill-ftpdir'),
1626 'format' => $conf->config('cust_bill-ftpformat'),
1630 =item spool_invoice [ TEMPLATENAME ]
1632 Spools this invoice data (see L<FS::spool_csv>)
1634 TEMPLATENAME is unused?
1640 my $conf = $self->conf;
1641 my $template = scalar(@_) ? shift : '';
1644 'format' => $conf->config('cust_bill-spoolformat'),
1645 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1649 =item send_csv OPTION => VALUE, ...
1651 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1655 protocol - currently only "ftp"
1661 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1662 and YYMMDDHHMMSS is a timestamp.
1664 See L</print_csv> for a description of the output format.
1669 my($self, %opt) = @_;
1673 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1674 mkdir $spooldir, 0700 unless -d $spooldir;
1676 # don't localize dates here, they're a defined format
1677 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1678 my $file = "$spooldir/$tracctnum.csv";
1680 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1682 open(CSV, ">$file") or die "can't open $file: $!";
1690 if ( $opt{protocol} eq 'ftp' ) {
1691 eval "use Net::FTP;";
1693 $net = Net::FTP->new($opt{server}) or die @$;
1695 die "unknown protocol: $opt{protocol}";
1698 $net->login( $opt{username}, $opt{password} )
1699 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1701 $net->binary or die "can't set binary mode";
1703 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1705 $net->put($file) or die "can't put $file: $!";
1715 Spools CSV invoice data.
1721 =item format - any of FS::Misc::::Invoicing::spool_formats
1723 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1724 customer has the corresponding invoice destinations set (see
1725 L<FS::cust_main_invoice>).
1727 =item agent_spools - if set to a true value, will spool to per-agent files
1728 rather than a single global file
1730 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1731 append to that spool. L<FS::Cron::upload> will then send the spool file to
1734 =item balanceover - if set, only spools the invoice if the total amount owed on
1735 this invoice and all older invoices is greater than the specified amount.
1737 =item time - the "current time". Controls the printing of past due messages
1745 my($self, %opt) = @_;
1747 my $time = $opt{'time'} || time;
1748 my $cust_main = $self->cust_main;
1750 if ( $opt{'dest'} ) {
1751 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1752 $cust_main->invoicing_list;
1753 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1754 || ! keys %invoicing_list;
1757 if ( $opt{'balanceover'} ) {
1759 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1762 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1763 mkdir $spooldir, 0700 unless -d $spooldir;
1765 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1768 if ( $opt{'agent_spools'} ) {
1769 $file = 'agentnum'.$cust_main->agentnum;
1774 if ( $opt{'upload_targetnum'} ) {
1775 $spooldir .= '/target'.$opt{'upload_targetnum'};
1776 mkdir $spooldir, 0700 unless -d $spooldir;
1777 } # otherwise it just goes into export.xxx/cust_bill
1779 if ( lc($opt{'format'}) eq 'billco' ) {
1783 $file = "$spooldir/$file.csv";
1785 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1787 open(CSV, ">>$file") or die "can't open $file: $!";
1788 flock(CSV, LOCK_EX);
1793 if ( lc($opt{'format'}) eq 'billco' ) {
1795 flock(CSV, LOCK_UN);
1798 $file =~ s/-header.csv$/-detail.csv/;
1800 open(CSV,">>$file") or die "can't open $file: $!";
1801 flock(CSV, LOCK_EX);
1805 print CSV $detail if defined($detail);
1807 flock(CSV, LOCK_UN);
1814 =item print_csv OPTION => VALUE, ...
1816 Returns CSV data for this invoice.
1820 format - 'default', 'billco', 'oneline', 'bridgestone'
1822 Returns a list consisting of two scalars. The first is a single line of CSV
1823 header information for this invoice. The second is one or more lines of CSV
1824 detail information for this invoice.
1826 If I<format> is not specified or "default", the fields of the CSV file are as
1829 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1830 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1834 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1836 B<record_type> is C<cust_bill> for the initial header line only. The
1837 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1838 fields are filled in.
1840 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1841 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1844 =item invnum - invoice number
1846 =item custnum - customer number
1848 =item _date - invoice date
1850 =item charged - total invoice amount
1852 =item first - customer first name
1854 =item last - customer first name
1856 =item company - company name
1858 =item address1 - address line 1
1860 =item address2 - address line 1
1870 =item pkg - line item description
1872 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1874 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1876 =item sdate - start date for recurring fee
1878 =item edate - end date for recurring fee
1882 If I<format> is "billco", the fields of the header CSV file are as follows:
1884 +-------------------------------------------------------------------+
1885 | FORMAT HEADER FILE |
1886 |-------------------------------------------------------------------|
1887 | Field | Description | Name | Type | Width |
1888 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1889 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1890 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1891 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1892 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1893 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1894 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1895 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1896 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1897 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1898 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1899 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1900 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1901 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1902 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1903 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1904 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1905 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1906 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1907 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1908 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1909 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1910 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1911 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1912 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1913 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1914 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1915 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1916 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1917 +-------+-------------------------------+------------+------+-------+
1919 If I<format> is "billco", the fields of the detail CSV file are as follows:
1921 FORMAT FOR DETAIL FILE
1923 Field | Description | Name | Type | Width
1924 1 | N/A-Leave Empty | RC | CHAR | 2
1925 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1926 3 | Account Number | TRACCTNUM | CHAR | 15
1927 4 | Invoice Number | TRINVOICE | CHAR | 15
1928 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1929 6 | Transaction Detail | DETAILS | CHAR | 100
1930 7 | Amount | AMT | NUM* | 9
1931 8 | Line Format Control** | LNCTRL | CHAR | 2
1932 9 | Grouping Code | GROUP | CHAR | 2
1933 10 | User Defined | ACCT CODE | CHAR | 15
1935 If format is 'oneline', there is no detail file. Each invoice has a
1936 header line only, with the fields:
1938 Agent number, agent name, customer number, first name, last name, address
1939 line 1, address line 2, city, state, zip, invoice date, invoice number,
1940 amount charged, amount due, previous balance, due date.
1942 and then, for each line item, three columns containing the package number,
1943 description, and amount.
1945 If format is 'bridgestone', there is no detail file. Each invoice has a
1946 header line with the following fields in a fixed-width format:
1948 Customer number (in display format), date, name (first last), company,
1949 address 1, address 2, city, state, zip.
1951 This is a mailing list format, and has no per-invoice fields. To avoid
1952 sending redundant notices, the spooling event should have a "once" or
1953 "once_percust_every" condition.
1958 my($self, %opt) = @_;
1960 eval "use Text::CSV_XS";
1963 my $cust_main = $self->cust_main;
1965 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1966 my $format = lc($opt{'format'});
1968 my $time = $opt{'time'} || time;
1970 my $tracctnum = ''; #leaking out from billco-specific sections :/
1971 if ( $format eq 'billco' ) {
1974 $self->conf->config('billco-account_num', $cust_main->agentnum);
1976 $tracctnum = $account_num eq 'display_custnum'
1977 ? $cust_main->display_custnum
1978 : $opt{'tracctnum'};
1981 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1983 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1985 my( $previous_balance, @unused ) = $self->previous; #previous balance
1987 my $pmt_cr_applied = 0;
1988 $pmt_cr_applied += $_->{'amount'}
1989 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1991 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1994 '', # 1 | N/A-Leave Empty CHAR 2
1995 '', # 2 | N/A-Leave Empty CHAR 15
1996 $tracctnum, # 3 | Transaction Account No CHAR 15
1997 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1998 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1999 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
2000 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
2001 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
2002 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
2003 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
2004 '', # 10 | Ancillary Billing Information CHAR 30
2005 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
2006 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
2009 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
2012 $duedate, # 14 | Bill Due Date CHAR 10
2014 $previous_balance, # 15 | Previous Balance NUM* 9
2015 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2016 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2017 $totaldue, # 18 | Total Amt Due NUM* 9
2018 $totaldue, # 19 | Total Amt Due NUM* 9
2019 '', # 20 | 30 Day Aging NUM* 9
2020 '', # 21 | 60 Day Aging NUM* 9
2021 '', # 22 | 90 Day Aging NUM* 9
2022 'N', # 23 | Y/N CHAR 1
2023 '', # 24 | Remittance automation CHAR 100
2024 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2025 $self->custnum, # 26 | Customer Reference Number CHAR 15
2026 '0', # 27 | Federal Tax*** NUM* 9
2027 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2028 '0', # 29 | Other Taxes & Fees*** NUM* 9
2031 } elsif ( $format eq 'oneline' ) { #name
2033 my ($previous_balance) = $self->previous;
2034 $previous_balance = sprintf('%.2f', $previous_balance);
2035 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2041 $self->_items_pkg, #_items_nontax? no sections or anything
2046 $cust_main->agentnum,
2047 $cust_main->agent->agent,
2051 $cust_main->company,
2052 $cust_main->address1,
2053 $cust_main->address2,
2059 time2str("%x", $self->_date),
2064 $self->due_date2str("%x"),
2069 } elsif ( $format eq 'bridgestone' ) {
2071 # bypass the CSV stuff and just return this
2072 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2073 my $zip = $cust_main->zip;
2075 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2079 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2081 $cust_main->display_custnum,
2083 uc(substr($cust_main->contact_firstlast,0,30)),
2084 uc(substr($cust_main->company ,0,30)),
2085 uc(substr($cust_main->address1 ,0,30)),
2086 uc(substr($cust_main->address2 ,0,30)),
2087 uc(substr($cust_main->city ,0,20)),
2088 uc($cust_main->state),
2094 } elsif ( $format eq 'ics' ) {
2096 my $bill = $cust_main->bill_location;
2097 my $zip = $bill->zip;
2101 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2106 # minor false laziness with print_generic
2107 my ($previous_balance) = $self->previous;
2108 my $balance_due = $self->owed + $previous_balance;
2109 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2110 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2113 if ( $self->due_date and $time >= $self->due_date ) {
2114 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2118 my $header = sprintf(
2119 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2120 $cust_main->display_custnum, #BID
2121 uc($cust_main->first), #FNAME
2122 uc($cust_main->last), #LNAME
2123 '00', #BATCH, should this ever be anything else?
2124 uc($cust_main->company), #COMP
2125 uc($bill->address1), #STREET1
2126 uc($bill->address2), #STREET2
2127 uc($bill->city), #CITY
2128 uc($bill->state), #STATE
2131 time2str('%Y%m%d', $self->_date), #BILL_DATE
2132 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2133 ( map {sprintf('%0.2f', $_)}
2134 $balance_due, #AMNT_DUE
2135 $previous_balance, #PREV_BAL
2136 $payment_total, #PYMT_RCVD
2137 $credit_total, #CREDITS
2138 $previous_balance, #BEG_BAL--is this correct?
2139 $self->charged, #NEW_CHRG
2142 $past_due, #PAST_MSG
2146 my %svc_class = ('' => ''); # maybe cache this more persistently?
2148 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2150 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2151 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2155 my @dates = ( $self->_date, undef );
2156 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2157 $dates[1] = $prev->sdate; #questionable
2160 # generate an 01 detail for each service
2161 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2162 foreach my $cust_svc ( @svcs ) {
2163 $show_pkgnum = ''; # hide it if we're showing svcnums
2165 my $svcpart = $cust_svc->svcpart;
2166 if (!exists($svc_class{$svcpart})) {
2167 my $classnum = $cust_svc->part_svc->classnum;
2168 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2170 $svc_class{$svcpart} = $part_svc_class ?
2171 $part_svc_class->classname :
2175 my @h_label = $cust_svc->label(@dates, 'I');
2176 push @details, sprintf('01%-9s%-20s%-47s',
2178 $svc_class{$svcpart},
2181 } #foreach $cust_svc
2184 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2185 if ($cust_bill_pkg->recur > 0) {
2186 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2187 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2189 push @details, sprintf('02%-6s%-60s%-10s',
2192 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2194 } #foreach $cust_bill_pkg
2196 # Tag this row so that we know whether this is one page (1), two pages
2197 # (2), # or "big" (B). The tag will be stripped off before uploading.
2198 if ( scalar(@details) < 12 ) {
2200 } elsif ( scalar(@details) < 58 ) {
2206 return join('', $header, @details, "\n");
2214 time2str("%x", $self->_date),
2215 sprintf("%.2f", $self->charged),
2216 ( map { $cust_main->getfield($_) }
2217 qw( first last company address1 address2 city state zip country ) ),
2219 ) or die "can't create csv";
2222 my $header = $csv->string. "\n";
2225 if ( lc($opt{'format'}) eq 'billco' ) {
2228 foreach my $item ( $self->_items_pkg ) {
2231 '', # 1 | N/A-Leave Empty CHAR 2
2232 '', # 2 | N/A-Leave Empty CHAR 15
2233 $tracctnum, # 3 | Account Number CHAR 15
2234 $self->invnum, # 4 | Invoice Number CHAR 15
2235 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2236 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2237 $item->{'amount'}, # 7 | Amount NUM* 9
2238 '', # 8 | Line Format Control** CHAR 2
2239 '', # 9 | Grouping Code CHAR 2
2240 '', # 10 | User Defined CHAR 15
2243 $detail .= $csv->string. "\n";
2247 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2253 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2255 my($pkg, $setup, $recur, $sdate, $edate);
2256 if ( $cust_bill_pkg->pkgnum ) {
2258 ($pkg, $setup, $recur, $sdate, $edate) = (
2259 $cust_bill_pkg->part_pkg->pkg,
2260 ( $cust_bill_pkg->setup != 0
2261 ? sprintf("%.2f", $cust_bill_pkg->setup )
2263 ( $cust_bill_pkg->recur != 0
2264 ? sprintf("%.2f", $cust_bill_pkg->recur )
2266 ( $cust_bill_pkg->sdate
2267 ? time2str("%x", $cust_bill_pkg->sdate)
2269 ($cust_bill_pkg->edate
2270 ? time2str("%x", $cust_bill_pkg->edate)
2274 } else { #pkgnum tax
2275 next unless $cust_bill_pkg->setup != 0;
2276 $pkg = $cust_bill_pkg->desc;
2277 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2278 ( $sdate, $edate ) = ( '', '' );
2284 ( map { '' } (1..11) ),
2285 ($pkg, $setup, $recur, $sdate, $edate)
2286 ) or die "can't create csv";
2288 $detail .= $csv->string. "\n";
2294 ( $header, $detail );
2300 Pays this invoice with a compliemntary payment. If there is an error,
2301 returns the error, otherwise returns false.
2307 my $cust_pay = new FS::cust_pay ( {
2308 'invnum' => $self->invnum,
2309 'paid' => $self->owed,
2312 'payinfo' => $self->cust_main->payinfo,
2320 Attempts to pay this invoice with a credit card payment via a
2321 Business::OnlinePayment realtime gateway. See
2322 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2323 for supported processors.
2329 $self->realtime_bop( 'CC', @_ );
2334 Attempts to pay this invoice with an electronic check (ACH) payment via a
2335 Business::OnlinePayment realtime gateway. See
2336 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2337 for supported processors.
2343 $self->realtime_bop( 'ECHECK', @_ );
2348 Attempts to pay this invoice with phone bill (LEC) payment via a
2349 Business::OnlinePayment realtime gateway. See
2350 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2351 for supported processors.
2357 $self->realtime_bop( 'LEC', @_ );
2361 my( $self, $method ) = (shift,shift);
2362 my $conf = $self->conf;
2365 my $cust_main = $self->cust_main;
2366 my $balance = $cust_main->balance;
2367 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2368 $amount = sprintf("%.2f", $amount);
2369 return "not run (balance $balance)" unless $amount > 0;
2371 my $description = 'Internet Services';
2372 if ( $conf->exists('business-onlinepayment-description') ) {
2373 my $dtempl = $conf->config('business-onlinepayment-description');
2375 my $agent_obj = $cust_main->agent
2376 or die "can't retreive agent for $cust_main (agentnum ".
2377 $cust_main->agentnum. ")";
2378 my $agent = $agent_obj->agent;
2379 my $pkgs = join(', ',
2380 map { $_->part_pkg->pkg }
2381 grep { $_->pkgnum } $self->cust_bill_pkg
2383 $description = eval qq("$dtempl");
2386 $cust_main->realtime_bop($method, $amount,
2387 'description' => $description,
2388 'invnum' => $self->invnum,
2389 #this didn't do what we want, it just calls apply_payments_and_credits
2391 'apply_to_invoice' => 1,
2394 #this changes application behavior: auto payments
2395 #triggered against a specific invoice are now applied
2396 #to that invoice instead of oldest open.
2402 =item batch_card OPTION => VALUE...
2404 Adds a payment for this invoice to the pending credit card batch (see
2405 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2406 runs the payment using a realtime gateway.
2411 my ($self, %options) = @_;
2412 my $cust_main = $self->cust_main;
2414 $options{invnum} = $self->invnum;
2416 $cust_main->batch_card(%options);
2419 sub _agent_template {
2421 $self->cust_main->agent_template;
2424 sub _agent_invoice_from {
2426 $self->cust_main->agent_invoice_from;
2429 =item invoice_barcode DIR_OR_FALSE
2431 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2432 it is taken as the temp directory where the PNG file will be generated and the
2433 PNG file name is returned. Otherwise, the PNG image itself is returned.
2437 sub invoice_barcode {
2438 my ($self, $dir) = (shift,shift);
2440 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2441 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2442 my $gd = $gdbar->plot(Height => 30);
2445 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2449 ) or die "can't open temp file: $!\n";
2450 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2451 my $png_file = $bh->filename;
2458 =item invnum_date_pretty
2460 Returns a string with the invoice number and date, for example:
2461 "Invoice #54 (3/20/2008)"
2465 sub invnum_date_pretty {
2467 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2470 #sub _items_extra_usage_sections {
2472 # my $escape = shift;
2474 # my %sections = ();
2476 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2477 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2479 # next unless $cust_bill_pkg->pkgnum > 0;
2481 # foreach my $section ( keys %usage_class ) {
2483 # my $usage = $cust_bill_pkg->usage($section);
2485 # next unless $usage && $usage > 0;
2487 # $sections{$section} ||= 0;
2488 # $sections{$section} += $usage;
2494 # map { { 'description' => &{$escape}($_),
2495 # 'subtotal' => $sections{$_},
2496 # 'summarized' => '',
2497 # 'tax_section' => '',
2500 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2504 sub _items_extra_usage_sections {
2506 my $conf = $self->conf;
2514 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2516 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2517 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2518 next unless $cust_bill_pkg->pkgnum > 0;
2520 foreach my $classnum ( keys %usage_class ) {
2521 my $section = $usage_class{$classnum}->classname;
2522 $classnums{$section} = $classnum;
2524 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2525 my $amount = $detail->amount;
2526 next unless $amount && $amount > 0;
2528 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2529 $sections{$section}{amount} += $amount; #subtotal
2530 $sections{$section}{calls}++;
2531 $sections{$section}{duration} += $detail->duration;
2533 my $desc = $detail->regionname;
2534 my $description = $desc;
2535 $description = substr($desc, 0, $maxlength). '...'
2536 if $format eq 'latex' && length($desc) > $maxlength;
2538 $lines{$section}{$desc} ||= {
2539 description => &{$escape}($description),
2540 #pkgpart => $part_pkg->pkgpart,
2541 pkgnum => $cust_bill_pkg->pkgnum,
2546 #unit_amount => $cust_bill_pkg->unitrecur,
2547 quantity => $cust_bill_pkg->quantity,
2548 product_code => 'N/A',
2549 ext_description => [],
2552 $lines{$section}{$desc}{amount} += $amount;
2553 $lines{$section}{$desc}{calls}++;
2554 $lines{$section}{$desc}{duration} += $detail->duration;
2560 my %sectionmap = ();
2561 foreach (keys %sections) {
2562 my $usage_class = $usage_class{$classnums{$_}};
2563 $sectionmap{$_} = { 'description' => &{$escape}($_),
2564 'amount' => $sections{$_}{amount}, #subtotal
2565 'calls' => $sections{$_}{calls},
2566 'duration' => $sections{$_}{duration},
2568 'tax_section' => '',
2569 'sort_weight' => $usage_class->weight,
2570 ( $usage_class->format
2571 ? ( map { $_ => $usage_class->$_($format) }
2572 qw( description_generator header_generator total_generator total_line_generator )
2579 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2583 foreach my $section ( keys %lines ) {
2584 foreach my $line ( keys %{$lines{$section}} ) {
2585 my $l = $lines{$section}{$line};
2586 $l->{section} = $sectionmap{$section};
2587 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2588 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2593 return(\@sections, \@lines);
2599 my $end = $self->_date;
2601 # start at date of previous invoice + 1 second or 0 if no previous invoice
2602 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2603 $start = 0 if !$start;
2606 my $cust_main = $self->cust_main;
2607 my @pkgs = $cust_main->all_pkgs;
2608 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2611 foreach my $pkg ( @pkgs ) {
2612 my @h_cust_svc = $pkg->h_cust_svc($end);
2613 foreach my $h_cust_svc ( @h_cust_svc ) {
2614 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2615 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2617 my $inserted = $h_cust_svc->date_inserted;
2618 my $deleted = $h_cust_svc->date_deleted;
2619 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2621 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2623 # DID either activated or ported in; cannot be both for same DID simultaneously
2624 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2625 && (!$phone_inserted->lnp_status
2626 || $phone_inserted->lnp_status eq ''
2627 || $phone_inserted->lnp_status eq 'native')) {
2630 else { # this one not so clean, should probably move to (h_)svc_phone
2631 my $phone_portedin = qsearchs( 'h_svc_phone',
2632 { 'svcnum' => $h_cust_svc->svcnum,
2633 'lnp_status' => 'portedin' },
2634 FS::h_svc_phone->sql_h_searchs($end),
2636 $num_portedin++ if $phone_portedin;
2639 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2640 if($deleted >= $start && $deleted <= $end && $phone_deleted
2641 && (!$phone_deleted->lnp_status
2642 || $phone_deleted->lnp_status ne 'portingout')) {
2645 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2646 && $phone_deleted->lnp_status
2647 && $phone_deleted->lnp_status eq 'portingout') {
2651 # increment usage minutes
2652 if ( $phone_inserted ) {
2653 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2654 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2657 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2660 # don't look at this service again
2661 push @seen, $h_cust_svc->svcnum;
2665 $minutes = sprintf("%d", $minutes);
2666 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2667 . "$num_deactivated Ported-Out: $num_portedout ",
2668 "Total Minutes: $minutes");
2671 sub _items_accountcode_cdr {
2676 my $section = { 'amount' => 0,
2679 'sort_weight' => '',
2681 'description' => 'Usage by Account Code',
2687 my %accountcodes = ();
2689 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2690 next unless $cust_bill_pkg->pkgnum > 0;
2692 my @header = $cust_bill_pkg->details_header;
2693 next unless scalar(@header);
2694 $section->{'header'} = join(',',@header);
2696 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2698 $section->{'header'} = $detail->formatted('format' => $format)
2699 if($detail->detail eq $section->{'header'});
2701 my $accountcode = $detail->accountcode;
2702 next unless $accountcode;
2704 my $amount = $detail->amount;
2705 next unless $amount && $amount > 0;
2707 $accountcodes{$accountcode} ||= {
2708 description => $accountcode,
2715 product_code => 'N/A',
2716 section => $section,
2717 ext_description => [ $section->{'header'} ],
2721 $section->{'amount'} += $amount;
2722 $accountcodes{$accountcode}{'amount'} += $amount;
2723 $accountcodes{$accountcode}{calls}++;
2724 $accountcodes{$accountcode}{duration} += $detail->duration;
2725 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2729 foreach my $l ( values %accountcodes ) {
2730 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2731 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2732 foreach my $sorted_detail ( @sorted_detail ) {
2733 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2735 delete $l->{detail_temp};
2739 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2741 return ($section,\@sorted_lines);
2744 sub _items_svc_phone_sections {
2746 my $conf = $self->conf;
2754 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2756 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2757 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2759 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2760 next unless $cust_bill_pkg->pkgnum > 0;
2762 my @header = $cust_bill_pkg->details_header;
2763 next unless scalar(@header);
2765 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2767 my $phonenum = $detail->phonenum;
2768 next unless $phonenum;
2770 my $amount = $detail->amount;
2771 next unless $amount && $amount > 0;
2773 $sections{$phonenum} ||= { 'amount' => 0,
2776 'sort_weight' => -1,
2777 'phonenum' => $phonenum,
2779 $sections{$phonenum}{amount} += $amount; #subtotal
2780 $sections{$phonenum}{calls}++;
2781 $sections{$phonenum}{duration} += $detail->duration;
2783 my $desc = $detail->regionname;
2784 my $description = $desc;
2785 $description = substr($desc, 0, $maxlength). '...'
2786 if $format eq 'latex' && length($desc) > $maxlength;
2788 $lines{$phonenum}{$desc} ||= {
2789 description => &{$escape}($description),
2790 #pkgpart => $part_pkg->pkgpart,
2798 product_code => 'N/A',
2799 ext_description => [],
2802 $lines{$phonenum}{$desc}{amount} += $amount;
2803 $lines{$phonenum}{$desc}{calls}++;
2804 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2806 my $line = $usage_class{$detail->classnum}->classname;
2807 $sections{"$phonenum $line"} ||=
2811 'sort_weight' => $usage_class{$detail->classnum}->weight,
2812 'phonenum' => $phonenum,
2813 'header' => [ @header ],
2815 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2816 $sections{"$phonenum $line"}{calls}++;
2817 $sections{"$phonenum $line"}{duration} += $detail->duration;
2819 $lines{"$phonenum $line"}{$desc} ||= {
2820 description => &{$escape}($description),
2821 #pkgpart => $part_pkg->pkgpart,
2829 product_code => 'N/A',
2830 ext_description => [],
2833 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2834 $lines{"$phonenum $line"}{$desc}{calls}++;
2835 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2836 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2837 $detail->formatted('format' => $format);
2842 my %sectionmap = ();
2843 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2844 foreach ( keys %sections ) {
2845 my @header = @{ $sections{$_}{header} || [] };
2847 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2848 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2849 my $usage_class = $summary ? $simple : $usage_simple;
2850 my $ending = $summary ? ' usage charges' : '';
2853 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2855 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2856 'amount' => $sections{$_}{amount}, #subtotal
2857 'calls' => $sections{$_}{calls},
2858 'duration' => $sections{$_}{duration},
2860 'tax_section' => '',
2861 'phonenum' => $sections{$_}{phonenum},
2862 'sort_weight' => $sections{$_}{sort_weight},
2863 'post_total' => $summary, #inspire pagebreak
2865 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2866 qw( description_generator
2869 total_line_generator
2876 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2877 $a->{sort_weight} <=> $b->{sort_weight}
2882 foreach my $section ( keys %lines ) {
2883 foreach my $line ( keys %{$lines{$section}} ) {
2884 my $l = $lines{$section}{$line};
2885 $l->{section} = $sectionmap{$section};
2886 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2887 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2892 if($conf->exists('phone_usage_class_summary')) {
2893 # this only works with Latex
2897 # after this, we'll have only two sections per DID:
2898 # Calls Summary and Calls Detail
2899 foreach my $section ( @sections ) {
2900 if($section->{'post_total'}) {
2901 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2902 $section->{'total_line_generator'} = sub { '' };
2903 $section->{'total_generator'} = sub { '' };
2904 $section->{'header_generator'} = sub { '' };
2905 $section->{'description_generator'} = '';
2906 push @newsections, $section;
2907 my %calls_detail = %$section;
2908 $calls_detail{'post_total'} = '';
2909 $calls_detail{'sort_weight'} = '';
2910 $calls_detail{'description_generator'} = sub { '' };
2911 $calls_detail{'header_generator'} = sub {
2912 return ' & Date/Time & Called Number & Duration & Price'
2913 if $format eq 'latex';
2916 $calls_detail{'description'} = 'Calls Detail: '
2917 . $section->{'phonenum'};
2918 push @newsections, \%calls_detail;
2922 # after this, each usage class is collapsed/summarized into a single
2923 # line under the Calls Summary section
2924 foreach my $newsection ( @newsections ) {
2925 if($newsection->{'post_total'}) { # this means Calls Summary
2926 foreach my $section ( @sections ) {
2927 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2928 && !$section->{'post_total'});
2929 my $newdesc = $section->{'description'};
2930 my $tn = $section->{'phonenum'};
2931 $newdesc =~ s/$tn//g;
2932 my $line = { ext_description => [],
2936 calls => $section->{'calls'},
2937 section => $newsection,
2938 duration => $section->{'duration'},
2939 description => $newdesc,
2940 amount => sprintf("%.2f",$section->{'amount'}),
2941 product_code => 'N/A',
2943 push @newlines, $line;
2948 # after this, Calls Details is populated with all CDRs
2949 foreach my $newsection ( @newsections ) {
2950 if(!$newsection->{'post_total'}) { # this means Calls Details
2951 foreach my $line ( @lines ) {
2952 next unless (scalar(@{$line->{'ext_description'}}) &&
2953 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2955 my @extdesc = @{$line->{'ext_description'}};
2957 foreach my $extdesc ( @extdesc ) {
2958 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2959 push @newextdesc, $extdesc;
2961 $line->{'ext_description'} = \@newextdesc;
2962 $line->{'section'} = $newsection;
2963 push @newlines, $line;
2968 return(\@newsections, \@newlines);
2971 return(\@sections, \@lines);
2975 =sub _items_usage_class_summary OPTIONS
2977 Returns a list of detail items summarizing the usage charges on this
2978 invoice. Each one will have 'amount', 'description' (the usage charge name),
2979 and 'usage_classnum'.
2981 OPTIONS can include 'escape' (a function to escape the descriptions).
2985 sub _items_usage_class_summary {
2989 my $escape = $opt{escape} || sub { $_[0] };
2990 my $invnum = $self->invnum;
2991 my @classes = qsearch({
2992 'table' => 'usage_class',
2993 'select' => 'classnum, classname, SUM(amount) AS amount',
2994 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2995 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2996 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2997 ' GROUP BY classnum, classname, weight'.
2998 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2999 ' ORDER BY weight ASC',
3003 description => &{$escape}($self->mt('Usage Summary')),
3007 foreach my $class (@classes) {
3009 'description' => &{$escape}($class->classname),
3010 'amount' => sprintf('%.2f', $class->amount),
3011 'usage_classnum' => $class->classnum,
3012 'section' => $section,
3018 sub _items_previous {
3020 my $conf = $self->conf;
3021 my $cust_main = $self->cust_main;
3022 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
3024 foreach ( @pr_cust_bill ) {
3025 my $date = $conf->exists('invoice_show_prior_due_date')
3026 ? 'due '. $_->due_date2str('short')
3027 : $self->time2str_local('short', $_->_date);
3029 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
3030 #'pkgpart' => 'N/A',
3032 'amount' => sprintf("%.2f", $_->owed),
3038 # 'description' => 'Previous Balance',
3039 # #'pkgpart' => 'N/A',
3040 # 'pkgnum' => 'N/A',
3041 # 'amount' => sprintf("%10.2f", $pr_total ),
3042 # 'ext_description' => [ map {
3043 # "Invoice ". $_->invnum.
3044 # " (". time2str("%x",$_->_date). ") ".
3045 # sprintf("%10.2f", $_->owed)
3046 # } @pr_cust_bill ],
3051 sub _items_credits {
3052 my( $self, %opt ) = @_;
3053 my $trim_len = $opt{'trim_len'} || 60;
3058 if ( $self->conf->exists('previous_balance-payments_since') ) {
3059 if ( $opt{'template'} eq 'statement' ) {
3060 # then the current bill is a "statement" (i.e. an invoice sent as
3061 # a payment receipt)
3062 # and in that case we want to see payments on or after THIS invoice
3063 @objects = qsearch('cust_credit', {
3064 'custnum' => $self->custnum,
3065 '_date' => {op => '>=', value => $self->_date},
3069 $date = $self->previous_bill->_date if $self->previous_bill;
3070 @objects = qsearch('cust_credit', {
3071 'custnum' => $self->custnum,
3072 '_date' => {op => '>=', value => $date},
3076 @objects = $self->cust_credited;
3079 foreach my $obj ( @objects ) {
3080 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3082 my $reason = substr($cust_credit->reason, 0, $trim_len);
3083 $reason .= '...' if length($reason) < length($cust_credit->reason);
3084 $reason = " ($reason) " if $reason;
3087 #'description' => 'Credit ref\#'. $_->crednum.
3088 # " (". time2str("%x",$_->cust_credit->_date) .")".
3090 'description' => $self->mt('Credit applied').' '.
3091 $self->time2str_local('short', $obj->_date). $reason,
3092 'amount' => sprintf("%.2f",$obj->amount),
3100 sub _items_payments {
3105 my $detailed = $self->conf->exists('invoice_payment_details');
3107 if ( $self->conf->exists('previous_balance-payments_since') ) {
3108 # then show payments dated on/after the previous bill...
3109 if ( $opt{'template'} eq 'statement' ) {
3110 # then the current bill is a "statement" (i.e. an invoice sent as
3111 # a payment receipt)
3112 # and in that case we want to see payments on or after THIS invoice
3113 @objects = qsearch('cust_pay', {
3114 'custnum' => $self->custnum,
3115 '_date' => {op => '>=', value => $self->_date},
3118 # the normal case: payments on or after the previous invoice
3120 $date = $self->previous_bill->_date if $self->previous_bill;
3121 @objects = qsearch('cust_pay', {
3122 'custnum' => $self->custnum,
3123 '_date' => {op => '>=', value => $date},
3125 # and before the current bill...
3126 @objects = grep { $_->_date < $self->_date } @objects;
3129 @objects = $self->cust_bill_pay;
3132 foreach my $obj (@objects) {
3133 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3134 my $desc = $self->mt('Payment received').' '.
3135 $self->time2str_local('short', $cust_pay->_date );
3136 $desc .= $self->mt(' via ') .
3137 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3141 'description' => $desc,
3142 'amount' => sprintf("%.2f", $obj->amount )
3150 =item call_details [ OPTION => VALUE ... ]
3152 Returns an array of CSV strings representing the call details for this invoice
3153 The only option available is the boolean prepend_billed_number
3158 my ($self, %opt) = @_;
3160 my $format_function = sub { shift };
3162 if ($opt{prepend_billed_number}) {
3163 $format_function = sub {
3167 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3172 my @details = map { $_->details( 'format_function' => $format_function,
3173 'escape_function' => sub{ return() },
3177 $self->cust_bill_pkg;
3178 my $header = $details[0];
3179 ( $header, grep { $_ ne $header } @details );
3189 =item process_reprint
3193 sub process_reprint {
3194 process_re_X('print', @_);
3197 =item process_reemail
3201 sub process_reemail {
3202 process_re_X('email', @_);
3210 process_re_X('fax', @_);
3218 process_re_X('ftp', @_);
3225 sub process_respool {
3226 process_re_X('spool', @_);
3229 use Storable qw(thaw);
3233 my( $method, $job ) = ( shift, shift );
3234 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3236 my $param = thaw(decode_base64(shift));
3237 warn Dumper($param) if $DEBUG;
3248 # spool_invoice ftp_invoice fax_invoice print_invoice
3249 my($method, $job, %param ) = @_;
3251 warn "re_X $method for job $job with param:\n".
3252 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3255 #some false laziness w/search/cust_bill.html
3257 my $orderby = 'ORDER BY cust_bill._date';
3259 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3261 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3263 my @cust_bill = qsearch( {
3264 #'select' => "cust_bill.*",
3265 'table' => 'cust_bill',
3266 'addl_from' => $addl_from,
3268 'extra_sql' => $extra_sql,
3269 'order_by' => $orderby,
3273 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3275 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3278 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3279 foreach my $cust_bill ( @cust_bill ) {
3280 $cust_bill->$method();
3282 if ( $job ) { #progressbar foo
3284 if ( time - $min_sec > $last ) {
3285 my $error = $job->update_statustext(
3286 int( 100 * $num / scalar(@cust_bill) )
3288 die $error if $error;
3299 =head1 CLASS METHODS
3305 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3310 my ($class, $start, $end) = @_;
3312 $class->paid_sql($start, $end). ' - '.
3313 $class->credited_sql($start, $end);
3318 Returns an SQL fragment to retreive the net amount (charged minus credited).
3323 my ($class, $start, $end) = @_;
3324 'charged - '. $class->credited_sql($start, $end);
3329 Returns an SQL fragment to retreive the amount paid against this invoice.
3334 my ($class, $start, $end) = @_;
3335 $start &&= "AND cust_bill_pay._date <= $start";
3336 $end &&= "AND cust_bill_pay._date > $end";
3337 $start = '' unless defined($start);
3338 $end = '' unless defined($end);
3339 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3340 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3345 Returns an SQL fragment to retreive the amount credited against this invoice.
3350 my ($class, $start, $end) = @_;
3351 $start &&= "AND cust_credit_bill._date <= $start";
3352 $end &&= "AND cust_credit_bill._date > $end";
3353 $start = '' unless defined($start);
3354 $end = '' unless defined($end);
3355 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3356 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3361 Returns an SQL fragment to retrieve the due date of an invoice.
3362 Currently only supported on PostgreSQL.
3367 my $conf = new FS::Conf;
3371 cust_bill.invoice_terms,
3372 cust_main.invoice_terms,
3373 \''.($conf->config('invoice_default_terms') || '').'\'
3374 ), E\'Net (\\\\d+)\'
3376 ) * 86400 + cust_bill._date'
3379 =item search_sql_where HASHREF
3381 Class method which returns an SQL WHERE fragment to search for parameters
3382 specified in HASHREF. Valid parameters are
3388 List reference of start date, end date, as UNIX timestamps.
3398 List reference of charged limits (exclusive).
3402 List reference of charged limits (exclusive).
3406 flag, return open invoices only
3410 flag, return net invoices only
3414 =item newest_percust
3418 Return only invoices belonging to that customer.
3422 Limit to that customer class (single value or arrayref).
3426 Limit to customers with that payment method (single value or arrayref).
3430 Limit to customers with that advertising source.
3434 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3438 sub search_sql_where {
3439 my($class, $param) = @_;
3441 warn "$me search_sql_where called with params: \n".
3442 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3448 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3449 push @search, "cust_main.agentnum = $1";
3453 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3454 push @search, "cust_main.refnum = $1";
3458 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3459 push @search, "cust_bill.custnum = $1";
3462 #customer classnum (false laziness w/ cust_main/Search.pm)
3463 if ( $param->{'cust_classnum'} ) {
3465 my @classnum = ref( $param->{'cust_classnum'} )
3466 ? @{ $param->{'cust_classnum'} }
3467 : ( $param->{'cust_classnum'} );
3469 @classnum = grep /^(\d*)$/, @classnum;
3472 push @search, '( '. join(' OR ', map {
3473 $_ ? "cust_main.classnum = $_"
3474 : "cust_main.classnum IS NULL"
3484 if ( $param->{payby} ) {
3485 my $payby = $param->{payby};
3486 $payby = [ $payby ] unless ref $payby;
3487 my $payby_in = join(',', map {dbh->quote($_)} @$payby);
3488 push @search, "cust_main.payby IN($payby_in)" if length($payby_in);
3492 if ( $param->{_date} ) {
3493 my($beginning, $ending) = @{$param->{_date}};
3495 push @search, "cust_bill._date >= $beginning",
3496 "cust_bill._date < $ending";
3500 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3501 push @search, "cust_bill.invnum >= $1";
3503 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3504 push @search, "cust_bill.invnum <= $1";
3508 if ( $param->{charged} ) {
3509 my @charged = ref($param->{charged})
3510 ? @{ $param->{charged} }
3511 : ($param->{charged});
3513 push @search, map { s/^charged/cust_bill.charged/; $_; }
3517 my $owed_sql = FS::cust_bill->owed_sql;
3520 if ( $param->{owed} ) {
3521 my @owed = ref($param->{owed})
3522 ? @{ $param->{owed} }
3524 push @search, map { s/^owed/$owed_sql/; $_; }
3529 push @search, "0 != $owed_sql"
3530 if $param->{'open'};
3531 push @search, '0 != '. FS::cust_bill->net_sql
3535 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3536 if $param->{'days'};
3539 if ( $param->{'newest_percust'} ) {
3541 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3542 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3544 my @newest_where = map { my $x = $_;
3545 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3548 grep ! /^cust_main./, @search;
3549 my $newest_where = scalar(@newest_where)
3550 ? ' AND '. join(' AND ', @newest_where)
3554 push @search, "cust_bill._date = (
3555 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3556 WHERE newest_cust_bill.custnum = cust_bill.custnum
3562 #promised_date - also has an option to accept nulls
3563 if ( $param->{promised_date} ) {
3564 my($beginning, $ending, $null) = @{$param->{promised_date}};
3566 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3567 "cust_bill.promised_date < $ending )" .
3568 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3571 #agent virtualization
3572 my $curuser = $FS::CurrentUser::CurrentUser;
3573 if ( $curuser->username eq 'fs_queue'
3574 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3576 my $newuser = qsearchs('access_user', {
3577 'username' => $username,
3581 $curuser = $newuser;
3583 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3586 push @search, $curuser->agentnums_sql;
3588 join(' AND ', @search );
3600 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3601 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base