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]';
44 #ask FS::UID to run this stuff for us later
45 FS::UID->install_callback( sub {
46 my $conf = new FS::Conf; #global
51 FS::cust_bill - Object methods for cust_bill records
57 $record = new FS::cust_bill \%hash;
58 $record = new FS::cust_bill { 'column' => 'value' };
60 $error = $record->insert;
62 $error = $new_record->replace($old_record);
64 $error = $record->delete;
66 $error = $record->check;
68 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
70 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
72 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
74 @cust_pay_objects = $cust_bill->cust_pay;
76 $tax_amount = $record->tax;
78 @lines = $cust_bill->print_text;
79 @lines = $cust_bill->print_text('time' => $time);
83 An FS::cust_bill object represents an invoice; a declaration that a customer
84 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
85 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
86 following fields are currently supported:
92 =item invnum - primary key (assigned automatically for new invoices)
94 =item custnum - customer (see L<FS::cust_main>)
96 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
97 L<Time::Local> and L<Date::Parse> for conversion functions.
99 =item charged - amount of this invoice
101 =item invoice_terms - optional terms override for this specific invoice
105 Customer info at invoice generation time
109 =item billing_balance - the customer's balance at the time the invoice was
110 generated (not including charges on this invoice)
112 =item previous_balance - the billing_balance of this customer's previous
113 invoice plus the charges on that invoice
121 =item printed - deprecated
129 =item closed - books closed flag, empty or `Y'
131 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
133 =item agent_invid - legacy invoice number
135 =item promised_date - customer promised payment date, for collection
145 Creates a new invoice. To add the invoice to the database, see L<"insert">.
146 Invoices are normally created by calling the bill method of a customer object
147 (see L<FS::cust_main>).
151 sub table { 'cust_bill'; }
153 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
154 # (except email_subject and invnum_date_pretty)
157 $self->conf->config('notice_name') || 'Invoice'
160 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
161 sub cust_unlinked_msg {
163 "WARNING: can't find cust_main.custnum ". $self->custnum.
164 ' (cust_bill.invnum '. $self->invnum. ')';
169 Adds this invoice to the database ("Posts" the invoice). If there is an error,
170 returns the error, otherwise returns false.
176 warn "$me insert called\n" if $DEBUG;
178 local $SIG{HUP} = 'IGNORE';
179 local $SIG{INT} = 'IGNORE';
180 local $SIG{QUIT} = 'IGNORE';
181 local $SIG{TERM} = 'IGNORE';
182 local $SIG{TSTP} = 'IGNORE';
183 local $SIG{PIPE} = 'IGNORE';
185 my $oldAutoCommit = $FS::UID::AutoCommit;
186 local $FS::UID::AutoCommit = 0;
189 my $error = $self->SUPER::insert;
191 $dbh->rollback if $oldAutoCommit;
195 if ( $self->get('cust_bill_pkg') ) {
196 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
197 $cust_bill_pkg->invnum($self->invnum);
198 my $error = $cust_bill_pkg->insert;
200 $dbh->rollback if $oldAutoCommit;
201 return "can't create invoice line item: $error";
206 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
213 Voids this invoice: deletes the invoice and adds a record of the voided invoice
214 to the FS::cust_bill_void table (and related tables starting from
215 FS::cust_bill_pkg_void).
221 my $reason = scalar(@_) ? shift : '';
223 local $SIG{HUP} = 'IGNORE';
224 local $SIG{INT} = 'IGNORE';
225 local $SIG{QUIT} = 'IGNORE';
226 local $SIG{TERM} = 'IGNORE';
227 local $SIG{TSTP} = 'IGNORE';
228 local $SIG{PIPE} = 'IGNORE';
230 my $oldAutoCommit = $FS::UID::AutoCommit;
231 local $FS::UID::AutoCommit = 0;
234 my $cust_bill_void = new FS::cust_bill_void ( {
235 map { $_ => $self->get($_) } $self->fields
237 $cust_bill_void->reason($reason);
238 my $error = $cust_bill_void->insert;
240 $dbh->rollback if $oldAutoCommit;
244 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
245 my $error = $cust_bill_pkg->void($reason);
247 $dbh->rollback if $oldAutoCommit;
252 $error = $self->delete;
254 $dbh->rollback if $oldAutoCommit;
258 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
266 This method now works but you probably shouldn't use it. Instead, apply a
267 credit against the invoice, or use the new void method.
269 Using this method to delete invoices outright is really, really bad. There
270 would be no record you ever posted this invoice, and there are no check to
271 make sure charged = 0 or that there are no associated cust_bill_pkg records.
273 Really, don't use it.
279 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
281 local $SIG{HUP} = 'IGNORE';
282 local $SIG{INT} = 'IGNORE';
283 local $SIG{QUIT} = 'IGNORE';
284 local $SIG{TERM} = 'IGNORE';
285 local $SIG{TSTP} = 'IGNORE';
286 local $SIG{PIPE} = 'IGNORE';
288 my $oldAutoCommit = $FS::UID::AutoCommit;
289 local $FS::UID::AutoCommit = 0;
292 foreach my $table (qw(
303 foreach my $linked ( $self->$table() ) {
304 my $error = $linked->delete;
306 $dbh->rollback if $oldAutoCommit;
313 my $error = $self->SUPER::delete(@_);
315 $dbh->rollback if $oldAutoCommit;
319 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
325 =item replace [ OLD_RECORD ]
327 You can, but probably shouldn't modify invoices...
329 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
330 supplied, replaces this record. If there is an error, returns the error,
331 otherwise returns false.
335 #replace can be inherited from Record.pm
337 # replace_check is now the preferred way to #implement replace data checks
338 # (so $object->replace() works without an argument)
341 my( $new, $old ) = ( shift, shift );
342 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
343 #return "Can't change _date!" unless $old->_date eq $new->_date;
344 return "Can't change _date" unless $old->_date == $new->_date;
345 return "Can't change charged" unless $old->charged == $new->charged
346 || $old->charged == 0
347 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
353 =item add_cc_surcharge
359 sub add_cc_surcharge {
360 my ($self, $pkgnum, $amount) = (shift, shift, shift);
363 my $cust_bill_pkg = new FS::cust_bill_pkg({
364 'invnum' => $self->invnum,
368 $error = $cust_bill_pkg->insert;
369 return $error if $error;
371 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
372 $self->charged($self->charged+$amount);
373 $error = $self->replace;
374 return $error if $error;
376 $self->apply_payments_and_credits;
382 Checks all fields to make sure this is a valid invoice. If there is an error,
383 returns the error, otherwise returns false. Called by the insert and replace
392 $self->ut_numbern('invnum')
393 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
394 || $self->ut_numbern('_date')
395 || $self->ut_money('charged')
396 || $self->ut_numbern('printed')
397 || $self->ut_enum('closed', [ '', 'Y' ])
398 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
399 || $self->ut_numbern('agent_invid') #varchar?
401 return $error if $error;
403 $self->_date(time) unless $self->_date;
405 $self->printed(0) if $self->printed eq '';
412 Returns the displayed invoice number for this invoice: agent_invid if
413 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
419 my $conf = $self->conf;
420 if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
421 return $self->agent_invid;
423 return $self->invnum;
429 Returns the customer's last invoice before this one.
435 if ( !$self->get('previous_bill') ) {
436 $self->set('previous_bill', qsearchs({
437 'table' => 'cust_bill',
438 'hashref' => { 'custnum' => $self->custnum,
439 '_date' => { op=>'<', value=>$self->_date } },
440 'order_by' => 'ORDER BY _date DESC LIMIT 1',
443 $self->get('previous_bill');
448 Returns a list consisting of the total previous balance for this customer,
449 followed by the previous outstanding invoices (as FS::cust_bill objects also).
456 my @cust_bill = sort { $a->_date <=> $b->_date }
457 grep { $_->owed != 0 }
458 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
459 #'_date' => { op=>'<', value=>$self->_date },
460 'invnum' => { op=>'<', value=>$self->invnum },
463 foreach ( @cust_bill ) { $total += $_->owed; }
467 =item enable_previous
469 Whether to show the 'Previous Charges' section when printing this invoice.
470 The negation of the 'disable_previous_balance' config setting.
474 sub enable_previous {
476 my $agentnum = $self->cust_main->agentnum;
477 !$self->conf->exists('disable_previous_balance', $agentnum);
482 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
489 { 'table' => 'cust_bill_pkg',
490 'hashref' => { 'invnum' => $self->invnum },
491 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
492 # the AUTLOADED FK search. or should
493 # that default to ORDER by the pkey?
498 =item cust_bill_pkg_pkgnum PKGNUM
500 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
505 sub cust_bill_pkg_pkgnum {
506 my( $self, $pkgnum ) = @_;
508 { 'table' => 'cust_bill_pkg',
509 'hashref' => { 'invnum' => $self->invnum,
512 'order_by' => 'ORDER BY billpkgnum',
519 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
526 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
527 $self->cust_bill_pkg;
529 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
534 Returns true if any of the packages (or their definitions) corresponding to the
535 line items for this invoice have the no_auto flag set.
541 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
544 =item open_cust_bill_pkg
546 Returns the open line items for this invoice.
548 Note that cust_bill_pkg with both setup and recur fees are returned as two
549 separate line items, each with only one fee.
553 # modeled after cust_main::open_cust_bill
554 sub open_cust_bill_pkg {
557 # grep { $_->owed > 0 } $self->cust_bill_pkg
559 my %other = ( 'recur' => 'setup',
560 'setup' => 'recur', );
562 foreach my $field ( qw( recur setup )) {
563 push @open, map { $_->set( $other{$field}, 0 ); $_; }
564 grep { $_->owed($field) > 0 }
565 $self->cust_bill_pkg;
571 =item cust_bill_event
573 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
577 sub cust_bill_event {
579 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
582 =item num_cust_bill_event
584 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
588 sub num_cust_bill_event {
591 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
592 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
593 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
594 $sth->fetchrow_arrayref->[0];
599 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
603 #false laziness w/cust_pkg.pm
607 'table' => 'cust_event',
608 'addl_from' => 'JOIN part_event USING ( eventpart )',
609 'hashref' => { 'tablenum' => $self->invnum },
610 'extra_sql' => " AND eventtable = 'cust_bill' ",
616 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
620 #false laziness w/cust_pkg.pm
624 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
625 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
626 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
627 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
628 $sth->fetchrow_arrayref->[0];
633 Returns the customer (see L<FS::cust_main>) for this invoice.
635 =item cust_suspend_if_balance_over AMOUNT
637 Suspends the customer associated with this invoice if the total amount owed on
638 this invoice and all older invoices is greater than the specified amount.
640 Returns a list: an empty list on success or a list of errors.
644 sub cust_suspend_if_balance_over {
645 my( $self, $amount ) = ( shift, shift );
646 my $cust_main = $self->cust_main;
647 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
650 $cust_main->suspend(@_);
656 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
662 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
663 sort { $a->_date <=> $b->_date }
664 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
669 =item cust_credit_bill
671 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
677 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
678 sort { $a->_date <=> $b->_date }
679 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
683 sub cust_credit_bill {
684 shift->cust_credited(@_);
687 #=item cust_bill_pay_pkgnum PKGNUM
689 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
690 #with matching pkgnum.
694 #sub cust_bill_pay_pkgnum {
695 # my( $self, $pkgnum ) = @_;
696 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
697 # sort { $a->_date <=> $b->_date }
698 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
699 # 'pkgnum' => $pkgnum,
704 =item cust_bill_pay_pkg PKGNUM
706 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
707 applied against the matching pkgnum.
711 sub cust_bill_pay_pkg {
712 my( $self, $pkgnum ) = @_;
715 'select' => 'cust_bill_pay_pkg.*',
716 'table' => 'cust_bill_pay_pkg',
717 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
718 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
719 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
720 " AND cust_bill_pkg.pkgnum = $pkgnum",
725 #=item cust_credited_pkgnum PKGNUM
727 #=item cust_credit_bill_pkgnum PKGNUM
729 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
730 #with matching pkgnum.
734 #sub cust_credited_pkgnum {
735 # my( $self, $pkgnum ) = @_;
736 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
737 # sort { $a->_date <=> $b->_date }
738 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
739 # 'pkgnum' => $pkgnum,
744 #sub cust_credit_bill_pkgnum {
745 # shift->cust_credited_pkgnum(@_);
748 =item cust_credit_bill_pkg PKGNUM
750 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
751 applied against the matching pkgnum.
755 sub cust_credit_bill_pkg {
756 my( $self, $pkgnum ) = @_;
759 'select' => 'cust_credit_bill_pkg.*',
760 'table' => 'cust_credit_bill_pkg',
761 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
762 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
763 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
764 " AND cust_bill_pkg.pkgnum = $pkgnum",
769 =item cust_bill_batch
771 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
775 sub cust_bill_batch {
777 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
782 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
783 hash keyed by term length.
789 FS::discount_plan->all($self);
794 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
801 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
803 foreach (@taxlines) { $total += $_->setup; }
809 Returns the amount owed (still outstanding) on this invoice, which is charged
810 minus all payment applications (see L<FS::cust_bill_pay>) and credit
811 applications (see L<FS::cust_credit_bill>).
817 my $balance = $self->charged;
818 $balance -= $_->amount foreach ( $self->cust_bill_pay );
819 $balance -= $_->amount foreach ( $self->cust_credited );
820 $balance = sprintf( "%.2f", $balance);
821 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
826 my( $self, $pkgnum ) = @_;
828 #my $balance = $self->charged;
830 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
832 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
833 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
835 $balance = sprintf( "%.2f", $balance);
836 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
842 Returns true if this invoice should be hidden. See the
843 selfservice-hide_invoices-taxclass configuraiton setting.
849 my $conf = $self->conf;
850 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
852 my @cust_bill_pkg = $self->cust_bill_pkg;
853 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
854 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
857 =item apply_payments_and_credits [ OPTION => VALUE ... ]
859 Applies unapplied payments and credits to this invoice.
861 A hash of optional arguments may be passed. Currently "manual" is supported.
862 If true, a payment receipt is sent instead of a statement when
863 'payment_receipt_email' configuration option is set.
865 If there is an error, returns the error, otherwise returns false.
869 sub apply_payments_and_credits {
870 my( $self, %options ) = @_;
871 my $conf = $self->conf;
873 local $SIG{HUP} = 'IGNORE';
874 local $SIG{INT} = 'IGNORE';
875 local $SIG{QUIT} = 'IGNORE';
876 local $SIG{TERM} = 'IGNORE';
877 local $SIG{TSTP} = 'IGNORE';
878 local $SIG{PIPE} = 'IGNORE';
880 my $oldAutoCommit = $FS::UID::AutoCommit;
881 local $FS::UID::AutoCommit = 0;
884 $self->select_for_update; #mutex
886 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
887 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
889 if ( $conf->exists('pkg-balances') ) {
890 # limit @payments & @credits to those w/ a pkgnum grepped from $self
891 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
892 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
893 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
896 while ( $self->owed > 0 and ( @payments || @credits ) ) {
899 if ( @payments && @credits ) {
901 #decide which goes first by weight of top (unapplied) line item
903 my @open_lineitems = $self->open_cust_bill_pkg;
906 max( map { $_->part_pkg->pay_weight || 0 }
911 my $max_credit_weight =
912 max( map { $_->part_pkg->credit_weight || 0 }
918 #if both are the same... payments first? it has to be something
919 if ( $max_pay_weight >= $max_credit_weight ) {
925 } elsif ( @payments ) {
927 } elsif ( @credits ) {
930 die "guru meditation #12 and 35";
934 if ( $app eq 'pay' ) {
936 my $payment = shift @payments;
937 $unapp_amount = $payment->unapplied;
938 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
939 $app->pkgnum( $payment->pkgnum )
940 if $conf->exists('pkg-balances') && $payment->pkgnum;
942 } elsif ( $app eq 'credit' ) {
944 my $credit = shift @credits;
945 $unapp_amount = $credit->credited;
946 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
947 $app->pkgnum( $credit->pkgnum )
948 if $conf->exists('pkg-balances') && $credit->pkgnum;
951 die "guru meditation #12 and 35";
955 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
956 warn "owed_pkgnum ". $app->pkgnum;
957 $owed = $self->owed_pkgnum($app->pkgnum);
961 next unless $owed > 0;
963 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
964 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
966 $app->invnum( $self->invnum );
968 my $error = $app->insert(%options);
970 $dbh->rollback if $oldAutoCommit;
971 return "Error inserting ". $app->table. " record: $error";
973 die $error if $error;
977 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
982 =item generate_email OPTION => VALUE ...
990 sender address, required
994 alternate template name, optional
998 text attachment arrayref, optional
1002 email subject, optional
1006 notice name instead of "Invoice", optional
1010 Returns an argument list to be passed to L<FS::Misc::send_email>.
1016 sub generate_email {
1020 my $conf = $self->conf;
1022 my $me = '[FS::cust_bill::generate_email]';
1025 'from' => $args{'from'},
1026 'subject' => ($args{'subject'} || $self->email_subject),
1027 'custnum' => $self->custnum,
1028 'msgtype' => 'invoice',
1031 $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1033 my $cust_main = $self->cust_main;
1035 if (ref($args{'to'}) eq 'ARRAY') {
1036 $return{'to'} = $args{'to'};
1038 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1039 $cust_main->invoicing_list
1043 if ( $conf->exists('invoice_html') ) {
1045 warn "$me creating HTML/text multipart message"
1048 $return{'nobody'} = 1;
1050 my $alternative = build MIME::Entity
1051 'Type' => 'multipart/alternative',
1052 #'Encoding' => '7bit',
1053 'Disposition' => 'inline'
1057 if ( $conf->exists('invoice_email_pdf')
1058 and scalar($conf->config('invoice_email_pdf_note')) ) {
1060 warn "$me using 'invoice_email_pdf_note' in multipart message"
1062 $data = [ map { $_ . "\n" }
1063 $conf->config('invoice_email_pdf_note')
1068 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1070 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1071 $data = $args{'print_text'};
1073 $data = [ $self->print_text(\%args) ];
1078 $alternative->attach(
1079 'Type' => 'text/plain',
1080 'Encoding' => 'quoted-printable',
1081 'Charset' => 'UTF-8',
1082 #'Encoding' => '7bit',
1084 'Disposition' => 'inline',
1091 if ( $conf->exists('invoice_email_pdf')
1092 and scalar($conf->config('invoice_email_pdf_note')) ) {
1094 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1098 $args{'from'} =~ /\@([\w\.\-]+)/;
1099 my $from = $1 || 'example.com';
1100 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1103 my $agentnum = $cust_main->agentnum;
1104 if ( defined($args{'template'}) && length($args{'template'})
1105 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1108 $logo = 'logo_'. $args{'template'}. '.png';
1112 my $image_data = $conf->config_binary( $logo, $agentnum);
1114 $image = build MIME::Entity
1115 'Type' => 'image/png',
1116 'Encoding' => 'base64',
1117 'Data' => $image_data,
1118 'Filename' => 'logo.png',
1119 'Content-ID' => "<$content_id>",
1122 if ($conf->exists('invoice-barcode')) {
1123 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1124 $barcode = build MIME::Entity
1125 'Type' => 'image/png',
1126 'Encoding' => 'base64',
1127 'Data' => $self->invoice_barcode(0),
1128 'Filename' => 'barcode.png',
1129 'Content-ID' => "<$barcode_content_id>",
1131 $args{'barcode_cid'} = $barcode_content_id;
1134 $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1137 $alternative->attach(
1138 'Type' => 'text/html',
1139 'Encoding' => 'quoted-printable',
1140 'Data' => [ '<html>',
1143 ' '. encode_entities($return{'subject'}),
1146 ' <body bgcolor="#e8e8e8">',
1151 'Disposition' => 'inline',
1152 #'Filename' => 'invoice.pdf',
1156 my @otherparts = ();
1157 if ( $cust_main->email_csv_cdr ) {
1159 push @otherparts, build MIME::Entity
1160 'Type' => 'text/csv',
1161 'Encoding' => '7bit',
1162 'Data' => [ map { "$_\n" }
1163 $self->call_details('prepend_billed_number' => 1)
1165 'Disposition' => 'attachment',
1166 'Filename' => 'usage-'. $self->invnum. '.csv',
1171 if ( $conf->exists('invoice_email_pdf') ) {
1176 # multipart/alternative
1182 my $related = build MIME::Entity 'Type' => 'multipart/related',
1183 'Encoding' => '7bit';
1185 #false laziness w/Misc::send_email
1186 $related->head->replace('Content-type',
1187 $related->mime_type.
1188 '; boundary="'. $related->head->multipart_boundary. '"'.
1189 '; type=multipart/alternative'
1192 $related->add_part($alternative);
1194 $related->add_part($image) if $image;
1196 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1198 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1202 #no other attachment:
1204 # multipart/alternative
1209 $return{'content-type'} = 'multipart/related';
1210 if ($conf->exists('invoice-barcode') && $barcode) {
1211 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1213 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1215 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1216 #$return{'disposition'} = 'inline';
1222 if ( $conf->exists('invoice_email_pdf') ) {
1223 warn "$me creating PDF attachment"
1226 #mime parts arguments a la MIME::Entity->build().
1227 $return{'mimeparts'} = [
1228 { $self->mimebuild_pdf(\%args) }
1232 if ( $conf->exists('invoice_email_pdf')
1233 and scalar($conf->config('invoice_email_pdf_note')) ) {
1235 warn "$me using 'invoice_email_pdf_note'"
1237 $return{'body'} = [ map { $_ . "\n" }
1238 $conf->config('invoice_email_pdf_note')
1243 warn "$me not using 'invoice_email_pdf_note'"
1245 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1246 $return{'body'} = $args{'print_text'};
1248 $return{'body'} = [ $self->print_text(\%args) ];
1261 Returns a list suitable for passing to MIME::Entity->build(), representing
1262 this invoice as PDF attachment.
1269 'Type' => 'application/pdf',
1270 'Encoding' => 'base64',
1271 'Data' => [ $self->print_pdf(@_) ],
1272 'Disposition' => 'attachment',
1273 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1279 Sends this invoice to the destinations configured for this customer: sends
1280 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1282 Options can be passed as a hashref. Positional parameters are no longer
1285 I<template>: a suffix for alternate invoices
1287 I<agentnum>: obsolete, now does nothing.
1289 I<invoice_from> overrides the default email invoice From: address.
1291 I<amount>: obsolete, does nothing
1293 I<notice_name> overrides "Invoice" as the name of the sent document
1294 (templates from 10/2009 or newer required).
1296 I<lpr> overrides the system 'lpr' option as the command to print a document
1297 from standard input.
1303 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1304 my $conf = $self->conf;
1306 my $cust_main = $self->cust_main;
1308 my @invoicing_list = $cust_main->invoicing_list;
1311 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1312 && ! $self->invoice_noemail;
1315 if grep { $_ eq 'POST' } @invoicing_list; #postal
1317 #this has never been used post-$ORIGINAL_ISP afaik
1318 $self->fax_invoice($opt)
1319 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1325 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1327 Sends this invoice to the customer's email destination(s).
1329 Options must be passed as a hashref. Positional parameters are no longer
1332 I<template>, if specified, is the name of a suffix for alternate invoices.
1334 I<invoice_from>, if specified, overrides the default email invoice From:
1337 I<notice_name> is the name of the sent document.
1341 sub queueable_email {
1344 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1345 or die "invalid invoice number: " . $opt{invnum};
1347 my %args = map {$_ => $opt{$_}}
1349 qw( invoice_from notice_name no_coupon template );
1351 my $error = $self->email( \%args );
1352 die $error if $error;
1358 return if $self->hide;
1359 my $conf = $self->conf;
1360 my $opt = shift || {};
1361 if ($opt and !ref($opt)) {
1362 die "FS::cust_bill::email called with positional parameters";
1365 my $template = $opt->{template};
1366 my $from = delete $opt->{invoice_from};
1368 # this is where we set the From: address
1369 $from ||= $self->_agent_invoice_from || #XXX should go away
1370 $conf->config('invoice_from', $self->cust_main->agentnum );
1372 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1373 $self->cust_main->invoicing_list;
1375 if ( ! @invoicing_list ) { #no recipients
1376 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1377 die 'No recipients for customer #'. $self->custnum;
1379 #default: better to notify this person than silence
1380 @invoicing_list = ($from);
1384 # this is where we set the Subject:
1385 my $subject = $self->email_subject($template);
1387 my $error = send_email(
1388 $self->generate_email(
1390 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1391 'subject' => $subject,
1392 %$opt, # template, etc.
1395 die "can't email invoice: $error\n" if $error;
1396 #die "$error\n" if $error;
1402 my $conf = $self->conf;
1404 #my $template = scalar(@_) ? shift : '';
1407 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1410 my $cust_main = $self->cust_main;
1411 my $name = $cust_main->name;
1412 my $name_short = $cust_main->name_short;
1413 my $invoice_number = $self->invnum;
1414 my $invoice_date = $self->_date_pretty;
1416 eval qq("$subject");
1419 =item lpr_data HASHREF
1421 Returns the postscript or plaintext for this invoice as an arrayref.
1423 Options must be passed as a hashref. Positional parameters are no longer
1426 I<template>, if specified, is the name of a suffix for alternate invoices.
1428 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1434 my $conf = $self->conf;
1435 my $opt = shift || {};
1436 if ($opt and !ref($opt)) {
1437 # nobody does this anyway
1438 die "FS::cust_bill::lpr_data called with positional parameters";
1441 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1442 [ $self->$method( $opt ) ];
1447 Prints this invoice.
1449 Options must be passed as a hashref.
1451 I<template>, if specified, is the name of a suffix for alternate invoices.
1453 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1459 return if $self->hide;
1460 my $conf = $self->conf;
1461 my $opt = shift || {};
1462 if ($opt and !ref($opt)) {
1463 die "FS::cust_bill::print called with positional parameters";
1466 my $lpr = delete $opt->{lpr};
1467 if($conf->exists('invoice_print_pdf')) {
1468 # Add the invoice to the current batch.
1469 $self->batch_invoice($opt);
1473 $self->lpr_data($opt),
1474 'agentnum' => $self->cust_main->agentnum,
1480 =item fax_invoice HASHREF
1484 Options must be passed as a hashref.
1486 I<template>, if specified, is the name of a suffix for alternate invoices.
1488 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1494 return if $self->hide;
1495 my $conf = $self->conf;
1496 my $opt = shift || {};
1497 if ($opt and !ref($opt)) {
1498 die "FS::cust_bill::fax_invoice called with positional parameters";
1501 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1502 unless $conf->exists('invoice_latex');
1504 my $dialstring = $self->cust_main->getfield('fax');
1507 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1508 'dialstring' => $dialstring,
1510 die $error if $error;
1514 =item batch_invoice [ HASHREF ]
1516 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1517 isn't an open batch, one will be created.
1522 my ($self, $opt) = @_;
1523 my $bill_batch = $self->get_open_bill_batch;
1524 my $cust_bill_batch = FS::cust_bill_batch->new({
1525 batchnum => $bill_batch->batchnum,
1526 invnum => $self->invnum,
1528 return $cust_bill_batch->insert($opt);
1531 =item get_open_batch
1533 Returns the currently open batch as an FS::bill_batch object, creating a new
1534 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1539 sub get_open_bill_batch {
1541 my $conf = $self->conf;
1542 my $hashref = { status => 'O' };
1543 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1544 ? $self->cust_main->agentnum
1546 my $batch = qsearchs('bill_batch', $hashref);
1547 return $batch if $batch;
1548 $batch = FS::bill_batch->new($hashref);
1549 my $error = $batch->insert;
1550 die $error if $error;
1554 =item ftp_invoice [ TEMPLATENAME ]
1556 Sends this invoice data via FTP.
1558 TEMPLATENAME is unused?
1564 my $conf = $self->conf;
1565 my $template = scalar(@_) ? shift : '';
1568 'protocol' => 'ftp',
1569 'server' => $conf->config('cust_bill-ftpserver'),
1570 'username' => $conf->config('cust_bill-ftpusername'),
1571 'password' => $conf->config('cust_bill-ftppassword'),
1572 'dir' => $conf->config('cust_bill-ftpdir'),
1573 'format' => $conf->config('cust_bill-ftpformat'),
1577 =item spool_invoice [ TEMPLATENAME ]
1579 Spools this invoice data (see L<FS::spool_csv>)
1581 TEMPLATENAME is unused?
1587 my $conf = $self->conf;
1588 my $template = scalar(@_) ? shift : '';
1591 'format' => $conf->config('cust_bill-spoolformat'),
1592 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1596 =item send_csv OPTION => VALUE, ...
1598 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1602 protocol - currently only "ftp"
1608 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1609 and YYMMDDHHMMSS is a timestamp.
1611 See L</print_csv> for a description of the output format.
1616 my($self, %opt) = @_;
1620 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1621 mkdir $spooldir, 0700 unless -d $spooldir;
1623 # don't localize dates here, they're a defined format
1624 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1625 my $file = "$spooldir/$tracctnum.csv";
1627 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1629 open(CSV, ">$file") or die "can't open $file: $!";
1637 if ( $opt{protocol} eq 'ftp' ) {
1638 eval "use Net::FTP;";
1640 $net = Net::FTP->new($opt{server}) or die @$;
1642 die "unknown protocol: $opt{protocol}";
1645 $net->login( $opt{username}, $opt{password} )
1646 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1648 $net->binary or die "can't set binary mode";
1650 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1652 $net->put($file) or die "can't put $file: $!";
1662 Spools CSV invoice data.
1668 =item format - any of FS::Misc::::Invoicing::spool_formats
1670 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1671 customer has the corresponding invoice destinations set (see
1672 L<FS::cust_main_invoice>).
1674 =item agent_spools - if set to a true value, will spool to per-agent files
1675 rather than a single global file
1677 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1678 append to that spool. L<FS::Cron::upload> will then send the spool file to
1681 =item balanceover - if set, only spools the invoice if the total amount owed on
1682 this invoice and all older invoices is greater than the specified amount.
1684 =item time - the "current time". Controls the printing of past due messages
1692 my($self, %opt) = @_;
1694 my $time = $opt{'time'} || time;
1695 my $cust_main = $self->cust_main;
1697 if ( $opt{'dest'} ) {
1698 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1699 $cust_main->invoicing_list;
1700 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1701 || ! keys %invoicing_list;
1704 if ( $opt{'balanceover'} ) {
1706 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1709 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1710 mkdir $spooldir, 0700 unless -d $spooldir;
1712 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1715 if ( $opt{'agent_spools'} ) {
1716 $file = 'agentnum'.$cust_main->agentnum;
1721 if ( $opt{'upload_targetnum'} ) {
1722 $spooldir .= '/target'.$opt{'upload_targetnum'};
1723 mkdir $spooldir, 0700 unless -d $spooldir;
1724 } # otherwise it just goes into export.xxx/cust_bill
1726 if ( lc($opt{'format'}) eq 'billco' ) {
1730 $file = "$spooldir/$file.csv";
1732 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1734 open(CSV, ">>$file") or die "can't open $file: $!";
1735 flock(CSV, LOCK_EX);
1740 if ( lc($opt{'format'}) eq 'billco' ) {
1742 flock(CSV, LOCK_UN);
1745 $file =~ s/-header.csv$/-detail.csv/;
1747 open(CSV,">>$file") or die "can't open $file: $!";
1748 flock(CSV, LOCK_EX);
1752 print CSV $detail if defined($detail);
1754 flock(CSV, LOCK_UN);
1761 =item print_csv OPTION => VALUE, ...
1763 Returns CSV data for this invoice.
1767 format - 'default', 'billco', 'oneline', 'bridgestone'
1769 Returns a list consisting of two scalars. The first is a single line of CSV
1770 header information for this invoice. The second is one or more lines of CSV
1771 detail information for this invoice.
1773 If I<format> is not specified or "default", the fields of the CSV file are as
1776 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1777 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1781 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1783 B<record_type> is C<cust_bill> for the initial header line only. The
1784 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1785 fields are filled in.
1787 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1788 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1791 =item invnum - invoice number
1793 =item custnum - customer number
1795 =item _date - invoice date
1797 =item charged - total invoice amount
1799 =item first - customer first name
1801 =item last - customer first name
1803 =item company - company name
1805 =item address1 - address line 1
1807 =item address2 - address line 1
1817 =item pkg - line item description
1819 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1821 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1823 =item sdate - start date for recurring fee
1825 =item edate - end date for recurring fee
1829 If I<format> is "billco", the fields of the header CSV file are as follows:
1831 +-------------------------------------------------------------------+
1832 | FORMAT HEADER FILE |
1833 |-------------------------------------------------------------------|
1834 | Field | Description | Name | Type | Width |
1835 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1836 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1837 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1838 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1839 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1840 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1841 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1842 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1843 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1844 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1845 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1846 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1847 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1848 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1849 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1850 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1851 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1852 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1853 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1854 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1855 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1856 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1857 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1858 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1859 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1860 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1861 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1862 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1863 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1864 +-------+-------------------------------+------------+------+-------+
1866 If I<format> is "billco", the fields of the detail CSV file are as follows:
1868 FORMAT FOR DETAIL FILE
1870 Field | Description | Name | Type | Width
1871 1 | N/A-Leave Empty | RC | CHAR | 2
1872 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1873 3 | Account Number | TRACCTNUM | CHAR | 15
1874 4 | Invoice Number | TRINVOICE | CHAR | 15
1875 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1876 6 | Transaction Detail | DETAILS | CHAR | 100
1877 7 | Amount | AMT | NUM* | 9
1878 8 | Line Format Control** | LNCTRL | CHAR | 2
1879 9 | Grouping Code | GROUP | CHAR | 2
1880 10 | User Defined | ACCT CODE | CHAR | 15
1882 If format is 'oneline', there is no detail file. Each invoice has a
1883 header line only, with the fields:
1885 Agent number, agent name, customer number, first name, last name, address
1886 line 1, address line 2, city, state, zip, invoice date, invoice number,
1887 amount charged, amount due, previous balance, due date.
1889 and then, for each line item, three columns containing the package number,
1890 description, and amount.
1892 If format is 'bridgestone', there is no detail file. Each invoice has a
1893 header line with the following fields in a fixed-width format:
1895 Customer number (in display format), date, name (first last), company,
1896 address 1, address 2, city, state, zip.
1898 This is a mailing list format, and has no per-invoice fields. To avoid
1899 sending redundant notices, the spooling event should have a "once" or
1900 "once_percust_every" condition.
1905 my($self, %opt) = @_;
1907 eval "use Text::CSV_XS";
1910 my $cust_main = $self->cust_main;
1912 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1913 my $format = lc($opt{'format'});
1915 my $time = $opt{'time'} || time;
1917 my $tracctnum = ''; #leaking out from billco-specific sections :/
1918 if ( $format eq 'billco' ) {
1921 $self->conf->config('billco-account_num', $cust_main->agentnum);
1923 $tracctnum = $account_num eq 'display_custnum'
1924 ? $cust_main->display_custnum
1925 : $opt{'tracctnum'};
1928 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1930 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1932 my( $previous_balance, @unused ) = $self->previous; #previous balance
1934 my $pmt_cr_applied = 0;
1935 $pmt_cr_applied += $_->{'amount'}
1936 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1938 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1941 '', # 1 | N/A-Leave Empty CHAR 2
1942 '', # 2 | N/A-Leave Empty CHAR 15
1943 $tracctnum, # 3 | Transaction Account No CHAR 15
1944 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1945 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1946 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1947 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1948 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1949 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1950 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1951 '', # 10 | Ancillary Billing Information CHAR 30
1952 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1953 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1956 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1959 $duedate, # 14 | Bill Due Date CHAR 10
1961 $previous_balance, # 15 | Previous Balance NUM* 9
1962 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1963 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1964 $totaldue, # 18 | Total Amt Due NUM* 9
1965 $totaldue, # 19 | Total Amt Due NUM* 9
1966 '', # 20 | 30 Day Aging NUM* 9
1967 '', # 21 | 60 Day Aging NUM* 9
1968 '', # 22 | 90 Day Aging NUM* 9
1969 'N', # 23 | Y/N CHAR 1
1970 '', # 24 | Remittance automation CHAR 100
1971 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1972 $self->custnum, # 26 | Customer Reference Number CHAR 15
1973 '0', # 27 | Federal Tax*** NUM* 9
1974 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1975 '0', # 29 | Other Taxes & Fees*** NUM* 9
1978 } elsif ( $format eq 'oneline' ) { #name
1980 my ($previous_balance) = $self->previous;
1981 $previous_balance = sprintf('%.2f', $previous_balance);
1982 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1988 $self->_items_pkg, #_items_nontax? no sections or anything
1993 $cust_main->agentnum,
1994 $cust_main->agent->agent,
1998 $cust_main->company,
1999 $cust_main->address1,
2000 $cust_main->address2,
2006 time2str("%x", $self->_date),
2011 $self->due_date2str("%x"),
2016 } elsif ( $format eq 'bridgestone' ) {
2018 # bypass the CSV stuff and just return this
2019 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2020 my $zip = $cust_main->zip;
2022 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2026 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2028 $cust_main->display_custnum,
2030 uc(substr($cust_main->contact_firstlast,0,30)),
2031 uc(substr($cust_main->company ,0,30)),
2032 uc(substr($cust_main->address1 ,0,30)),
2033 uc(substr($cust_main->address2 ,0,30)),
2034 uc(substr($cust_main->city ,0,20)),
2035 uc($cust_main->state),
2041 } elsif ( $format eq 'ics' ) {
2043 my $bill = $cust_main->bill_location;
2044 my $zip = $bill->zip;
2048 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2053 # minor false laziness with print_generic
2054 my ($previous_balance) = $self->previous;
2055 my $balance_due = $self->owed + $previous_balance;
2056 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2057 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2060 if ( $self->due_date and $time >= $self->due_date ) {
2061 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2065 my $header = sprintf(
2066 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2067 $cust_main->display_custnum, #BID
2068 uc($cust_main->first), #FNAME
2069 uc($cust_main->last), #LNAME
2070 '00', #BATCH, should this ever be anything else?
2071 uc($cust_main->company), #COMP
2072 uc($bill->address1), #STREET1
2073 uc($bill->address2), #STREET2
2074 uc($bill->city), #CITY
2075 uc($bill->state), #STATE
2078 time2str('%Y%m%d', $self->_date), #BILL_DATE
2079 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2080 ( map {sprintf('%0.2f', $_)}
2081 $balance_due, #AMNT_DUE
2082 $previous_balance, #PREV_BAL
2083 $payment_total, #PYMT_RCVD
2084 $credit_total, #CREDITS
2085 $previous_balance, #BEG_BAL--is this correct?
2086 $self->charged, #NEW_CHRG
2089 $past_due, #PAST_MSG
2093 my %svc_class = ('' => ''); # maybe cache this more persistently?
2095 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2097 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2098 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2102 my @dates = ( $self->_date, undef );
2103 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2104 $dates[1] = $prev->sdate; #questionable
2107 # generate an 01 detail for each service
2108 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2109 foreach my $cust_svc ( @svcs ) {
2110 $show_pkgnum = ''; # hide it if we're showing svcnums
2112 my $svcpart = $cust_svc->svcpart;
2113 if (!exists($svc_class{$svcpart})) {
2114 my $classnum = $cust_svc->part_svc->classnum;
2115 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2117 $svc_class{$svcpart} = $part_svc_class ?
2118 $part_svc_class->classname :
2122 my @h_label = $cust_svc->label(@dates, 'I');
2123 push @details, sprintf('01%-9s%-20s%-47s',
2125 $svc_class{$svcpart},
2128 } #foreach $cust_svc
2131 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2132 if ($cust_bill_pkg->recur > 0) {
2133 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2134 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2136 push @details, sprintf('02%-6s%-60s%-10s',
2139 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2141 } #foreach $cust_bill_pkg
2143 # Tag this row so that we know whether this is one page (1), two pages
2144 # (2), # or "big" (B). The tag will be stripped off before uploading.
2145 if ( scalar(@details) < 12 ) {
2147 } elsif ( scalar(@details) < 58 ) {
2153 return join('', $header, @details, "\n");
2161 time2str("%x", $self->_date),
2162 sprintf("%.2f", $self->charged),
2163 ( map { $cust_main->getfield($_) }
2164 qw( first last company address1 address2 city state zip country ) ),
2166 ) or die "can't create csv";
2169 my $header = $csv->string. "\n";
2172 if ( lc($opt{'format'}) eq 'billco' ) {
2175 foreach my $item ( $self->_items_pkg ) {
2178 '', # 1 | N/A-Leave Empty CHAR 2
2179 '', # 2 | N/A-Leave Empty CHAR 15
2180 $tracctnum, # 3 | Account Number CHAR 15
2181 $self->invnum, # 4 | Invoice Number CHAR 15
2182 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2183 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2184 $item->{'amount'}, # 7 | Amount NUM* 9
2185 '', # 8 | Line Format Control** CHAR 2
2186 '', # 9 | Grouping Code CHAR 2
2187 '', # 10 | User Defined CHAR 15
2190 $detail .= $csv->string. "\n";
2194 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2200 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2202 my($pkg, $setup, $recur, $sdate, $edate);
2203 if ( $cust_bill_pkg->pkgnum ) {
2205 ($pkg, $setup, $recur, $sdate, $edate) = (
2206 $cust_bill_pkg->part_pkg->pkg,
2207 ( $cust_bill_pkg->setup != 0
2208 ? sprintf("%.2f", $cust_bill_pkg->setup )
2210 ( $cust_bill_pkg->recur != 0
2211 ? sprintf("%.2f", $cust_bill_pkg->recur )
2213 ( $cust_bill_pkg->sdate
2214 ? time2str("%x", $cust_bill_pkg->sdate)
2216 ($cust_bill_pkg->edate
2217 ? time2str("%x", $cust_bill_pkg->edate)
2221 } else { #pkgnum tax
2222 next unless $cust_bill_pkg->setup != 0;
2223 $pkg = $cust_bill_pkg->desc;
2224 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2225 ( $sdate, $edate ) = ( '', '' );
2231 ( map { '' } (1..11) ),
2232 ($pkg, $setup, $recur, $sdate, $edate)
2233 ) or die "can't create csv";
2235 $detail .= $csv->string. "\n";
2241 ( $header, $detail );
2247 Pays this invoice with a compliemntary payment. If there is an error,
2248 returns the error, otherwise returns false.
2254 my $cust_pay = new FS::cust_pay ( {
2255 'invnum' => $self->invnum,
2256 'paid' => $self->owed,
2259 'payinfo' => $self->cust_main->payinfo,
2267 Attempts to pay this invoice with a credit card payment via a
2268 Business::OnlinePayment realtime gateway. See
2269 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2270 for supported processors.
2276 $self->realtime_bop( 'CC', @_ );
2281 Attempts to pay this invoice with an electronic check (ACH) payment via a
2282 Business::OnlinePayment realtime gateway. See
2283 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2284 for supported processors.
2290 $self->realtime_bop( 'ECHECK', @_ );
2295 Attempts to pay this invoice with phone bill (LEC) payment via a
2296 Business::OnlinePayment realtime gateway. See
2297 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2298 for supported processors.
2304 $self->realtime_bop( 'LEC', @_ );
2308 my( $self, $method ) = (shift,shift);
2309 my $conf = $self->conf;
2312 my $cust_main = $self->cust_main;
2313 my $balance = $cust_main->balance;
2314 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2315 $amount = sprintf("%.2f", $amount);
2316 return "not run (balance $balance)" unless $amount > 0;
2318 my $description = 'Internet Services';
2319 if ( $conf->exists('business-onlinepayment-description') ) {
2320 my $dtempl = $conf->config('business-onlinepayment-description');
2322 my $agent_obj = $cust_main->agent
2323 or die "can't retreive agent for $cust_main (agentnum ".
2324 $cust_main->agentnum. ")";
2325 my $agent = $agent_obj->agent;
2326 my $pkgs = join(', ',
2327 map { $_->part_pkg->pkg }
2328 grep { $_->pkgnum } $self->cust_bill_pkg
2330 $description = eval qq("$dtempl");
2333 $cust_main->realtime_bop($method, $amount,
2334 'description' => $description,
2335 'invnum' => $self->invnum,
2336 #this didn't do what we want, it just calls apply_payments_and_credits
2338 'apply_to_invoice' => 1,
2341 #this changes application behavior: auto payments
2342 #triggered against a specific invoice are now applied
2343 #to that invoice instead of oldest open.
2349 =item batch_card OPTION => VALUE...
2351 Adds a payment for this invoice to the pending credit card batch (see
2352 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2353 runs the payment using a realtime gateway.
2358 my ($self, %options) = @_;
2359 my $cust_main = $self->cust_main;
2361 $options{invnum} = $self->invnum;
2363 $cust_main->batch_card(%options);
2366 sub _agent_template {
2368 $self->cust_main->agent_template;
2371 sub _agent_invoice_from {
2373 $self->cust_main->agent_invoice_from;
2376 =item invoice_barcode DIR_OR_FALSE
2378 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2379 it is taken as the temp directory where the PNG file will be generated and the
2380 PNG file name is returned. Otherwise, the PNG image itself is returned.
2384 sub invoice_barcode {
2385 my ($self, $dir) = (shift,shift);
2387 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2388 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2389 my $gd = $gdbar->plot(Height => 30);
2392 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2396 ) or die "can't open temp file: $!\n";
2397 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2398 my $png_file = $bh->filename;
2405 =item invnum_date_pretty
2407 Returns a string with the invoice number and date, for example:
2408 "Invoice #54 (3/20/2008)"
2412 sub invnum_date_pretty {
2414 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
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_previous {
2924 my $conf = $self->conf;
2925 my $cust_main = $self->cust_main;
2926 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2928 foreach ( @pr_cust_bill ) {
2929 my $date = $conf->exists('invoice_show_prior_due_date')
2930 ? 'due '. $_->due_date2str('short')
2931 : $self->time2str_local('short', $_->_date);
2933 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2934 #'pkgpart' => 'N/A',
2936 'amount' => sprintf("%.2f", $_->owed),
2942 # 'description' => 'Previous Balance',
2943 # #'pkgpart' => 'N/A',
2944 # 'pkgnum' => 'N/A',
2945 # 'amount' => sprintf("%10.2f", $pr_total ),
2946 # 'ext_description' => [ map {
2947 # "Invoice ". $_->invnum.
2948 # " (". time2str("%x",$_->_date). ") ".
2949 # sprintf("%10.2f", $_->owed)
2950 # } @pr_cust_bill ],
2955 sub _items_credits {
2956 my( $self, %opt ) = @_;
2957 my $trim_len = $opt{'trim_len'} || 60;
2962 if ( $self->conf->exists('previous_balance-payments_since') ) {
2963 if ( $opt{'template'} eq 'statement' ) {
2964 # then the current bill is a "statement" (i.e. an invoice sent as
2965 # a payment receipt)
2966 # and in that case we want to see payments on or after THIS invoice
2967 @objects = qsearch('cust_credit', {
2968 'custnum' => $self->custnum,
2969 '_date' => {op => '>=', value => $self->_date},
2973 $date = $self->previous_bill->_date if $self->previous_bill;
2974 @objects = qsearch('cust_credit', {
2975 'custnum' => $self->custnum,
2976 '_date' => {op => '>=', value => $date},
2980 @objects = $self->cust_credited;
2983 foreach my $obj ( @objects ) {
2984 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2986 my $reason = substr($cust_credit->reason, 0, $trim_len);
2987 $reason .= '...' if length($reason) < length($cust_credit->reason);
2988 $reason = " ($reason) " if $reason;
2991 #'description' => 'Credit ref\#'. $_->crednum.
2992 # " (". time2str("%x",$_->cust_credit->_date) .")".
2994 'description' => $self->mt('Credit applied').' '.
2995 $self->time2str_local('short', $obj->_date). $reason,
2996 'amount' => sprintf("%.2f",$obj->amount),
3004 sub _items_payments {
3009 my $detailed = $self->conf->exists('invoice_payment_details');
3011 if ( $self->conf->exists('previous_balance-payments_since') ) {
3012 # then show payments dated on/after the previous bill...
3013 if ( $opt{'template'} eq 'statement' ) {
3014 # then the current bill is a "statement" (i.e. an invoice sent as
3015 # a payment receipt)
3016 # and in that case we want to see payments on or after THIS invoice
3017 @objects = qsearch('cust_pay', {
3018 'custnum' => $self->custnum,
3019 '_date' => {op => '>=', value => $self->_date},
3022 # the normal case: payments on or after the previous invoice
3024 $date = $self->previous_bill->_date if $self->previous_bill;
3025 @objects = qsearch('cust_pay', {
3026 'custnum' => $self->custnum,
3027 '_date' => {op => '>=', value => $date},
3029 # and before the current bill...
3030 @objects = grep { $_->_date < $self->_date } @objects;
3033 @objects = $self->cust_bill_pay;
3036 foreach my $obj (@objects) {
3037 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3038 my $desc = $self->mt('Payment received').' '.
3039 $self->time2str_local('short', $cust_pay->_date );
3040 $desc .= $self->mt(' via ') .
3041 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3045 'description' => $desc,
3046 'amount' => sprintf("%.2f", $obj->amount )
3054 =item call_details [ OPTION => VALUE ... ]
3056 Returns an array of CSV strings representing the call details for this invoice
3057 The only option available is the boolean prepend_billed_number
3062 my ($self, %opt) = @_;
3064 my $format_function = sub { shift };
3066 if ($opt{prepend_billed_number}) {
3067 $format_function = sub {
3071 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3076 my @details = map { $_->details( 'format_function' => $format_function,
3077 'escape_function' => sub{ return() },
3081 $self->cust_bill_pkg;
3082 my $header = $details[0];
3083 ( $header, grep { $_ ne $header } @details );
3093 =item process_reprint
3097 sub process_reprint {
3098 process_re_X('print', @_);
3101 =item process_reemail
3105 sub process_reemail {
3106 process_re_X('email', @_);
3114 process_re_X('fax', @_);
3122 process_re_X('ftp', @_);
3129 sub process_respool {
3130 process_re_X('spool', @_);
3133 use Storable qw(thaw);
3137 my( $method, $job ) = ( shift, shift );
3138 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3140 my $param = thaw(decode_base64(shift));
3141 warn Dumper($param) if $DEBUG;
3152 # spool_invoice ftp_invoice fax_invoice print_invoice
3153 my($method, $job, %param ) = @_;
3155 warn "re_X $method for job $job with param:\n".
3156 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3159 #some false laziness w/search/cust_bill.html
3161 my $orderby = 'ORDER BY cust_bill._date';
3163 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3165 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3167 my @cust_bill = qsearch( {
3168 #'select' => "cust_bill.*",
3169 'table' => 'cust_bill',
3170 'addl_from' => $addl_from,
3172 'extra_sql' => $extra_sql,
3173 'order_by' => $orderby,
3177 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3179 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3182 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3183 foreach my $cust_bill ( @cust_bill ) {
3184 $cust_bill->$method();
3186 if ( $job ) { #progressbar foo
3188 if ( time - $min_sec > $last ) {
3189 my $error = $job->update_statustext(
3190 int( 100 * $num / scalar(@cust_bill) )
3192 die $error if $error;
3203 =head1 CLASS METHODS
3209 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3214 my ($class, $start, $end) = @_;
3216 $class->paid_sql($start, $end). ' - '.
3217 $class->credited_sql($start, $end);
3222 Returns an SQL fragment to retreive the net amount (charged minus credited).
3227 my ($class, $start, $end) = @_;
3228 'charged - '. $class->credited_sql($start, $end);
3233 Returns an SQL fragment to retreive the amount paid against this invoice.
3238 my ($class, $start, $end) = @_;
3239 $start &&= "AND cust_bill_pay._date <= $start";
3240 $end &&= "AND cust_bill_pay._date > $end";
3241 $start = '' unless defined($start);
3242 $end = '' unless defined($end);
3243 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3244 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3249 Returns an SQL fragment to retreive the amount credited against this invoice.
3254 my ($class, $start, $end) = @_;
3255 $start &&= "AND cust_credit_bill._date <= $start";
3256 $end &&= "AND cust_credit_bill._date > $end";
3257 $start = '' unless defined($start);
3258 $end = '' unless defined($end);
3259 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3260 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3265 Returns an SQL fragment to retrieve the due date of an invoice.
3266 Currently only supported on PostgreSQL.
3271 my $conf = new FS::Conf;
3275 cust_bill.invoice_terms,
3276 cust_main.invoice_terms,
3277 \''.($conf->config('invoice_default_terms') || '').'\'
3278 ), E\'Net (\\\\d+)\'
3280 ) * 86400 + cust_bill._date'
3283 =item search_sql_where HASHREF
3285 Class method which returns an SQL WHERE fragment to search for parameters
3286 specified in HASHREF. Valid parameters are
3292 List reference of start date, end date, as UNIX timestamps.
3302 List reference of charged limits (exclusive).
3306 List reference of charged limits (exclusive).
3310 flag, return open invoices only
3314 flag, return net invoices only
3318 =item newest_percust
3322 Return only invoices belonging to that customer.
3326 Limit to that customer class (single value or arrayref).
3330 Limit to customers with that payment method (single value or arrayref).
3334 Limit to customers with that advertising source.
3338 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3342 sub search_sql_where {
3343 my($class, $param) = @_;
3345 warn "$me search_sql_where called with params: \n".
3346 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3352 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3353 push @search, "cust_main.agentnum = $1";
3357 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3358 push @search, "cust_main.refnum = $1";
3362 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3363 push @search, "cust_bill.custnum = $1";
3366 #customer classnum (false laziness w/ cust_main/Search.pm)
3367 if ( $param->{'cust_classnum'} ) {
3369 my @classnum = ref( $param->{'cust_classnum'} )
3370 ? @{ $param->{'cust_classnum'} }
3371 : ( $param->{'cust_classnum'} );
3373 @classnum = grep /^(\d*)$/, @classnum;
3376 push @search, '( '. join(' OR ', map {
3377 $_ ? "cust_main.classnum = $_"
3378 : "cust_main.classnum IS NULL"
3388 if ( $param->{payby} ) {
3389 my $payby = $param->{payby};
3390 $payby = [ $payby ] unless ref $payby;
3391 my $payby_in = join(',', map {dbh->quote($_)} @$payby);
3392 push @search, "cust_main.payby IN($payby_in)" if length($payby_in);
3396 if ( $param->{_date} ) {
3397 my($beginning, $ending) = @{$param->{_date}};
3399 push @search, "cust_bill._date >= $beginning",
3400 "cust_bill._date < $ending";
3404 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3405 push @search, "cust_bill.invnum >= $1";
3407 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3408 push @search, "cust_bill.invnum <= $1";
3412 if ( $param->{charged} ) {
3413 my @charged = ref($param->{charged})
3414 ? @{ $param->{charged} }
3415 : ($param->{charged});
3417 push @search, map { s/^charged/cust_bill.charged/; $_; }
3421 my $owed_sql = FS::cust_bill->owed_sql;
3424 if ( $param->{owed} ) {
3425 my @owed = ref($param->{owed})
3426 ? @{ $param->{owed} }
3428 push @search, map { s/^owed/$owed_sql/; $_; }
3433 push @search, "0 != $owed_sql"
3434 if $param->{'open'};
3435 push @search, '0 != '. FS::cust_bill->net_sql
3439 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3440 if $param->{'days'};
3443 if ( $param->{'newest_percust'} ) {
3445 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3446 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3448 my @newest_where = map { my $x = $_;
3449 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3452 grep ! /^cust_main./, @search;
3453 my $newest_where = scalar(@newest_where)
3454 ? ' AND '. join(' AND ', @newest_where)
3458 push @search, "cust_bill._date = (
3459 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3460 WHERE newest_cust_bill.custnum = cust_bill.custnum
3466 #promised_date - also has an option to accept nulls
3467 if ( $param->{promised_date} ) {
3468 my($beginning, $ending, $null) = @{$param->{promised_date}};
3470 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3471 "cust_bill.promised_date < $ending )" .
3472 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3475 #agent virtualization
3476 my $curuser = $FS::CurrentUser::CurrentUser;
3477 if ( $curuser->username eq 'fs_queue'
3478 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3480 my $newuser = qsearchs('access_user', {
3481 'username' => $username,
3485 $curuser = $newuser;
3487 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3490 push @search, $curuser->agentnums_sql;
3492 join(' AND ', @search );
3504 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3505 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base