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 );
18 use FS::cust_statement;
19 use FS::cust_bill_pkg;
20 use FS::cust_bill_pkg_display;
21 use FS::cust_bill_pkg_detail;
25 use FS::cust_credit_bill;
27 use FS::cust_bill_event;
30 use FS::cust_bill_pay;
31 use FS::part_bill_event;
34 use FS::cust_bill_batch;
35 use FS::cust_bill_pay_pkg;
36 use FS::cust_credit_bill_pkg;
37 use FS::discount_plan;
38 use FS::cust_bill_void;
42 $me = '[FS::cust_bill]';
46 FS::cust_bill - Object methods for cust_bill records
52 $record = new FS::cust_bill \%hash;
53 $record = new FS::cust_bill { 'column' => 'value' };
55 $error = $record->insert;
57 $error = $new_record->replace($old_record);
59 $error = $record->delete;
61 $error = $record->check;
63 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
65 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
67 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
69 @cust_pay_objects = $cust_bill->cust_pay;
71 $tax_amount = $record->tax;
73 @lines = $cust_bill->print_text;
74 @lines = $cust_bill->print_text('time' => $time);
78 An FS::cust_bill object represents an invoice; a declaration that a customer
79 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
80 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
81 following fields are currently supported:
87 =item invnum - primary key (assigned automatically for new invoices)
89 =item custnum - customer (see L<FS::cust_main>)
91 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
92 L<Time::Local> and L<Date::Parse> for conversion functions.
94 =item charged - amount of this invoice
96 =item invoice_terms - optional terms override for this specific invoice
104 =item billing_balance - the customer's balance immediately before generating
105 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
106 to determine the customer's balance at a specific time.
108 =item previous_balance - the customer's balance immediately after generating
109 the invoice before this one. DEPRECATED.
111 =item printed - formerly used to track the number of times an invoice had
112 been printed; no longer used.
120 =item closed - books closed flag, empty or `Y'
122 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
124 =item agent_invid - legacy invoice number
126 =item promised_date - customer promised payment date, for collection
136 Creates a new invoice. To add the invoice to the database, see L<"insert">.
137 Invoices are normally created by calling the bill method of a customer object
138 (see L<FS::cust_main>).
142 sub table { 'cust_bill'; }
144 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
145 # (except email_subject and invnum_date_pretty)
148 $self->conf->config('notice_name') || 'Invoice'
151 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
152 sub cust_unlinked_msg {
154 "WARNING: can't find cust_main.custnum ". $self->custnum.
155 ' (cust_bill.invnum '. $self->invnum. ')';
160 Adds this invoice to the database ("Posts" the invoice). If there is an error,
161 returns the error, otherwise returns false.
167 warn "$me insert called\n" if $DEBUG;
169 local $SIG{HUP} = 'IGNORE';
170 local $SIG{INT} = 'IGNORE';
171 local $SIG{QUIT} = 'IGNORE';
172 local $SIG{TERM} = 'IGNORE';
173 local $SIG{TSTP} = 'IGNORE';
174 local $SIG{PIPE} = 'IGNORE';
176 my $oldAutoCommit = $FS::UID::AutoCommit;
177 local $FS::UID::AutoCommit = 0;
180 my $error = $self->SUPER::insert;
182 $dbh->rollback if $oldAutoCommit;
186 if ( $self->get('cust_bill_pkg') ) {
187 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
188 $cust_bill_pkg->invnum($self->invnum);
189 my $error = $cust_bill_pkg->insert;
191 $dbh->rollback if $oldAutoCommit;
192 return "can't create invoice line item: $error";
197 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
204 Voids this invoice: deletes the invoice and adds a record of the voided invoice
205 to the FS::cust_bill_void table (and related tables starting from
206 FS::cust_bill_pkg_void).
212 my $reason = scalar(@_) ? shift : '';
214 local $SIG{HUP} = 'IGNORE';
215 local $SIG{INT} = 'IGNORE';
216 local $SIG{QUIT} = 'IGNORE';
217 local $SIG{TERM} = 'IGNORE';
218 local $SIG{TSTP} = 'IGNORE';
219 local $SIG{PIPE} = 'IGNORE';
221 my $oldAutoCommit = $FS::UID::AutoCommit;
222 local $FS::UID::AutoCommit = 0;
225 my $cust_bill_void = new FS::cust_bill_void ( {
226 map { $_ => $self->get($_) } $self->fields
228 $cust_bill_void->reason($reason);
229 my $error = $cust_bill_void->insert;
231 $dbh->rollback if $oldAutoCommit;
235 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
236 my $error = $cust_bill_pkg->void($reason);
238 $dbh->rollback if $oldAutoCommit;
243 $error = $self->delete;
245 $dbh->rollback if $oldAutoCommit;
249 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
257 This method now works but you probably shouldn't use it. Instead, apply a
258 credit against the invoice, or use the new void method.
260 Using this method to delete invoices outright is really, really bad. There
261 would be no record you ever posted this invoice, and there are no check to
262 make sure charged = 0 or that there are no associated cust_bill_pkg records.
264 Really, don't use it.
270 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
272 local $SIG{HUP} = 'IGNORE';
273 local $SIG{INT} = 'IGNORE';
274 local $SIG{QUIT} = 'IGNORE';
275 local $SIG{TERM} = 'IGNORE';
276 local $SIG{TSTP} = 'IGNORE';
277 local $SIG{PIPE} = 'IGNORE';
279 my $oldAutoCommit = $FS::UID::AutoCommit;
280 local $FS::UID::AutoCommit = 0;
283 foreach my $table (qw(
294 foreach my $linked ( $self->$table() ) {
295 my $error = $linked->delete;
297 $dbh->rollback if $oldAutoCommit;
304 my $error = $self->SUPER::delete(@_);
306 $dbh->rollback if $oldAutoCommit;
310 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
316 =item replace [ OLD_RECORD ]
318 You can, but probably shouldn't modify invoices...
320 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
321 supplied, replaces this record. If there is an error, returns the error,
322 otherwise returns false.
326 #replace can be inherited from Record.pm
328 # replace_check is now the preferred way to #implement replace data checks
329 # (so $object->replace() works without an argument)
332 my( $new, $old ) = ( shift, shift );
333 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
334 #return "Can't change _date!" unless $old->_date eq $new->_date;
335 return "Can't change _date" unless $old->_date == $new->_date;
336 return "Can't change charged" unless $old->charged == $new->charged
337 || $old->charged == 0
338 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
344 =item add_cc_surcharge
350 sub add_cc_surcharge {
351 my ($self, $pkgnum, $amount) = (shift, shift, shift);
354 my $cust_bill_pkg = new FS::cust_bill_pkg({
355 'invnum' => $self->invnum,
359 $error = $cust_bill_pkg->insert;
360 return $error if $error;
362 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
363 $self->charged($self->charged+$amount);
364 $error = $self->replace;
365 return $error if $error;
367 $self->apply_payments_and_credits;
373 Checks all fields to make sure this is a valid invoice. If there is an error,
374 returns the error, otherwise returns false. Called by the insert and replace
383 $self->ut_numbern('invnum')
384 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
385 || $self->ut_numbern('_date')
386 || $self->ut_money('charged')
387 || $self->ut_numbern('printed')
388 || $self->ut_enum('closed', [ '', 'Y' ])
389 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
390 || $self->ut_numbern('agent_invid') #varchar?
392 return $error if $error;
394 $self->_date(time) unless $self->_date;
396 $self->printed(0) if $self->printed eq '';
403 Returns the displayed invoice number for this invoice: agent_invid if
404 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
410 if ( $self->agent_invid
411 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
412 return $self->agent_invid;
414 return $self->invnum;
420 Returns the customer's last invoice before this one.
426 if ( !$self->get('previous_bill') ) {
427 $self->set('previous_bill', qsearchs({
428 'table' => 'cust_bill',
429 'hashref' => { 'custnum' => $self->custnum,
430 '_date' => { op=>'<', value=>$self->_date } },
431 'order_by' => 'ORDER BY _date DESC LIMIT 1',
434 $self->get('previous_bill');
439 Returns a list consisting of the total previous balance for this customer,
440 followed by the previous outstanding invoices (as FS::cust_bill objects also).
447 my @cust_bill = sort { $a->_date <=> $b->_date }
448 grep { $_->owed != 0 }
449 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
450 #'_date' => { op=>'<', value=>$self->_date },
451 'invnum' => { op=>'<', value=>$self->invnum },
454 foreach ( @cust_bill ) { $total += $_->owed; }
458 =item enable_previous
460 Whether to show the 'Previous Charges' section when printing this invoice.
461 The negation of the 'disable_previous_balance' config setting.
465 sub enable_previous {
467 my $agentnum = $self->cust_main->agentnum;
468 !$self->conf->exists('disable_previous_balance', $agentnum);
473 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
480 { 'table' => 'cust_bill_pkg',
481 'hashref' => { 'invnum' => $self->invnum },
482 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
483 # the AUTLOADED FK search. or should
484 # that default to ORDER by the pkey?
489 =item cust_bill_pkg_pkgnum PKGNUM
491 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
496 sub cust_bill_pkg_pkgnum {
497 my( $self, $pkgnum ) = @_;
499 { 'table' => 'cust_bill_pkg',
500 'hashref' => { 'invnum' => $self->invnum,
503 'order_by' => 'ORDER BY billpkgnum',
510 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
517 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
518 $self->cust_bill_pkg;
520 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
525 Returns true if any of the packages (or their definitions) corresponding to the
526 line items for this invoice have the no_auto flag set.
532 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
535 =item open_cust_bill_pkg
537 Returns the open line items for this invoice.
539 Note that cust_bill_pkg with both setup and recur fees are returned as two
540 separate line items, each with only one fee.
544 # modeled after cust_main::open_cust_bill
545 sub open_cust_bill_pkg {
548 # grep { $_->owed > 0 } $self->cust_bill_pkg
550 my %other = ( 'recur' => 'setup',
551 'setup' => 'recur', );
553 foreach my $field ( qw( recur setup )) {
554 push @open, map { $_->set( $other{$field}, 0 ); $_; }
555 grep { $_->owed($field) > 0 }
556 $self->cust_bill_pkg;
562 =item cust_bill_event
564 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
568 sub cust_bill_event {
570 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
573 =item num_cust_bill_event
575 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
579 sub num_cust_bill_event {
582 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
583 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
584 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
585 $sth->fetchrow_arrayref->[0];
590 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
594 #false laziness w/cust_pkg.pm
598 'table' => 'cust_event',
599 'addl_from' => 'JOIN part_event USING ( eventpart )',
600 'hashref' => { 'tablenum' => $self->invnum },
601 'extra_sql' => " AND eventtable = 'cust_bill' ",
607 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
611 #false laziness w/cust_pkg.pm
615 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
616 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
617 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
618 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
619 $sth->fetchrow_arrayref->[0];
624 Returns the customer (see L<FS::cust_main>) for this invoice.
626 =item cust_suspend_if_balance_over AMOUNT
628 Suspends the customer associated with this invoice if the total amount owed on
629 this invoice and all older invoices is greater than the specified amount.
631 Returns a list: an empty list on success or a list of errors.
635 sub cust_suspend_if_balance_over {
636 my( $self, $amount ) = ( shift, shift );
637 my $cust_main = $self->cust_main;
638 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
641 $cust_main->suspend(@_);
647 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
653 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
654 sort { $a->_date <=> $b->_date }
655 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
660 =item cust_credit_bill
662 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
668 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
669 sort { $a->_date <=> $b->_date }
670 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
674 sub cust_credit_bill {
675 shift->cust_credited(@_);
678 #=item cust_bill_pay_pkgnum PKGNUM
680 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
681 #with matching pkgnum.
685 #sub cust_bill_pay_pkgnum {
686 # my( $self, $pkgnum ) = @_;
687 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
688 # sort { $a->_date <=> $b->_date }
689 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
690 # 'pkgnum' => $pkgnum,
695 =item cust_bill_pay_pkg PKGNUM
697 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
698 applied against the matching pkgnum.
702 sub cust_bill_pay_pkg {
703 my( $self, $pkgnum ) = @_;
706 'select' => 'cust_bill_pay_pkg.*',
707 'table' => 'cust_bill_pay_pkg',
708 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
709 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
710 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
711 " AND cust_bill_pkg.pkgnum = $pkgnum",
716 #=item cust_credited_pkgnum PKGNUM
718 #=item cust_credit_bill_pkgnum PKGNUM
720 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
721 #with matching pkgnum.
725 #sub cust_credited_pkgnum {
726 # my( $self, $pkgnum ) = @_;
727 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
728 # sort { $a->_date <=> $b->_date }
729 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
730 # 'pkgnum' => $pkgnum,
735 #sub cust_credit_bill_pkgnum {
736 # shift->cust_credited_pkgnum(@_);
739 =item cust_credit_bill_pkg PKGNUM
741 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
742 applied against the matching pkgnum.
746 sub cust_credit_bill_pkg {
747 my( $self, $pkgnum ) = @_;
750 'select' => 'cust_credit_bill_pkg.*',
751 'table' => 'cust_credit_bill_pkg',
752 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
753 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
754 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
755 " AND cust_bill_pkg.pkgnum = $pkgnum",
760 =item cust_bill_batch
762 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
766 sub cust_bill_batch {
768 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
773 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
774 hash keyed by term length.
780 FS::discount_plan->all($self);
785 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
792 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
794 foreach (@taxlines) { $total += $_->setup; }
800 Returns the amount owed (still outstanding) on this invoice, which is charged
801 minus all payment applications (see L<FS::cust_bill_pay>) and credit
802 applications (see L<FS::cust_credit_bill>).
808 my $balance = $self->charged;
809 $balance -= $_->amount foreach ( $self->cust_bill_pay );
810 $balance -= $_->amount foreach ( $self->cust_credited );
811 $balance = sprintf( "%.2f", $balance);
812 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
817 my( $self, $pkgnum ) = @_;
819 #my $balance = $self->charged;
821 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
823 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
824 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
826 $balance = sprintf( "%.2f", $balance);
827 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
833 Returns true if this invoice should be hidden. See the
834 selfservice-hide_invoices-taxclass configuraiton setting.
840 my $conf = $self->conf;
841 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
843 my @cust_bill_pkg = $self->cust_bill_pkg;
844 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
845 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
848 =item apply_payments_and_credits [ OPTION => VALUE ... ]
850 Applies unapplied payments and credits to this invoice.
852 A hash of optional arguments may be passed. Currently "manual" is supported.
853 If true, a payment receipt is sent instead of a statement when
854 'payment_receipt_email' configuration option is set.
856 If there is an error, returns the error, otherwise returns false.
860 sub apply_payments_and_credits {
861 my( $self, %options ) = @_;
862 my $conf = $self->conf;
864 local $SIG{HUP} = 'IGNORE';
865 local $SIG{INT} = 'IGNORE';
866 local $SIG{QUIT} = 'IGNORE';
867 local $SIG{TERM} = 'IGNORE';
868 local $SIG{TSTP} = 'IGNORE';
869 local $SIG{PIPE} = 'IGNORE';
871 my $oldAutoCommit = $FS::UID::AutoCommit;
872 local $FS::UID::AutoCommit = 0;
875 $self->select_for_update; #mutex
877 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
878 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
880 if ( $conf->exists('pkg-balances') ) {
881 # limit @payments & @credits to those w/ a pkgnum grepped from $self
882 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
883 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
884 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
887 while ( $self->owed > 0 and ( @payments || @credits ) ) {
890 if ( @payments && @credits ) {
892 #decide which goes first by weight of top (unapplied) line item
894 my @open_lineitems = $self->open_cust_bill_pkg;
897 max( map { $_->part_pkg->pay_weight || 0 }
902 my $max_credit_weight =
903 max( map { $_->part_pkg->credit_weight || 0 }
909 #if both are the same... payments first? it has to be something
910 if ( $max_pay_weight >= $max_credit_weight ) {
916 } elsif ( @payments ) {
918 } elsif ( @credits ) {
921 die "guru meditation #12 and 35";
925 if ( $app eq 'pay' ) {
927 my $payment = shift @payments;
928 $unapp_amount = $payment->unapplied;
929 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
930 $app->pkgnum( $payment->pkgnum )
931 if $conf->exists('pkg-balances') && $payment->pkgnum;
933 } elsif ( $app eq 'credit' ) {
935 my $credit = shift @credits;
936 $unapp_amount = $credit->credited;
937 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
938 $app->pkgnum( $credit->pkgnum )
939 if $conf->exists('pkg-balances') && $credit->pkgnum;
942 die "guru meditation #12 and 35";
946 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
947 warn "owed_pkgnum ". $app->pkgnum;
948 $owed = $self->owed_pkgnum($app->pkgnum);
952 next unless $owed > 0;
954 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
955 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
957 $app->invnum( $self->invnum );
959 my $error = $app->insert(%options);
961 $dbh->rollback if $oldAutoCommit;
962 return "Error inserting ". $app->table. " record: $error";
964 die $error if $error;
968 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
973 =item generate_email OPTION => VALUE ...
981 sender address, required
985 alternate template name, optional
989 text attachment arrayref, optional
993 email subject, optional
997 notice name instead of "Invoice", optional
1001 Returns an argument list to be passed to L<FS::Misc::send_email>.
1007 sub generate_email {
1011 my $conf = $self->conf;
1013 my $me = '[FS::cust_bill::generate_email]';
1016 'from' => $args{'from'},
1017 'subject' => ($args{'subject'} || $self->email_subject),
1018 'custnum' => $self->custnum,
1019 'msgtype' => 'invoice',
1022 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1024 my $cust_main = $self->cust_main;
1026 if (ref($args{'to'}) eq 'ARRAY') {
1027 $return{'to'} = $args{'to'};
1029 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1030 $cust_main->invoicing_list
1034 if ( $conf->exists('invoice_html') ) {
1036 warn "$me creating HTML/text multipart message"
1039 $return{'nobody'} = 1;
1041 my $alternative = build MIME::Entity
1042 'Type' => 'multipart/alternative',
1043 #'Encoding' => '7bit',
1044 'Disposition' => 'inline'
1048 if ( $conf->exists('invoice_email_pdf')
1049 and scalar($conf->config('invoice_email_pdf_note')) ) {
1051 warn "$me using 'invoice_email_pdf_note' in multipart message"
1053 $data = [ map { $_ . "\n" }
1054 $conf->config('invoice_email_pdf_note')
1059 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1061 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1062 $data = $args{'print_text'};
1064 $data = [ $self->print_text(\%args) ];
1069 $alternative->attach(
1070 'Type' => 'text/plain',
1071 'Encoding' => 'quoted-printable',
1072 'Charset' => 'UTF-8',
1073 #'Encoding' => '7bit',
1075 'Disposition' => 'inline',
1082 if ( $conf->exists('invoice_email_pdf')
1083 and scalar($conf->config('invoice_email_pdf_note')) ) {
1085 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1089 $args{'from'} =~ /\@([\w\.\-]+)/;
1090 my $from = $1 || 'example.com';
1091 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1094 my $agentnum = $cust_main->agentnum;
1095 if ( defined($args{'template'}) && length($args{'template'})
1096 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1099 $logo = 'logo_'. $args{'template'}. '.png';
1103 my $image_data = $conf->config_binary( $logo, $agentnum);
1105 $image = build MIME::Entity
1106 'Type' => 'image/png',
1107 'Encoding' => 'base64',
1108 'Data' => $image_data,
1109 'Filename' => 'logo.png',
1110 'Content-ID' => "<$content_id>",
1113 if ($conf->exists('invoice-barcode')) {
1114 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1115 $barcode = build MIME::Entity
1116 'Type' => 'image/png',
1117 'Encoding' => 'base64',
1118 'Data' => $self->invoice_barcode(0),
1119 'Filename' => 'barcode.png',
1120 'Content-ID' => "<$barcode_content_id>",
1122 $args{'barcode_cid'} = $barcode_content_id;
1125 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1128 $alternative->attach(
1129 'Type' => 'text/html',
1130 'Encoding' => 'quoted-printable',
1131 'Data' => [ '<html>',
1134 ' '. encode_entities($return{'subject'}),
1137 ' <body bgcolor="#e8e8e8">',
1142 'Disposition' => 'inline',
1143 #'Filename' => 'invoice.pdf',
1147 my @otherparts = ();
1148 if ( $cust_main->email_csv_cdr ) {
1150 push @otherparts, build MIME::Entity
1151 'Type' => 'text/csv',
1152 'Encoding' => '7bit',
1153 'Data' => [ map { "$_\n" }
1154 $self->call_details('prepend_billed_number' => 1)
1156 'Disposition' => 'attachment',
1157 'Filename' => 'usage-'. $self->invnum. '.csv',
1162 if ( $conf->exists('invoice_email_pdf') ) {
1167 # multipart/alternative
1173 my $related = build MIME::Entity 'Type' => 'multipart/related',
1174 'Encoding' => '7bit';
1176 #false laziness w/Misc::send_email
1177 $related->head->replace('Content-type',
1178 $related->mime_type.
1179 '; boundary="'. $related->head->multipart_boundary. '"'.
1180 '; type=multipart/alternative'
1183 $related->add_part($alternative);
1185 $related->add_part($image) if $image;
1187 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1189 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1193 #no other attachment:
1195 # multipart/alternative
1200 $return{'content-type'} = 'multipart/related';
1201 if ($conf->exists('invoice-barcode') && $barcode) {
1202 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1204 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1206 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1207 #$return{'disposition'} = 'inline';
1213 if ( $conf->exists('invoice_email_pdf') ) {
1214 warn "$me creating PDF attachment"
1217 #mime parts arguments a la MIME::Entity->build().
1218 $return{'mimeparts'} = [
1219 { $self->mimebuild_pdf(\%args) }
1223 if ( $conf->exists('invoice_email_pdf')
1224 and scalar($conf->config('invoice_email_pdf_note')) ) {
1226 warn "$me using 'invoice_email_pdf_note'"
1228 $return{'body'} = [ map { $_ . "\n" }
1229 $conf->config('invoice_email_pdf_note')
1234 warn "$me not using 'invoice_email_pdf_note'"
1236 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1237 $return{'body'} = $args{'print_text'};
1239 $return{'body'} = [ $self->print_text(\%args) ];
1252 Returns a list suitable for passing to MIME::Entity->build(), representing
1253 this invoice as PDF attachment.
1260 'Type' => 'application/pdf',
1261 'Encoding' => 'base64',
1262 'Data' => [ $self->print_pdf(@_) ],
1263 'Disposition' => 'attachment',
1264 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1270 Sends this invoice to the destinations configured for this customer: sends
1271 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1273 Options can be passed as a hashref. Positional parameters are no longer
1276 I<template>: a suffix for alternate invoices
1278 I<agentnum>: obsolete, now does nothing.
1280 I<invoice_from> overrides the default email invoice From: address.
1282 I<amount>: obsolete, does nothing
1284 I<notice_name> overrides "Invoice" as the name of the sent document
1285 (templates from 10/2009 or newer required).
1287 I<lpr> overrides the system 'lpr' option as the command to print a document
1288 from standard input.
1294 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1295 my $conf = $self->conf;
1297 my $cust_main = $self->cust_main;
1299 my @invoicing_list = $cust_main->invoicing_list;
1302 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1303 && ! $self->invoice_noemail;
1306 if grep { $_ eq 'POST' } @invoicing_list; #postal
1308 #this has never been used post-$ORIGINAL_ISP afaik
1309 $self->fax_invoice($opt)
1310 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1316 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1318 Sends this invoice to the customer's email destination(s).
1320 Options must be passed as a hashref. Positional parameters are no longer
1323 I<template>, if specified, is the name of a suffix for alternate invoices.
1325 I<invoice_from>, if specified, overrides the default email invoice From:
1328 I<notice_name> is the name of the sent document.
1332 sub queueable_email {
1335 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1336 or die "invalid invoice number: " . $opt{invnum};
1338 my %args = map {$_ => $opt{$_}}
1340 qw( invoice_from notice_name no_coupon template );
1342 my $error = $self->email( \%args );
1343 die $error if $error;
1349 return if $self->hide;
1350 my $conf = $self->conf;
1351 my $opt = shift || {};
1352 if ($opt and !ref($opt)) {
1353 die "FS::cust_bill::email called with positional parameters";
1356 my $template = $opt->{template};
1357 my $from = delete $opt->{invoice_from};
1359 # this is where we set the From: address
1360 $from ||= $self->_agent_invoice_from || #XXX should go away
1361 $conf->config('invoice_from', $self->cust_main->agentnum );
1363 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1364 $self->cust_main->invoicing_list;
1366 if ( ! @invoicing_list ) { #no recipients
1367 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1368 die 'No recipients for customer #'. $self->custnum;
1370 #default: better to notify this person than silence
1371 @invoicing_list = ($from);
1375 # this is where we set the Subject:
1376 my $subject = $self->email_subject($template);
1378 my $error = send_email(
1379 $self->generate_email(
1381 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1382 'subject' => $subject,
1383 %$opt, # template, etc.
1386 die "can't email invoice: $error\n" if $error;
1387 #die "$error\n" if $error;
1393 my $conf = $self->conf;
1395 #my $template = scalar(@_) ? shift : '';
1398 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1401 my $cust_main = $self->cust_main;
1402 my $name = $cust_main->name;
1403 my $name_short = $cust_main->name_short;
1404 my $invoice_number = $self->invnum;
1405 my $invoice_date = $self->_date_pretty;
1407 eval qq("$subject");
1410 =item lpr_data HASHREF
1412 Returns the postscript or plaintext for this invoice as an arrayref.
1414 Options must be passed as a hashref. Positional parameters are no longer
1417 I<template>, if specified, is the name of a suffix for alternate invoices.
1419 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1425 my $conf = $self->conf;
1426 my $opt = shift || {};
1427 if ($opt and !ref($opt)) {
1428 # nobody does this anyway
1429 die "FS::cust_bill::lpr_data called with positional parameters";
1432 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1433 [ $self->$method( $opt ) ];
1438 Prints this invoice.
1440 Options must be passed as a hashref.
1442 I<template>, if specified, is the name of a suffix for alternate invoices.
1444 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1450 return if $self->hide;
1451 my $conf = $self->conf;
1452 my $opt = shift || {};
1453 if ($opt and !ref($opt)) {
1454 die "FS::cust_bill::print called with positional parameters";
1457 my $lpr = delete $opt->{lpr};
1458 if($conf->exists('invoice_print_pdf')) {
1459 # Add the invoice to the current batch.
1460 $self->batch_invoice($opt);
1464 $self->lpr_data($opt),
1465 'agentnum' => $self->cust_main->agentnum,
1471 =item fax_invoice HASHREF
1475 Options must be passed as a hashref.
1477 I<template>, if specified, is the name of a suffix for alternate invoices.
1479 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1485 return if $self->hide;
1486 my $conf = $self->conf;
1487 my $opt = shift || {};
1488 if ($opt and !ref($opt)) {
1489 die "FS::cust_bill::fax_invoice called with positional parameters";
1492 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1493 unless $conf->exists('invoice_latex');
1495 my $dialstring = $self->cust_main->getfield('fax');
1498 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1499 'dialstring' => $dialstring,
1501 die $error if $error;
1505 =item batch_invoice [ HASHREF ]
1507 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1508 isn't an open batch, one will be created.
1510 HASHREF may contain any options to be passed to C<print_pdf>.
1515 my ($self, $opt) = @_;
1516 my $bill_batch = $self->get_open_bill_batch;
1517 my $cust_bill_batch = FS::cust_bill_batch->new({
1518 batchnum => $bill_batch->batchnum,
1519 invnum => $self->invnum,
1521 return $cust_bill_batch->insert($opt);
1524 =item get_open_batch
1526 Returns the currently open batch as an FS::bill_batch object, creating a new
1527 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1532 sub get_open_bill_batch {
1534 my $conf = $self->conf;
1535 my $hashref = { status => 'O' };
1536 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1537 ? $self->cust_main->agentnum
1539 my $batch = qsearchs('bill_batch', $hashref);
1540 return $batch if $batch;
1541 $batch = FS::bill_batch->new($hashref);
1542 my $error = $batch->insert;
1543 die $error if $error;
1547 =item ftp_invoice [ TEMPLATENAME ]
1549 Sends this invoice data via FTP.
1551 TEMPLATENAME is unused?
1557 my $conf = $self->conf;
1558 my $template = scalar(@_) ? shift : '';
1561 'protocol' => 'ftp',
1562 'server' => $conf->config('cust_bill-ftpserver'),
1563 'username' => $conf->config('cust_bill-ftpusername'),
1564 'password' => $conf->config('cust_bill-ftppassword'),
1565 'dir' => $conf->config('cust_bill-ftpdir'),
1566 'format' => $conf->config('cust_bill-ftpformat'),
1570 =item spool_invoice [ TEMPLATENAME ]
1572 Spools this invoice data (see L<FS::spool_csv>)
1574 TEMPLATENAME is unused?
1580 my $conf = $self->conf;
1581 my $template = scalar(@_) ? shift : '';
1584 'format' => $conf->config('cust_bill-spoolformat'),
1585 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1589 =item send_csv OPTION => VALUE, ...
1591 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1595 protocol - currently only "ftp"
1601 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1602 and YYMMDDHHMMSS is a timestamp.
1604 See L</print_csv> for a description of the output format.
1609 my($self, %opt) = @_;
1613 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1614 mkdir $spooldir, 0700 unless -d $spooldir;
1616 # don't localize dates here, they're a defined format
1617 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1618 my $file = "$spooldir/$tracctnum.csv";
1620 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1622 open(CSV, ">$file") or die "can't open $file: $!";
1630 if ( $opt{protocol} eq 'ftp' ) {
1631 eval "use Net::FTP;";
1633 $net = Net::FTP->new($opt{server}) or die @$;
1635 die "unknown protocol: $opt{protocol}";
1638 $net->login( $opt{username}, $opt{password} )
1639 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1641 $net->binary or die "can't set binary mode";
1643 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1645 $net->put($file) or die "can't put $file: $!";
1655 Spools CSV invoice data.
1661 =item format - any of FS::Misc::::Invoicing::spool_formats
1663 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1664 customer has the corresponding invoice destinations set (see
1665 L<FS::cust_main_invoice>).
1667 =item agent_spools - if set to a true value, will spool to per-agent files
1668 rather than a single global file
1670 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1671 append to that spool. L<FS::Cron::upload> will then send the spool file to
1674 =item balanceover - if set, only spools the invoice if the total amount owed on
1675 this invoice and all older invoices is greater than the specified amount.
1677 =item time - the "current time". Controls the printing of past due messages
1685 my($self, %opt) = @_;
1687 my $time = $opt{'time'} || time;
1688 my $cust_main = $self->cust_main;
1690 if ( $opt{'dest'} ) {
1691 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1692 $cust_main->invoicing_list;
1693 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1694 || ! keys %invoicing_list;
1697 if ( $opt{'balanceover'} ) {
1699 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1702 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1703 mkdir $spooldir, 0700 unless -d $spooldir;
1705 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1708 if ( $opt{'agent_spools'} ) {
1709 $file = 'agentnum'.$cust_main->agentnum;
1714 if ( $opt{'upload_targetnum'} ) {
1715 $spooldir .= '/target'.$opt{'upload_targetnum'};
1716 mkdir $spooldir, 0700 unless -d $spooldir;
1717 } # otherwise it just goes into export.xxx/cust_bill
1719 if ( lc($opt{'format'}) eq 'billco' ) {
1723 $file = "$spooldir/$file.csv";
1725 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1727 open(CSV, ">>$file") or die "can't open $file: $!";
1728 flock(CSV, LOCK_EX);
1733 if ( lc($opt{'format'}) eq 'billco' ) {
1735 flock(CSV, LOCK_UN);
1738 $file =~ s/-header.csv$/-detail.csv/;
1740 open(CSV,">>$file") or die "can't open $file: $!";
1741 flock(CSV, LOCK_EX);
1745 print CSV $detail if defined($detail);
1747 flock(CSV, LOCK_UN);
1754 =item print_csv OPTION => VALUE, ...
1756 Returns CSV data for this invoice.
1760 format - 'default', 'billco', 'oneline', 'bridgestone'
1762 Returns a list consisting of two scalars. The first is a single line of CSV
1763 header information for this invoice. The second is one or more lines of CSV
1764 detail information for this invoice.
1766 If I<format> is not specified or "default", the fields of the CSV file are as
1769 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1770 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1774 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1776 B<record_type> is C<cust_bill> for the initial header line only. The
1777 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1778 fields are filled in.
1780 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1781 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1784 =item invnum - invoice number
1786 =item custnum - customer number
1788 =item _date - invoice date
1790 =item charged - total invoice amount
1792 =item first - customer first name
1794 =item last - customer first name
1796 =item company - company name
1798 =item address1 - address line 1
1800 =item address2 - address line 1
1810 =item pkg - line item description
1812 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1814 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1816 =item sdate - start date for recurring fee
1818 =item edate - end date for recurring fee
1822 If I<format> is "billco", the fields of the header CSV file are as follows:
1824 +-------------------------------------------------------------------+
1825 | FORMAT HEADER FILE |
1826 |-------------------------------------------------------------------|
1827 | Field | Description | Name | Type | Width |
1828 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1829 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1830 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1831 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1832 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1833 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1834 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1835 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1836 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1837 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1838 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1839 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1840 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1841 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1842 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1843 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1844 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1845 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1846 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1847 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1848 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1849 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1850 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1851 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1852 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1853 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1854 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1855 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1856 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1857 +-------+-------------------------------+------------+------+-------+
1859 If I<format> is "billco", the fields of the detail CSV file are as follows:
1861 FORMAT FOR DETAIL FILE
1863 Field | Description | Name | Type | Width
1864 1 | N/A-Leave Empty | RC | CHAR | 2
1865 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1866 3 | Account Number | TRACCTNUM | CHAR | 15
1867 4 | Invoice Number | TRINVOICE | CHAR | 15
1868 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1869 6 | Transaction Detail | DETAILS | CHAR | 100
1870 7 | Amount | AMT | NUM* | 9
1871 8 | Line Format Control** | LNCTRL | CHAR | 2
1872 9 | Grouping Code | GROUP | CHAR | 2
1873 10 | User Defined | ACCT CODE | CHAR | 15
1875 If format is 'oneline', there is no detail file. Each invoice has a
1876 header line only, with the fields:
1878 Agent number, agent name, customer number, first name, last name, address
1879 line 1, address line 2, city, state, zip, invoice date, invoice number,
1880 amount charged, amount due, previous balance, due date.
1882 and then, for each line item, three columns containing the package number,
1883 description, and amount.
1885 If format is 'bridgestone', there is no detail file. Each invoice has a
1886 header line with the following fields in a fixed-width format:
1888 Customer number (in display format), date, name (first last), company,
1889 address 1, address 2, city, state, zip.
1891 This is a mailing list format, and has no per-invoice fields. To avoid
1892 sending redundant notices, the spooling event should have a "once" or
1893 "once_percust_every" condition.
1898 my($self, %opt) = @_;
1900 eval "use Text::CSV_XS";
1903 my $cust_main = $self->cust_main;
1905 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1906 my $format = lc($opt{'format'});
1908 my $time = $opt{'time'} || time;
1910 my $tracctnum = ''; #leaking out from billco-specific sections :/
1911 if ( $format eq 'billco' ) {
1914 $self->conf->config('billco-account_num', $cust_main->agentnum);
1916 $tracctnum = $account_num eq 'display_custnum'
1917 ? $cust_main->display_custnum
1918 : $opt{'tracctnum'};
1921 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1923 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1925 my( $previous_balance, @unused ) = $self->previous; #previous balance
1927 my $pmt_cr_applied = 0;
1928 $pmt_cr_applied += $_->{'amount'}
1929 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1931 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1934 '', # 1 | N/A-Leave Empty CHAR 2
1935 '', # 2 | N/A-Leave Empty CHAR 15
1936 $tracctnum, # 3 | Transaction Account No CHAR 15
1937 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1938 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1939 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1940 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1941 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1942 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1943 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1944 '', # 10 | Ancillary Billing Information CHAR 30
1945 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1946 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1949 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1952 $duedate, # 14 | Bill Due Date CHAR 10
1954 $previous_balance, # 15 | Previous Balance NUM* 9
1955 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1956 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1957 $totaldue, # 18 | Total Amt Due NUM* 9
1958 $totaldue, # 19 | Total Amt Due NUM* 9
1959 '', # 20 | 30 Day Aging NUM* 9
1960 '', # 21 | 60 Day Aging NUM* 9
1961 '', # 22 | 90 Day Aging NUM* 9
1962 'N', # 23 | Y/N CHAR 1
1963 '', # 24 | Remittance automation CHAR 100
1964 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1965 $self->custnum, # 26 | Customer Reference Number CHAR 15
1966 '0', # 27 | Federal Tax*** NUM* 9
1967 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1968 '0', # 29 | Other Taxes & Fees*** NUM* 9
1971 } elsif ( $format eq 'oneline' ) { #name
1973 my ($previous_balance) = $self->previous;
1974 $previous_balance = sprintf('%.2f', $previous_balance);
1975 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1981 $self->_items_pkg, #_items_nontax? no sections or anything
1986 $cust_main->agentnum,
1987 $cust_main->agent->agent,
1991 $cust_main->company,
1992 $cust_main->address1,
1993 $cust_main->address2,
1999 time2str("%x", $self->_date),
2004 $self->due_date2str("%x"),
2009 } elsif ( $format eq 'bridgestone' ) {
2011 # bypass the CSV stuff and just return this
2012 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2013 my $zip = $cust_main->zip;
2015 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2019 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2021 $cust_main->display_custnum,
2023 uc(substr($cust_main->contact_firstlast,0,30)),
2024 uc(substr($cust_main->company ,0,30)),
2025 uc(substr($cust_main->address1 ,0,30)),
2026 uc(substr($cust_main->address2 ,0,30)),
2027 uc(substr($cust_main->city ,0,20)),
2028 uc($cust_main->state),
2034 } elsif ( $format eq 'ics' ) {
2036 my $bill = $cust_main->bill_location;
2037 my $zip = $bill->zip;
2041 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2046 # minor false laziness with print_generic
2047 my ($previous_balance) = $self->previous;
2048 my $balance_due = $self->owed + $previous_balance;
2049 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2050 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2053 if ( $self->due_date and $time >= $self->due_date ) {
2054 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2058 my $header = sprintf(
2059 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2060 $cust_main->display_custnum, #BID
2061 uc($cust_main->first), #FNAME
2062 uc($cust_main->last), #LNAME
2063 '00', #BATCH, should this ever be anything else?
2064 uc($cust_main->company), #COMP
2065 uc($bill->address1), #STREET1
2066 uc($bill->address2), #STREET2
2067 uc($bill->city), #CITY
2068 uc($bill->state), #STATE
2071 time2str('%Y%m%d', $self->_date), #BILL_DATE
2072 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2073 ( map {sprintf('%0.2f', $_)}
2074 $balance_due, #AMNT_DUE
2075 $previous_balance, #PREV_BAL
2076 $payment_total, #PYMT_RCVD
2077 $credit_total, #CREDITS
2078 $previous_balance, #BEG_BAL--is this correct?
2079 $self->charged, #NEW_CHRG
2082 $past_due, #PAST_MSG
2086 my %svc_class = ('' => ''); # maybe cache this more persistently?
2088 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2090 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2091 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2095 my @dates = ( $self->_date, undef );
2096 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2097 $dates[1] = $prev->sdate; #questionable
2100 # generate an 01 detail for each service
2101 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2102 foreach my $cust_svc ( @svcs ) {
2103 $show_pkgnum = ''; # hide it if we're showing svcnums
2105 my $svcpart = $cust_svc->svcpart;
2106 if (!exists($svc_class{$svcpart})) {
2107 my $classnum = $cust_svc->part_svc->classnum;
2108 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2110 $svc_class{$svcpart} = $part_svc_class ?
2111 $part_svc_class->classname :
2115 my @h_label = $cust_svc->label(@dates, 'I');
2116 push @details, sprintf('01%-9s%-20s%-47s',
2118 $svc_class{$svcpart},
2121 } #foreach $cust_svc
2124 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2125 if ($cust_bill_pkg->recur > 0) {
2126 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2127 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2129 push @details, sprintf('02%-6s%-60s%-10s',
2132 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2134 } #foreach $cust_bill_pkg
2136 # Tag this row so that we know whether this is one page (1), two pages
2137 # (2), # or "big" (B). The tag will be stripped off before uploading.
2138 if ( scalar(@details) < 12 ) {
2140 } elsif ( scalar(@details) < 58 ) {
2146 return join('', $header, @details, "\n");
2154 time2str("%x", $self->_date),
2155 sprintf("%.2f", $self->charged),
2156 ( map { $cust_main->getfield($_) }
2157 qw( first last company address1 address2 city state zip country ) ),
2159 ) or die "can't create csv";
2162 my $header = $csv->string. "\n";
2165 if ( lc($opt{'format'}) eq 'billco' ) {
2168 foreach my $item ( $self->_items_pkg ) {
2171 '', # 1 | N/A-Leave Empty CHAR 2
2172 '', # 2 | N/A-Leave Empty CHAR 15
2173 $tracctnum, # 3 | Account Number CHAR 15
2174 $self->invnum, # 4 | Invoice Number CHAR 15
2175 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2176 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2177 $item->{'amount'}, # 7 | Amount NUM* 9
2178 '', # 8 | Line Format Control** CHAR 2
2179 '', # 9 | Grouping Code CHAR 2
2180 '', # 10 | User Defined CHAR 15
2183 $detail .= $csv->string. "\n";
2187 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2193 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2195 my($pkg, $setup, $recur, $sdate, $edate);
2196 if ( $cust_bill_pkg->pkgnum ) {
2198 ($pkg, $setup, $recur, $sdate, $edate) = (
2199 $cust_bill_pkg->part_pkg->pkg,
2200 ( $cust_bill_pkg->setup != 0
2201 ? sprintf("%.2f", $cust_bill_pkg->setup )
2203 ( $cust_bill_pkg->recur != 0
2204 ? sprintf("%.2f", $cust_bill_pkg->recur )
2206 ( $cust_bill_pkg->sdate
2207 ? time2str("%x", $cust_bill_pkg->sdate)
2209 ($cust_bill_pkg->edate
2210 ? time2str("%x", $cust_bill_pkg->edate)
2214 } else { #pkgnum tax
2215 next unless $cust_bill_pkg->setup != 0;
2216 $pkg = $cust_bill_pkg->desc;
2217 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2218 ( $sdate, $edate ) = ( '', '' );
2224 ( map { '' } (1..11) ),
2225 ($pkg, $setup, $recur, $sdate, $edate)
2226 ) or die "can't create csv";
2228 $detail .= $csv->string. "\n";
2234 ( $header, $detail );
2240 Pays this invoice with a compliemntary payment. If there is an error,
2241 returns the error, otherwise returns false.
2247 my $cust_pay = new FS::cust_pay ( {
2248 'invnum' => $self->invnum,
2249 'paid' => $self->owed,
2252 'payinfo' => $self->cust_main->payinfo,
2260 Attempts to pay this invoice with a credit card payment via a
2261 Business::OnlinePayment realtime gateway. See
2262 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2263 for supported processors.
2269 $self->realtime_bop( 'CC', @_ );
2274 Attempts to pay this invoice with an electronic check (ACH) payment via a
2275 Business::OnlinePayment realtime gateway. See
2276 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2277 for supported processors.
2283 $self->realtime_bop( 'ECHECK', @_ );
2288 Attempts to pay this invoice with phone bill (LEC) payment via a
2289 Business::OnlinePayment realtime gateway. See
2290 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2291 for supported processors.
2297 $self->realtime_bop( 'LEC', @_ );
2301 my( $self, $method ) = (shift,shift);
2302 my $conf = $self->conf;
2305 my $cust_main = $self->cust_main;
2306 my $balance = $cust_main->balance;
2307 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2308 $amount = sprintf("%.2f", $amount);
2309 return "not run (balance $balance)" unless $amount > 0;
2311 my $description = 'Internet Services';
2312 if ( $conf->exists('business-onlinepayment-description') ) {
2313 my $dtempl = $conf->config('business-onlinepayment-description');
2315 my $agent_obj = $cust_main->agent
2316 or die "can't retreive agent for $cust_main (agentnum ".
2317 $cust_main->agentnum. ")";
2318 my $agent = $agent_obj->agent;
2319 my $pkgs = join(', ',
2320 map { $_->part_pkg->pkg }
2321 grep { $_->pkgnum } $self->cust_bill_pkg
2323 $description = eval qq("$dtempl");
2326 $cust_main->realtime_bop($method, $amount,
2327 'description' => $description,
2328 'invnum' => $self->invnum,
2329 #this didn't do what we want, it just calls apply_payments_and_credits
2331 'apply_to_invoice' => 1,
2334 #this changes application behavior: auto payments
2335 #triggered against a specific invoice are now applied
2336 #to that invoice instead of oldest open.
2342 =item batch_card OPTION => VALUE...
2344 Adds a payment for this invoice to the pending credit card batch (see
2345 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2346 runs the payment using a realtime gateway.
2351 my ($self, %options) = @_;
2352 my $cust_main = $self->cust_main;
2354 $options{invnum} = $self->invnum;
2356 $cust_main->batch_card(%options);
2359 sub _agent_template {
2361 $self->cust_main->agent_template;
2364 sub _agent_invoice_from {
2366 $self->cust_main->agent_invoice_from;
2369 =item invoice_barcode DIR_OR_FALSE
2371 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2372 it is taken as the temp directory where the PNG file will be generated and the
2373 PNG file name is returned. Otherwise, the PNG image itself is returned.
2377 sub invoice_barcode {
2378 my ($self, $dir) = (shift,shift);
2380 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2381 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2382 my $gd = $gdbar->plot(Height => 30);
2385 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2389 ) or die "can't open temp file: $!\n";
2390 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2391 my $png_file = $bh->filename;
2398 =item invnum_date_pretty
2400 Returns a string with the invoice number and date, for example:
2401 "Invoice #54 (3/20/2008)".
2403 Intended for back-end context, with regard to translation and date formatting.
2407 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2408 # for backend use (and also does the wrong thing, localizing for end customer
2409 # instead of backoffice configured date format)
2410 sub invnum_date_pretty {
2412 #$self->mt('Invoice #').
2413 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2414 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2417 #sub _items_extra_usage_sections {
2419 # my $escape = shift;
2421 # my %sections = ();
2423 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2424 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2426 # next unless $cust_bill_pkg->pkgnum > 0;
2428 # foreach my $section ( keys %usage_class ) {
2430 # my $usage = $cust_bill_pkg->usage($section);
2432 # next unless $usage && $usage > 0;
2434 # $sections{$section} ||= 0;
2435 # $sections{$section} += $usage;
2441 # map { { 'description' => &{$escape}($_),
2442 # 'subtotal' => $sections{$_},
2443 # 'summarized' => '',
2444 # 'tax_section' => '',
2447 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2451 sub _items_extra_usage_sections {
2453 my $conf = $self->conf;
2461 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2463 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2464 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2465 next unless $cust_bill_pkg->pkgnum > 0;
2467 foreach my $classnum ( keys %usage_class ) {
2468 my $section = $usage_class{$classnum}->classname;
2469 $classnums{$section} = $classnum;
2471 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2472 my $amount = $detail->amount;
2473 next unless $amount && $amount > 0;
2475 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2476 $sections{$section}{amount} += $amount; #subtotal
2477 $sections{$section}{calls}++;
2478 $sections{$section}{duration} += $detail->duration;
2480 my $desc = $detail->regionname;
2481 my $description = $desc;
2482 $description = substr($desc, 0, $maxlength). '...'
2483 if $format eq 'latex' && length($desc) > $maxlength;
2485 $lines{$section}{$desc} ||= {
2486 description => &{$escape}($description),
2487 #pkgpart => $part_pkg->pkgpart,
2488 pkgnum => $cust_bill_pkg->pkgnum,
2493 #unit_amount => $cust_bill_pkg->unitrecur,
2494 quantity => $cust_bill_pkg->quantity,
2495 product_code => 'N/A',
2496 ext_description => [],
2499 $lines{$section}{$desc}{amount} += $amount;
2500 $lines{$section}{$desc}{calls}++;
2501 $lines{$section}{$desc}{duration} += $detail->duration;
2507 my %sectionmap = ();
2508 foreach (keys %sections) {
2509 my $usage_class = $usage_class{$classnums{$_}};
2510 $sectionmap{$_} = { 'description' => &{$escape}($_),
2511 'amount' => $sections{$_}{amount}, #subtotal
2512 'calls' => $sections{$_}{calls},
2513 'duration' => $sections{$_}{duration},
2515 'tax_section' => '',
2516 'sort_weight' => $usage_class->weight,
2517 ( $usage_class->format
2518 ? ( map { $_ => $usage_class->$_($format) }
2519 qw( description_generator header_generator total_generator total_line_generator )
2526 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2530 foreach my $section ( keys %lines ) {
2531 foreach my $line ( keys %{$lines{$section}} ) {
2532 my $l = $lines{$section}{$line};
2533 $l->{section} = $sectionmap{$section};
2534 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2535 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2540 return(\@sections, \@lines);
2546 my $end = $self->_date;
2548 # start at date of previous invoice + 1 second or 0 if no previous invoice
2549 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2550 $start = 0 if !$start;
2553 my $cust_main = $self->cust_main;
2554 my @pkgs = $cust_main->all_pkgs;
2555 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2558 foreach my $pkg ( @pkgs ) {
2559 my @h_cust_svc = $pkg->h_cust_svc($end);
2560 foreach my $h_cust_svc ( @h_cust_svc ) {
2561 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2562 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2564 my $inserted = $h_cust_svc->date_inserted;
2565 my $deleted = $h_cust_svc->date_deleted;
2566 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2568 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2570 # DID either activated or ported in; cannot be both for same DID simultaneously
2571 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2572 && (!$phone_inserted->lnp_status
2573 || $phone_inserted->lnp_status eq ''
2574 || $phone_inserted->lnp_status eq 'native')) {
2577 else { # this one not so clean, should probably move to (h_)svc_phone
2578 my $phone_portedin = qsearchs( 'h_svc_phone',
2579 { 'svcnum' => $h_cust_svc->svcnum,
2580 'lnp_status' => 'portedin' },
2581 FS::h_svc_phone->sql_h_searchs($end),
2583 $num_portedin++ if $phone_portedin;
2586 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2587 if($deleted >= $start && $deleted <= $end && $phone_deleted
2588 && (!$phone_deleted->lnp_status
2589 || $phone_deleted->lnp_status ne 'portingout')) {
2592 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2593 && $phone_deleted->lnp_status
2594 && $phone_deleted->lnp_status eq 'portingout') {
2598 # increment usage minutes
2599 if ( $phone_inserted ) {
2600 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2601 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2604 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2607 # don't look at this service again
2608 push @seen, $h_cust_svc->svcnum;
2612 $minutes = sprintf("%d", $minutes);
2613 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2614 . "$num_deactivated Ported-Out: $num_portedout ",
2615 "Total Minutes: $minutes");
2618 sub _items_accountcode_cdr {
2623 my $section = { 'amount' => 0,
2626 'sort_weight' => '',
2628 'description' => 'Usage by Account Code',
2634 my %accountcodes = ();
2636 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2637 next unless $cust_bill_pkg->pkgnum > 0;
2639 my @header = $cust_bill_pkg->details_header;
2640 next unless scalar(@header);
2641 $section->{'header'} = join(',',@header);
2643 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2645 $section->{'header'} = $detail->formatted('format' => $format)
2646 if($detail->detail eq $section->{'header'});
2648 my $accountcode = $detail->accountcode;
2649 next unless $accountcode;
2651 my $amount = $detail->amount;
2652 next unless $amount && $amount > 0;
2654 $accountcodes{$accountcode} ||= {
2655 description => $accountcode,
2662 product_code => 'N/A',
2663 section => $section,
2664 ext_description => [ $section->{'header'} ],
2668 $section->{'amount'} += $amount;
2669 $accountcodes{$accountcode}{'amount'} += $amount;
2670 $accountcodes{$accountcode}{calls}++;
2671 $accountcodes{$accountcode}{duration} += $detail->duration;
2672 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2676 foreach my $l ( values %accountcodes ) {
2677 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2678 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2679 foreach my $sorted_detail ( @sorted_detail ) {
2680 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2682 delete $l->{detail_temp};
2686 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2688 return ($section,\@sorted_lines);
2691 sub _items_svc_phone_sections {
2693 my $conf = $self->conf;
2701 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2703 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2704 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2706 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2707 next unless $cust_bill_pkg->pkgnum > 0;
2709 my @header = $cust_bill_pkg->details_header;
2710 next unless scalar(@header);
2712 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2714 my $phonenum = $detail->phonenum;
2715 next unless $phonenum;
2717 my $amount = $detail->amount;
2718 next unless $amount && $amount > 0;
2720 $sections{$phonenum} ||= { 'amount' => 0,
2723 'sort_weight' => -1,
2724 'phonenum' => $phonenum,
2726 $sections{$phonenum}{amount} += $amount; #subtotal
2727 $sections{$phonenum}{calls}++;
2728 $sections{$phonenum}{duration} += $detail->duration;
2730 my $desc = $detail->regionname;
2731 my $description = $desc;
2732 $description = substr($desc, 0, $maxlength). '...'
2733 if $format eq 'latex' && length($desc) > $maxlength;
2735 $lines{$phonenum}{$desc} ||= {
2736 description => &{$escape}($description),
2737 #pkgpart => $part_pkg->pkgpart,
2745 product_code => 'N/A',
2746 ext_description => [],
2749 $lines{$phonenum}{$desc}{amount} += $amount;
2750 $lines{$phonenum}{$desc}{calls}++;
2751 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2753 my $line = $usage_class{$detail->classnum}->classname;
2754 $sections{"$phonenum $line"} ||=
2758 'sort_weight' => $usage_class{$detail->classnum}->weight,
2759 'phonenum' => $phonenum,
2760 'header' => [ @header ],
2762 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2763 $sections{"$phonenum $line"}{calls}++;
2764 $sections{"$phonenum $line"}{duration} += $detail->duration;
2766 $lines{"$phonenum $line"}{$desc} ||= {
2767 description => &{$escape}($description),
2768 #pkgpart => $part_pkg->pkgpart,
2776 product_code => 'N/A',
2777 ext_description => [],
2780 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2781 $lines{"$phonenum $line"}{$desc}{calls}++;
2782 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2783 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2784 $detail->formatted('format' => $format);
2789 my %sectionmap = ();
2790 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2791 foreach ( keys %sections ) {
2792 my @header = @{ $sections{$_}{header} || [] };
2794 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2795 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2796 my $usage_class = $summary ? $simple : $usage_simple;
2797 my $ending = $summary ? ' usage charges' : '';
2800 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2802 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2803 'amount' => $sections{$_}{amount}, #subtotal
2804 'calls' => $sections{$_}{calls},
2805 'duration' => $sections{$_}{duration},
2807 'tax_section' => '',
2808 'phonenum' => $sections{$_}{phonenum},
2809 'sort_weight' => $sections{$_}{sort_weight},
2810 'post_total' => $summary, #inspire pagebreak
2812 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2813 qw( description_generator
2816 total_line_generator
2823 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2824 $a->{sort_weight} <=> $b->{sort_weight}
2829 foreach my $section ( keys %lines ) {
2830 foreach my $line ( keys %{$lines{$section}} ) {
2831 my $l = $lines{$section}{$line};
2832 $l->{section} = $sectionmap{$section};
2833 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2834 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2839 if($conf->exists('phone_usage_class_summary')) {
2840 # this only works with Latex
2844 # after this, we'll have only two sections per DID:
2845 # Calls Summary and Calls Detail
2846 foreach my $section ( @sections ) {
2847 if($section->{'post_total'}) {
2848 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2849 $section->{'total_line_generator'} = sub { '' };
2850 $section->{'total_generator'} = sub { '' };
2851 $section->{'header_generator'} = sub { '' };
2852 $section->{'description_generator'} = '';
2853 push @newsections, $section;
2854 my %calls_detail = %$section;
2855 $calls_detail{'post_total'} = '';
2856 $calls_detail{'sort_weight'} = '';
2857 $calls_detail{'description_generator'} = sub { '' };
2858 $calls_detail{'header_generator'} = sub {
2859 return ' & Date/Time & Called Number & Duration & Price'
2860 if $format eq 'latex';
2863 $calls_detail{'description'} = 'Calls Detail: '
2864 . $section->{'phonenum'};
2865 push @newsections, \%calls_detail;
2869 # after this, each usage class is collapsed/summarized into a single
2870 # line under the Calls Summary section
2871 foreach my $newsection ( @newsections ) {
2872 if($newsection->{'post_total'}) { # this means Calls Summary
2873 foreach my $section ( @sections ) {
2874 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2875 && !$section->{'post_total'});
2876 my $newdesc = $section->{'description'};
2877 my $tn = $section->{'phonenum'};
2878 $newdesc =~ s/$tn//g;
2879 my $line = { ext_description => [],
2883 calls => $section->{'calls'},
2884 section => $newsection,
2885 duration => $section->{'duration'},
2886 description => $newdesc,
2887 amount => sprintf("%.2f",$section->{'amount'}),
2888 product_code => 'N/A',
2890 push @newlines, $line;
2895 # after this, Calls Details is populated with all CDRs
2896 foreach my $newsection ( @newsections ) {
2897 if(!$newsection->{'post_total'}) { # this means Calls Details
2898 foreach my $line ( @lines ) {
2899 next unless (scalar(@{$line->{'ext_description'}}) &&
2900 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2902 my @extdesc = @{$line->{'ext_description'}};
2904 foreach my $extdesc ( @extdesc ) {
2905 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2906 push @newextdesc, $extdesc;
2908 $line->{'ext_description'} = \@newextdesc;
2909 $line->{'section'} = $newsection;
2910 push @newlines, $line;
2915 return(\@newsections, \@newlines);
2918 return(\@sections, \@lines);
2922 =sub _items_usage_class_summary OPTIONS
2924 Returns a list of detail items summarizing the usage charges on this
2925 invoice. Each one will have 'amount', 'description' (the usage charge name),
2926 and 'usage_classnum'.
2928 OPTIONS can include 'escape' (a function to escape the descriptions).
2932 sub _items_usage_class_summary {
2936 my $escape = $opt{escape} || sub { $_[0] };
2937 my $invnum = $self->invnum;
2938 my @classes = qsearch({
2939 'table' => 'usage_class',
2940 'select' => 'classnum, classname, SUM(amount) AS amount',
2941 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2942 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2943 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2944 ' GROUP BY classnum, classname, weight'.
2945 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2946 ' ORDER BY weight ASC',
2950 description => &{$escape}($self->mt('Usage Summary')),
2954 foreach my $class (@classes) {
2956 'description' => &{$escape}($class->classname),
2957 'amount' => sprintf('%.2f', $class->amount),
2958 'usage_classnum' => $class->classnum,
2959 'section' => $section,
2965 sub _items_previous {
2967 my $conf = $self->conf;
2968 my $cust_main = $self->cust_main;
2969 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2971 foreach ( @pr_cust_bill ) {
2972 my $date = $conf->exists('invoice_show_prior_due_date')
2973 ? 'due '. $_->due_date2str('short')
2974 : $self->time2str_local('short', $_->_date);
2976 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2977 #'pkgpart' => 'N/A',
2979 'amount' => sprintf("%.2f", $_->owed),
2985 # 'description' => 'Previous Balance',
2986 # #'pkgpart' => 'N/A',
2987 # 'pkgnum' => 'N/A',
2988 # 'amount' => sprintf("%10.2f", $pr_total ),
2989 # 'ext_description' => [ map {
2990 # "Invoice ". $_->invnum.
2991 # " (". time2str("%x",$_->_date). ") ".
2992 # sprintf("%10.2f", $_->owed)
2993 # } @pr_cust_bill ],
2998 sub _items_credits {
2999 my( $self, %opt ) = @_;
3000 my $trim_len = $opt{'trim_len'} || 60;
3005 if ( $self->conf->exists('previous_balance-payments_since') ) {
3006 if ( $opt{'template'} eq 'statement' ) {
3007 # then the current bill is a "statement" (i.e. an invoice sent as
3008 # a payment receipt)
3009 # and in that case we want to see payments on or after THIS invoice
3010 @objects = qsearch('cust_credit', {
3011 'custnum' => $self->custnum,
3012 '_date' => {op => '>=', value => $self->_date},
3016 $date = $self->previous_bill->_date if $self->previous_bill;
3017 @objects = qsearch('cust_credit', {
3018 'custnum' => $self->custnum,
3019 '_date' => {op => '>=', value => $date},
3023 @objects = $self->cust_credited;
3026 foreach my $obj ( @objects ) {
3027 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3029 my $reason = substr($cust_credit->reason, 0, $trim_len);
3030 $reason .= '...' if length($reason) < length($cust_credit->reason);
3031 $reason = " ($reason) " if $reason;
3034 #'description' => 'Credit ref\#'. $_->crednum.
3035 # " (". time2str("%x",$_->cust_credit->_date) .")".
3037 'description' => $self->mt('Credit applied').' '.
3038 $self->time2str_local('short', $obj->_date). $reason,
3039 'amount' => sprintf("%.2f",$obj->amount),
3047 sub _items_payments {
3052 my $detailed = $self->conf->exists('invoice_payment_details');
3054 if ( $self->conf->exists('previous_balance-payments_since') ) {
3055 # then show payments dated on/after the previous bill...
3056 if ( $opt{'template'} eq 'statement' ) {
3057 # then the current bill is a "statement" (i.e. an invoice sent as
3058 # a payment receipt)
3059 # and in that case we want to see payments on or after THIS invoice
3060 @objects = qsearch('cust_pay', {
3061 'custnum' => $self->custnum,
3062 '_date' => {op => '>=', value => $self->_date},
3065 # the normal case: payments on or after the previous invoice
3067 $date = $self->previous_bill->_date if $self->previous_bill;
3068 @objects = qsearch('cust_pay', {
3069 'custnum' => $self->custnum,
3070 '_date' => {op => '>=', value => $date},
3072 # and before the current bill...
3073 @objects = grep { $_->_date < $self->_date } @objects;
3076 @objects = $self->cust_bill_pay;
3079 foreach my $obj (@objects) {
3080 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3081 my $desc = $self->mt('Payment received').' '.
3082 $self->time2str_local('short', $cust_pay->_date );
3083 $desc .= $self->mt(' via ') .
3084 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3088 'description' => $desc,
3089 'amount' => sprintf("%.2f", $obj->amount )
3097 =item call_details [ OPTION => VALUE ... ]
3099 Returns an array of CSV strings representing the call details for this invoice
3100 The only option available is the boolean prepend_billed_number
3105 my ($self, %opt) = @_;
3107 my $format_function = sub { shift };
3109 if ($opt{prepend_billed_number}) {
3110 $format_function = sub {
3114 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3119 my @details = map { $_->details( 'format_function' => $format_function,
3120 'escape_function' => sub{ return() },
3124 $self->cust_bill_pkg;
3125 my $header = $details[0];
3126 ( $header, grep { $_ ne $header } @details );
3136 =item process_reprint
3140 sub process_reprint {
3141 process_re_X('print', @_);
3144 =item process_reemail
3148 sub process_reemail {
3149 process_re_X('email', @_);
3157 process_re_X('fax', @_);
3165 process_re_X('ftp', @_);
3172 sub process_respool {
3173 process_re_X('spool', @_);
3176 use Storable qw(thaw);
3180 my( $method, $job ) = ( shift, shift );
3181 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3183 my $param = thaw(decode_base64(shift));
3184 warn Dumper($param) if $DEBUG;
3195 # spool_invoice ftp_invoice fax_invoice print_invoice
3196 my($method, $job, %param ) = @_;
3198 warn "re_X $method for job $job with param:\n".
3199 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3202 #some false laziness w/search/cust_bill.html
3204 my $orderby = 'ORDER BY cust_bill._date';
3206 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3208 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3210 my @cust_bill = qsearch( {
3211 #'select' => "cust_bill.*",
3212 'table' => 'cust_bill',
3213 'addl_from' => $addl_from,
3215 'extra_sql' => $extra_sql,
3216 'order_by' => $orderby,
3220 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3222 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3225 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3226 foreach my $cust_bill ( @cust_bill ) {
3227 $cust_bill->$method();
3229 if ( $job ) { #progressbar foo
3231 if ( time - $min_sec > $last ) {
3232 my $error = $job->update_statustext(
3233 int( 100 * $num / scalar(@cust_bill) )
3235 die $error if $error;
3246 +{ ( map { $_=>$self->$_ } $self->fields ),
3247 'owed' => $self->owed,
3248 #XXX last payment applied date
3254 =head1 CLASS METHODS
3260 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3265 my ($class, $start, $end) = @_;
3267 $class->paid_sql($start, $end). ' - '.
3268 $class->credited_sql($start, $end);
3273 Returns an SQL fragment to retreive the net amount (charged minus credited).
3278 my ($class, $start, $end) = @_;
3279 'charged - '. $class->credited_sql($start, $end);
3284 Returns an SQL fragment to retreive the amount paid against this invoice.
3289 my ($class, $start, $end) = @_;
3290 $start &&= "AND cust_bill_pay._date <= $start";
3291 $end &&= "AND cust_bill_pay._date > $end";
3292 $start = '' unless defined($start);
3293 $end = '' unless defined($end);
3294 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3295 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3300 Returns an SQL fragment to retreive the amount credited against this invoice.
3305 my ($class, $start, $end) = @_;
3306 $start &&= "AND cust_credit_bill._date <= $start";
3307 $end &&= "AND cust_credit_bill._date > $end";
3308 $start = '' unless defined($start);
3309 $end = '' unless defined($end);
3310 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3311 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3316 Returns an SQL fragment to retrieve the due date of an invoice.
3317 Currently only supported on PostgreSQL.
3322 my $conf = new FS::Conf;
3326 cust_bill.invoice_terms,
3327 cust_main.invoice_terms,
3328 \''.($conf->config('invoice_default_terms') || '').'\'
3329 ), E\'Net (\\\\d+)\'
3331 ) * 86400 + cust_bill._date'
3334 =item search_sql_where HASHREF
3336 Class method which returns an SQL WHERE fragment to search for parameters
3337 specified in HASHREF. Valid parameters are
3343 List reference of start date, end date, as UNIX timestamps.
3353 List reference of charged limits (exclusive).
3357 List reference of charged limits (exclusive).
3361 flag, return open invoices only
3365 flag, return net invoices only
3369 =item newest_percust
3373 Return only invoices belonging to that customer.
3377 Limit to that customer class (single value or arrayref).
3381 Limit to customers with that payment method (single value or arrayref).
3385 Limit to customers with that advertising source.
3389 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3393 sub search_sql_where {
3394 my($class, $param) = @_;
3396 warn "$me search_sql_where called with params: \n".
3397 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3403 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3404 push @search, "cust_main.agentnum = $1";
3408 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3409 push @search, "cust_main.refnum = $1";
3413 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3414 push @search, "cust_bill.custnum = $1";
3417 #customer classnum (false laziness w/ cust_main/Search.pm)
3418 if ( $param->{'cust_classnum'} ) {
3420 my @classnum = ref( $param->{'cust_classnum'} )
3421 ? @{ $param->{'cust_classnum'} }
3422 : ( $param->{'cust_classnum'} );
3424 @classnum = grep /^(\d*)$/, @classnum;
3427 push @search, '( '. join(' OR ', map {
3428 $_ ? "cust_main.classnum = $_"
3429 : "cust_main.classnum IS NULL"
3439 if ( $param->{payby} ) {
3440 my $payby = $param->{payby};
3441 $payby = [ $payby ] unless ref $payby;
3442 my $payby_in = join(',', map {dbh->quote($_)} @$payby);
3443 push @search, "cust_main.payby IN($payby_in)" if length($payby_in);
3447 if ( $param->{_date} ) {
3448 my($beginning, $ending) = @{$param->{_date}};
3450 push @search, "cust_bill._date >= $beginning",
3451 "cust_bill._date < $ending";
3455 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3456 push @search, "cust_bill.invnum >= $1";
3458 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3459 push @search, "cust_bill.invnum <= $1";
3463 if ( $param->{charged} ) {
3464 my @charged = ref($param->{charged})
3465 ? @{ $param->{charged} }
3466 : ($param->{charged});
3468 push @search, map { s/^charged/cust_bill.charged/; $_; }
3472 my $owed_sql = FS::cust_bill->owed_sql;
3475 if ( $param->{owed} ) {
3476 my @owed = ref($param->{owed})
3477 ? @{ $param->{owed} }
3479 push @search, map { s/^owed/$owed_sql/; $_; }
3484 push @search, "0 != $owed_sql"
3485 if $param->{'open'};
3486 push @search, '0 != '. FS::cust_bill->net_sql
3490 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3491 if $param->{'days'};
3494 if ( $param->{'newest_percust'} ) {
3496 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3497 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3499 my @newest_where = map { my $x = $_;
3500 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3503 grep ! /^cust_main./, @search;
3504 my $newest_where = scalar(@newest_where)
3505 ? ' AND '. join(' AND ', @newest_where)
3509 push @search, "cust_bill._date = (
3510 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3511 WHERE newest_cust_bill.custnum = cust_bill.custnum
3517 #promised_date - also has an option to accept nulls
3518 if ( $param->{promised_date} ) {
3519 my($beginning, $ending, $null) = @{$param->{promised_date}};
3521 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3522 "cust_bill.promised_date < $ending )" .
3523 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3526 #agent virtualization
3527 my $curuser = $FS::CurrentUser::CurrentUser;
3528 if ( $curuser->username eq 'fs_queue'
3529 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3531 my $newuser = qsearchs('access_user', {
3532 'username' => $username,
3536 $curuser = $newuser;
3538 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3541 push @search, $curuser->agentnums_sql;
3543 join(' AND ', @search );
3555 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3556 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base