2 use base qw( FS::cust_bill::Search FS::Template_Mixin
3 FS::cust_main_Mixin FS::Record
7 use vars qw( $DEBUG $me );
10 use Fcntl qw(:flock); #for spool_csv
12 use List::Util qw(min max sum);
16 use Storable qw( freeze thaw );
18 use FS::UID qw( datasrc );
19 use FS::Misc qw( send_fax do_print );
20 use FS::Record qw( qsearch qsearchs dbh );
21 use FS::cust_statement;
22 use FS::cust_bill_pkg;
23 use FS::cust_bill_pkg_display;
24 use FS::cust_bill_pkg_detail;
28 use FS::cust_credit_bill;
32 use FS::cust_bill_pay;
35 use FS::cust_bill_batch;
36 use FS::cust_bill_pay_pkg;
37 use FS::cust_credit_bill_pkg;
38 use FS::discount_plan;
39 use FS::cust_bill_void;
43 $me = '[FS::cust_bill]';
47 FS::cust_bill - Object methods for cust_bill records
53 $record = new FS::cust_bill \%hash;
54 $record = new FS::cust_bill { 'column' => 'value' };
56 $error = $record->insert;
58 $error = $new_record->replace($old_record);
60 $error = $record->delete;
62 $error = $record->check;
64 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
66 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
68 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
70 @cust_pay_objects = $cust_bill->cust_pay;
72 $tax_amount = $record->tax;
74 @lines = $cust_bill->print_text;
75 @lines = $cust_bill->print_text('time' => $time);
79 An FS::cust_bill object represents an invoice; a declaration that a customer
80 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
81 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
82 following fields are currently supported:
88 =item invnum - primary key (assigned automatically for new invoices)
90 =item custnum - customer (see L<FS::cust_main>)
92 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
93 L<Time::Local> and L<Date::Parse> for conversion functions.
95 =item charged - amount of this invoice
97 =item invoice_terms - optional terms override for this specific invoice
105 =item billing_balance - the customer's balance immediately before generating
106 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
107 to determine the customer's balance at a specific time.
109 =item previous_balance - the customer's balance immediately after generating
110 the invoice before this one. DEPRECATED.
112 =item printed - formerly used to track the number of times an invoice had
113 been printed; no longer used.
121 =item closed - books closed flag, empty or `Y'
123 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
125 =item agent_invid - legacy invoice number
127 =item promised_date - customer promised payment date, for collection
129 =item pending - invoice is still being generated, empty or 'Y'
139 Creates a new invoice. To add the invoice to the database, see L<"insert">.
140 Invoices are normally created by calling the bill method of a customer object
141 (see L<FS::cust_main>).
145 sub table { 'cust_bill'; }
146 sub template_conf { 'invoice_'; }
150 my $agentnum = $self->cust_main->agentnum;
151 my $tc = $self->template_conf;
153 $self->conf->exists($tc.'sections', $agentnum) ||
154 $self->conf->exists($tc.'sections_by_location', $agentnum);
157 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
158 # (except email_subject and invnum_date_pretty)
161 $self->conf->config('notice_name') || 'Invoice'
164 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
165 sub cust_unlinked_msg {
167 "WARNING: can't find cust_main.custnum ". $self->custnum.
168 ' (cust_bill.invnum '. $self->invnum. ')';
173 Adds this invoice to the database ("Posts" the invoice). If there is an error,
174 returns the error, otherwise returns false.
180 warn "$me insert called\n" if $DEBUG;
182 local $SIG{HUP} = 'IGNORE';
183 local $SIG{INT} = 'IGNORE';
184 local $SIG{QUIT} = 'IGNORE';
185 local $SIG{TERM} = 'IGNORE';
186 local $SIG{TSTP} = 'IGNORE';
187 local $SIG{PIPE} = 'IGNORE';
189 my $oldAutoCommit = $FS::UID::AutoCommit;
190 local $FS::UID::AutoCommit = 0;
193 my $error = $self->SUPER::insert;
195 $dbh->rollback if $oldAutoCommit;
199 if ( $self->get('cust_bill_pkg') ) {
200 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
201 $cust_bill_pkg->invnum($self->invnum);
202 my $error = $cust_bill_pkg->insert;
204 $dbh->rollback if $oldAutoCommit;
205 return "can't create invoice line item: $error";
210 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
217 Voids this invoice: deletes the invoice and adds a record of the voided invoice
218 to the FS::cust_bill_void table (and related tables starting from
219 FS::cust_bill_pkg_void).
225 my $reason = scalar(@_) ? shift : '';
227 local $SIG{HUP} = 'IGNORE';
228 local $SIG{INT} = 'IGNORE';
229 local $SIG{QUIT} = 'IGNORE';
230 local $SIG{TERM} = 'IGNORE';
231 local $SIG{TSTP} = 'IGNORE';
232 local $SIG{PIPE} = 'IGNORE';
234 my $oldAutoCommit = $FS::UID::AutoCommit;
235 local $FS::UID::AutoCommit = 0;
238 my $cust_bill_void = new FS::cust_bill_void ( {
239 map { $_ => $self->get($_) } $self->fields
241 $cust_bill_void->reason($reason);
242 my $error = $cust_bill_void->insert;
244 $dbh->rollback if $oldAutoCommit;
248 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
249 my $error = $cust_bill_pkg->void($reason);
251 $dbh->rollback if $oldAutoCommit;
256 $error = $self->delete;
258 $dbh->rollback if $oldAutoCommit;
262 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
270 This method now works but you probably shouldn't use it. Instead, apply a
271 credit against the invoice, or use the new void method.
273 Using this method to delete invoices outright is really, really bad. There
274 would be no record you ever posted this invoice, and there are no check to
275 make sure charged = 0 or that there are no associated cust_bill_pkg records.
277 Really, don't use it.
283 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
285 local $SIG{HUP} = 'IGNORE';
286 local $SIG{INT} = 'IGNORE';
287 local $SIG{QUIT} = 'IGNORE';
288 local $SIG{TERM} = 'IGNORE';
289 local $SIG{TSTP} = 'IGNORE';
290 local $SIG{PIPE} = 'IGNORE';
292 my $oldAutoCommit = $FS::UID::AutoCommit;
293 local $FS::UID::AutoCommit = 0;
296 foreach my $table (qw(
304 #cust_event # problematic
306 foreach my $linked ( $self->$table() ) {
307 my $error = $linked->delete;
309 $dbh->rollback if $oldAutoCommit;
316 my $error = $self->SUPER::delete(@_);
318 $dbh->rollback if $oldAutoCommit;
322 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
328 =item replace [ OLD_RECORD ]
330 You can, but probably shouldn't modify invoices...
332 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
333 supplied, replaces this record. If there is an error, returns the error,
334 otherwise returns false.
338 #replace can be inherited from Record.pm
340 # replace_check is now the preferred way to #implement replace data checks
341 # (so $object->replace() works without an argument)
344 my( $new, $old ) = ( shift, shift );
345 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
346 #return "Can't change _date!" unless $old->_date eq $new->_date;
347 return "Can't change _date" unless $old->_date == $new->_date;
348 return "Can't change charged" unless $old->charged == $new->charged
349 || $old->pending eq 'Y'
350 || $old->charged == 0
351 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
357 =item add_cc_surcharge
363 sub add_cc_surcharge {
364 my ($self, $pkgnum, $amount) = (shift, shift, shift);
367 my $cust_bill_pkg = new FS::cust_bill_pkg({
368 'invnum' => $self->invnum,
372 $error = $cust_bill_pkg->insert;
373 return $error if $error;
375 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
376 $self->charged($self->charged+$amount);
377 $error = $self->replace;
378 return $error if $error;
380 $self->apply_payments_and_credits;
386 Checks all fields to make sure this is a valid invoice. If there is an error,
387 returns the error, otherwise returns false. Called by the insert and replace
396 $self->ut_numbern('invnum')
397 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
398 || $self->ut_numbern('_date')
399 || $self->ut_money('charged')
400 || $self->ut_numbern('printed')
401 || $self->ut_enum('closed', [ '', 'Y' ])
402 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
403 || $self->ut_numbern('agent_invid') #varchar?
404 || $self->ut_flag('pending')
406 return $error if $error;
408 $self->_date(time) unless $self->_date;
410 $self->printed(0) if $self->printed eq '';
417 Returns the displayed invoice number for this invoice: agent_invid if
418 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
424 if ( $self->agent_invid
425 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
426 return $self->agent_invid;
428 return $self->invnum;
434 Returns the customer's last invoice before this one.
440 if ( !$self->get('previous_bill') ) {
441 $self->set('previous_bill', qsearchs({
442 'table' => 'cust_bill',
443 'hashref' => { 'custnum' => $self->custnum,
444 '_date' => { op=>'<', value=>$self->_date } },
445 'order_by' => 'ORDER BY _date DESC LIMIT 1',
448 $self->get('previous_bill');
453 Returns a list consisting of the total previous balance for this customer,
454 followed by the previous outstanding invoices (as FS::cust_bill objects also).
460 # simple memoize; we use this a lot
461 if (!$self->get('previous')) {
463 my @cust_bill = sort { $a->_date <=> $b->_date }
464 grep { $_->owed != 0 }
465 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
466 #'_date' => { op=>'<', value=>$self->_date },
467 'invnum' => { op=>'<', value=>$self->invnum },
470 foreach ( @cust_bill ) { $total += $_->owed; }
471 $self->set('previous', [$total, @cust_bill]);
473 return @{ $self->get('previous') };
476 =item enable_previous
478 Whether to show the 'Previous Charges' section when printing this invoice.
479 The negation of the 'disable_previous_balance' config setting.
483 sub enable_previous {
485 my $agentnum = $self->cust_main->agentnum;
486 !$self->conf->exists('disable_previous_balance', $agentnum);
491 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
498 { 'table' => 'cust_bill_pkg',
499 'hashref' => { 'invnum' => $self->invnum },
500 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
501 # the AUTLOADED FK search. or should
502 # that default to ORDER by the pkey?
507 =item cust_bill_pkg_pkgnum PKGNUM
509 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
514 sub cust_bill_pkg_pkgnum {
515 my( $self, $pkgnum ) = @_;
517 { 'table' => 'cust_bill_pkg',
518 'hashref' => { 'invnum' => $self->invnum,
521 'order_by' => 'ORDER BY billpkgnum',
528 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
535 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
536 $self->cust_bill_pkg;
538 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
543 Returns true if any of the packages (or their definitions) corresponding to the
544 line items for this invoice have the no_auto flag set.
550 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
553 =item open_cust_bill_pkg
555 Returns the open line items for this invoice.
557 Note that cust_bill_pkg with both setup and recur fees are returned as two
558 separate line items, each with only one fee.
562 # modeled after cust_main::open_cust_bill
563 sub open_cust_bill_pkg {
566 # grep { $_->owed > 0 } $self->cust_bill_pkg
568 my %other = ( 'recur' => 'setup',
569 'setup' => 'recur', );
571 foreach my $field ( qw( recur setup )) {
572 push @open, map { $_->set( $other{$field}, 0 ); $_; }
573 grep { $_->owed($field) > 0 }
574 $self->cust_bill_pkg;
582 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
586 #false laziness w/cust_pkg.pm
590 'table' => 'cust_event',
591 'addl_from' => 'JOIN part_event USING ( eventpart )',
592 'hashref' => { 'tablenum' => $self->invnum },
593 'extra_sql' => " AND eventtable = 'cust_bill' ",
599 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
603 #false laziness w/cust_pkg.pm
607 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
608 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
609 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
610 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
611 $sth->fetchrow_arrayref->[0];
616 Returns the customer (see L<FS::cust_main>) for this invoice.
620 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice
622 Returns a list: an empty list on success or a list of errors.
629 grep { $_->suspend(@_) }
630 grep {! $_->getfield('cancel') }
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 Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options
661 my( $self, %opt ) = @_;
663 warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
664 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
667 return ( 'Access denied' )
668 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
670 my @pkgs = $self->cust_pkg;
672 if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
674 my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
675 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
680 map { $_->cancel(%opt) }
681 grep { ! $_->getfield('cancel') }
687 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
693 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
694 sort { $a->_date <=> $b->_date }
695 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
700 =item cust_credit_bill
702 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
708 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
709 sort { $a->_date <=> $b->_date }
710 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
714 sub cust_credit_bill {
715 shift->cust_credited(@_);
718 #=item cust_bill_pay_pkgnum PKGNUM
720 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
721 #with matching pkgnum.
725 #sub cust_bill_pay_pkgnum {
726 # my( $self, $pkgnum ) = @_;
727 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
728 # sort { $a->_date <=> $b->_date }
729 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
730 # 'pkgnum' => $pkgnum,
735 =item cust_bill_pay_pkg PKGNUM
737 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
738 applied against the matching pkgnum.
742 sub cust_bill_pay_pkg {
743 my( $self, $pkgnum ) = @_;
746 'select' => 'cust_bill_pay_pkg.*',
747 'table' => 'cust_bill_pay_pkg',
748 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
749 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
750 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
751 " AND cust_bill_pkg.pkgnum = $pkgnum",
756 #=item cust_credited_pkgnum PKGNUM
758 #=item cust_credit_bill_pkgnum PKGNUM
760 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
761 #with matching pkgnum.
765 #sub cust_credited_pkgnum {
766 # my( $self, $pkgnum ) = @_;
767 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
768 # sort { $a->_date <=> $b->_date }
769 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
770 # 'pkgnum' => $pkgnum,
775 #sub cust_credit_bill_pkgnum {
776 # shift->cust_credited_pkgnum(@_);
779 =item cust_credit_bill_pkg PKGNUM
781 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
782 applied against the matching pkgnum.
786 sub cust_credit_bill_pkg {
787 my( $self, $pkgnum ) = @_;
790 'select' => 'cust_credit_bill_pkg.*',
791 'table' => 'cust_credit_bill_pkg',
792 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
793 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
794 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
795 " AND cust_bill_pkg.pkgnum = $pkgnum",
800 =item cust_bill_batch
802 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
806 sub cust_bill_batch {
808 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
813 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
814 hash keyed by term length.
820 FS::discount_plan->all($self);
825 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
832 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
834 foreach (@taxlines) { $total += $_->setup; }
840 Returns the amount owed (still outstanding) on this invoice, which is charged
841 minus all payment applications (see L<FS::cust_bill_pay>) and credit
842 applications (see L<FS::cust_credit_bill>).
848 my $balance = $self->charged;
849 $balance -= $_->amount foreach ( $self->cust_bill_pay );
850 $balance -= $_->amount foreach ( $self->cust_credited );
851 $balance = sprintf( "%.2f", $balance);
852 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
857 my( $self, $pkgnum ) = @_;
859 #my $balance = $self->charged;
861 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
863 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
864 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
866 $balance = sprintf( "%.2f", $balance);
867 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
873 Returns true if this invoice should be hidden. See the
874 selfservice-hide_invoices-taxclass configuraiton setting.
880 my $conf = $self->conf;
881 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
883 my @cust_bill_pkg = $self->cust_bill_pkg;
884 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
885 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
888 =item apply_payments_and_credits [ OPTION => VALUE ... ]
890 Applies unapplied payments and credits to this invoice.
891 Payments with the no_auto_apply flag set will not be applied.
893 A hash of optional arguments may be passed. Currently "manual" is supported.
894 If true, a payment receipt is sent instead of a statement when
895 'payment_receipt_email' configuration option is set.
897 If there is an error, returns the error, otherwise returns false.
901 sub apply_payments_and_credits {
902 my( $self, %options ) = @_;
903 my $conf = $self->conf;
905 local $SIG{HUP} = 'IGNORE';
906 local $SIG{INT} = 'IGNORE';
907 local $SIG{QUIT} = 'IGNORE';
908 local $SIG{TERM} = 'IGNORE';
909 local $SIG{TSTP} = 'IGNORE';
910 local $SIG{PIPE} = 'IGNORE';
912 my $oldAutoCommit = $FS::UID::AutoCommit;
913 local $FS::UID::AutoCommit = 0;
916 $self->select_for_update; #mutex
918 my @payments = grep { $_->unapplied > 0 }
919 grep { !$_->no_auto_apply }
920 $self->cust_main->cust_pay;
921 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
923 if ( $conf->exists('pkg-balances') ) {
924 # limit @payments & @credits to those w/ a pkgnum grepped from $self
925 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
926 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
927 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
930 while ( $self->owed > 0 and ( @payments || @credits ) ) {
933 if ( @payments && @credits ) {
935 #decide which goes first by weight of top (unapplied) line item
937 my @open_lineitems = $self->open_cust_bill_pkg;
940 max( map { $_->part_pkg->pay_weight || 0 }
945 my $max_credit_weight =
946 max( map { $_->part_pkg->credit_weight || 0 }
952 #if both are the same... payments first? it has to be something
953 if ( $max_pay_weight >= $max_credit_weight ) {
959 } elsif ( @payments ) {
961 } elsif ( @credits ) {
964 die "guru meditation #12 and 35";
968 if ( $app eq 'pay' ) {
970 my $payment = shift @payments;
971 $unapp_amount = $payment->unapplied;
972 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
973 $app->pkgnum( $payment->pkgnum )
974 if $conf->exists('pkg-balances') && $payment->pkgnum;
976 } elsif ( $app eq 'credit' ) {
978 my $credit = shift @credits;
979 $unapp_amount = $credit->credited;
980 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
981 $app->pkgnum( $credit->pkgnum )
982 if $conf->exists('pkg-balances') && $credit->pkgnum;
985 die "guru meditation #12 and 35";
989 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
990 warn "owed_pkgnum ". $app->pkgnum;
991 $owed = $self->owed_pkgnum($app->pkgnum);
995 next unless $owed > 0;
997 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
998 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1000 $app->invnum( $self->invnum );
1002 my $error = $app->insert(%options);
1004 $dbh->rollback if $oldAutoCommit;
1005 return "Error inserting ". $app->table. " record: $error";
1007 die $error if $error;
1011 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1018 Sends this invoice to the destinations configured for this customer: sends
1019 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1021 Options can be passed as a hashref. Positional parameters are no longer
1024 I<template>: a suffix for alternate invoices
1026 I<agentnum>: obsolete, now does nothing.
1028 I<from> overrides the default email invoice From: address.
1030 I<amount>: obsolete, does nothing
1032 I<notice_name> overrides "Invoice" as the name of the sent document
1033 (templates from 10/2009 or newer required).
1035 I<lpr> overrides the system 'lpr' option as the command to print a document
1036 from standard input.
1042 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1043 my $conf = $self->conf;
1045 my $cust_main = $self->cust_main;
1047 my @invoicing_list = $cust_main->invoicing_list;
1050 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1051 && ! $cust_main->invoice_noemail;
1054 if grep { $_ eq 'POST' } @invoicing_list; #postal
1056 #this has never been used post-$ORIGINAL_ISP afaik
1057 $self->fax_invoice($opt)
1058 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1066 my $opt = shift || {};
1067 if ($opt and !ref($opt)) {
1068 die ref($self). '->email called with positional parameters';
1071 my $conf = $self->conf;
1073 my $from = delete $opt->{from};
1075 # this is where we set the From: address
1076 $from ||= $self->_agent_invoice_from || #XXX should go away
1077 $conf->invoice_from_full( $self->cust_main->agentnum );
1079 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1081 if ( ! @invoicing_list ) { #no recipients
1082 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1083 die 'No recipients for customer #'. $self->custnum;
1085 #default: better to notify this person than silence
1086 @invoicing_list = ($from);
1090 $self->SUPER::email( {
1092 'to' => \@invoicing_list,
1098 #this stays here for now because its explicitly used as
1099 # FS::cust_bill::queueable_email
1100 sub queueable_email {
1103 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1104 or die "invalid invoice number: " . $opt{invnum};
1107 $self->set('mode', $opt{mode});
1110 my %args = map {$_ => $opt{$_}}
1112 qw( from notice_name no_coupon template );
1114 my $error = $self->email( \%args );
1115 die $error if $error;
1121 my $conf = $self->conf;
1123 #my $template = scalar(@_) ? shift : '';
1126 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1129 my $cust_main = $self->cust_main;
1130 my $name = $cust_main->name;
1131 my $name_short = $cust_main->name_short;
1132 my $invoice_number = $self->invnum;
1133 my $invoice_date = $self->_date_pretty;
1135 eval qq("$subject");
1138 =item lpr_data HASHREF
1140 Returns the postscript or plaintext for this invoice as an arrayref.
1142 Options must be passed as a hashref. Positional parameters are no longer
1145 I<template>, if specified, is the name of a suffix for alternate invoices.
1147 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1153 my $conf = $self->conf;
1154 my $opt = shift || {};
1155 if ($opt and !ref($opt)) {
1156 # nobody does this anyway
1157 die "FS::cust_bill::lpr_data called with positional parameters";
1160 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1161 [ $self->$method( $opt ) ];
1166 Prints this invoice.
1168 Options must be passed as a hashref.
1170 I<template>, if specified, is the name of a suffix for alternate invoices.
1172 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1178 return if $self->hide;
1179 my $conf = $self->conf;
1180 my $opt = shift || {};
1181 if ($opt and !ref($opt)) {
1182 die "FS::cust_bill::print called with positional parameters";
1185 my $lpr = delete $opt->{lpr};
1186 if($conf->exists('invoice_print_pdf')) {
1187 # Add the invoice to the current batch.
1188 $self->batch_invoice($opt);
1192 $self->lpr_data($opt),
1193 'agentnum' => $self->cust_main->agentnum,
1199 =item fax_invoice HASHREF
1203 Options must be passed as a hashref.
1205 I<template>, if specified, is the name of a suffix for alternate invoices.
1207 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1213 return if $self->hide;
1214 my $conf = $self->conf;
1215 my $opt = shift || {};
1216 if ($opt and !ref($opt)) {
1217 die "FS::cust_bill::fax_invoice called with positional parameters";
1220 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1221 unless $conf->exists('invoice_latex');
1223 my $dialstring = $self->cust_main->getfield('fax');
1226 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1227 'dialstring' => $dialstring,
1229 die $error if $error;
1233 =item batch_invoice [ HASHREF ]
1235 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1236 isn't an open batch, one will be created.
1238 HASHREF may contain any options to be passed to C<print_pdf>.
1243 my ($self, $opt) = @_;
1244 my $bill_batch = $self->get_open_bill_batch;
1245 my $cust_bill_batch = FS::cust_bill_batch->new({
1246 batchnum => $bill_batch->batchnum,
1247 invnum => $self->invnum,
1249 return $cust_bill_batch->insert($opt);
1252 =item get_open_batch
1254 Returns the currently open batch as an FS::bill_batch object, creating a new
1255 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1260 sub get_open_bill_batch {
1262 my $conf = $self->conf;
1263 my $hashref = { status => 'O' };
1264 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1265 ? $self->cust_main->agentnum
1267 my $batch = qsearchs('bill_batch', $hashref);
1268 return $batch if $batch;
1269 $batch = FS::bill_batch->new($hashref);
1270 my $error = $batch->insert;
1271 die $error if $error;
1275 =item ftp_invoice [ TEMPLATENAME ]
1277 Sends this invoice data via FTP.
1279 TEMPLATENAME is unused?
1285 my $conf = $self->conf;
1286 my $template = scalar(@_) ? shift : '';
1289 'protocol' => 'ftp',
1290 'server' => $conf->config('cust_bill-ftpserver'),
1291 'username' => $conf->config('cust_bill-ftpusername'),
1292 'password' => $conf->config('cust_bill-ftppassword'),
1293 'dir' => $conf->config('cust_bill-ftpdir'),
1294 'format' => $conf->config('cust_bill-ftpformat'),
1298 =item spool_invoice [ TEMPLATENAME ]
1300 Spools this invoice data (see L<FS::spool_csv>)
1302 TEMPLATENAME is unused?
1308 my $conf = $self->conf;
1309 my $template = scalar(@_) ? shift : '';
1312 'format' => $conf->config('cust_bill-spoolformat'),
1313 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1317 =item send_csv OPTION => VALUE, ...
1319 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1323 protocol - currently only "ftp"
1329 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1330 and YYMMDDHHMMSS is a timestamp.
1332 See L</print_csv> for a description of the output format.
1337 my($self, %opt) = @_;
1341 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1342 mkdir $spooldir, 0700 unless -d $spooldir;
1344 # don't localize dates here, they're a defined format
1345 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1346 my $file = "$spooldir/$tracctnum.csv";
1348 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1350 open(CSV, ">$file") or die "can't open $file: $!";
1358 if ( $opt{protocol} eq 'ftp' ) {
1359 eval "use Net::FTP;";
1361 $net = Net::FTP->new($opt{server}) or die @$;
1363 die "unknown protocol: $opt{protocol}";
1366 $net->login( $opt{username}, $opt{password} )
1367 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1369 $net->binary or die "can't set binary mode";
1371 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1373 $net->put($file) or die "can't put $file: $!";
1383 Spools CSV invoice data.
1389 =item format - any of FS::Misc::::Invoicing::spool_formats
1391 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1392 customer has the corresponding invoice destinations set (see
1393 L<FS::cust_main_invoice>).
1395 =item agent_spools - if set to a true value, will spool to per-agent files
1396 rather than a single global file
1398 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1399 append to that spool. L<FS::Cron::upload> will then send the spool file to
1402 =item balanceover - if set, only spools the invoice if the total amount owed on
1403 this invoice and all older invoices is greater than the specified amount.
1405 =item time - the "current time". Controls the printing of past due messages
1413 my($self, %opt) = @_;
1415 my $time = $opt{'time'} || time;
1416 my $cust_main = $self->cust_main;
1418 if ( $opt{'dest'} ) {
1419 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1420 $cust_main->invoicing_list;
1421 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1422 || ! keys %invoicing_list;
1425 if ( $opt{'balanceover'} ) {
1427 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1430 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1431 mkdir $spooldir, 0700 unless -d $spooldir;
1433 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1436 if ( $opt{'agent_spools'} ) {
1437 $file = 'agentnum'.$cust_main->agentnum;
1442 if ( $opt{'upload_targetnum'} ) {
1443 $spooldir .= '/target'.$opt{'upload_targetnum'};
1444 mkdir $spooldir, 0700 unless -d $spooldir;
1445 } # otherwise it just goes into export.xxx/cust_bill
1447 if ( lc($opt{'format'}) eq 'billco' ) {
1451 $file = "$spooldir/$file.csv";
1453 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1455 open(CSV, ">>$file") or die "can't open $file: $!";
1456 flock(CSV, LOCK_EX);
1461 if ( lc($opt{'format'}) eq 'billco' ) {
1463 flock(CSV, LOCK_UN);
1466 $file =~ s/-header.csv$/-detail.csv/;
1468 open(CSV,">>$file") or die "can't open $file: $!";
1469 flock(CSV, LOCK_EX);
1473 print CSV $detail if defined($detail);
1475 flock(CSV, LOCK_UN);
1482 =item print_csv OPTION => VALUE, ...
1484 Returns CSV data for this invoice.
1488 format - 'default', 'billco', 'oneline', 'bridgestone'
1490 Returns a list consisting of two scalars. The first is a single line of CSV
1491 header information for this invoice. The second is one or more lines of CSV
1492 detail information for this invoice.
1494 If I<format> is not specified or "default", the fields of the CSV file are as
1497 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1498 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1502 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1504 B<record_type> is C<cust_bill> for the initial header line only. The
1505 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1506 fields are filled in.
1508 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1509 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1512 =item invnum - invoice number
1514 =item custnum - customer number
1516 =item _date - invoice date
1518 =item charged - total invoice amount
1520 =item first - customer first name
1522 =item last - customer first name
1524 =item company - company name
1526 =item address1 - address line 1
1528 =item address2 - address line 1
1538 =item pkg - line item description
1540 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1542 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1544 =item sdate - start date for recurring fee
1546 =item edate - end date for recurring fee
1550 If I<format> is "billco", the fields of the header CSV file are as follows:
1552 +-------------------------------------------------------------------+
1553 | FORMAT HEADER FILE |
1554 |-------------------------------------------------------------------|
1555 | Field | Description | Name | Type | Width |
1556 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1557 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1558 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1559 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1560 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1561 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1562 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1563 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1564 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1565 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1566 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1567 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1568 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1569 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1570 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1571 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1572 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1573 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1574 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1575 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1576 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1577 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1578 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1579 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1580 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1581 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1582 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1583 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1584 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1585 +-------+-------------------------------+------------+------+-------+
1587 If I<format> is "billco", the fields of the detail CSV file are as follows:
1589 FORMAT FOR DETAIL FILE
1591 Field | Description | Name | Type | Width
1592 1 | N/A-Leave Empty | RC | CHAR | 2
1593 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1594 3 | Account Number | TRACCTNUM | CHAR | 15
1595 4 | Invoice Number | TRINVOICE | CHAR | 15
1596 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1597 6 | Transaction Detail | DETAILS | CHAR | 100
1598 7 | Amount | AMT | NUM* | 9
1599 8 | Line Format Control** | LNCTRL | CHAR | 2
1600 9 | Grouping Code | GROUP | CHAR | 2
1601 10 | User Defined | ACCT CODE | CHAR | 15
1603 If format is 'oneline', there is no detail file. Each invoice has a
1604 header line only, with the fields:
1606 Agent number, agent name, customer number, first name, last name, address
1607 line 1, address line 2, city, state, zip, invoice date, invoice number,
1608 amount charged, amount due, previous balance, due date.
1610 and then, for each line item, three columns containing the package number,
1611 description, and amount.
1613 If format is 'bridgestone', there is no detail file. Each invoice has a
1614 header line with the following fields in a fixed-width format:
1616 Customer number (in display format), date, name (first last), company,
1617 address 1, address 2, city, state, zip.
1619 This is a mailing list format, and has no per-invoice fields. To avoid
1620 sending redundant notices, the spooling event should have a "once" or
1621 "once_percust_every" condition.
1626 my($self, %opt) = @_;
1628 eval "use Text::CSV_XS";
1631 my $cust_main = $self->cust_main;
1633 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1634 my $format = lc($opt{'format'});
1636 my $time = $opt{'time'} || time;
1638 my $tracctnum = ''; #leaking out from billco-specific sections :/
1639 if ( $format eq 'billco' ) {
1642 $self->conf->config('billco-account_num', $cust_main->agentnum);
1644 $tracctnum = $account_num eq 'display_custnum'
1645 ? $cust_main->display_custnum
1646 : $opt{'tracctnum'};
1649 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1651 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1653 my( $previous_balance, @unused ) = $self->previous; #previous balance
1655 my $pmt_cr_applied = 0;
1656 $pmt_cr_applied += $_->{'amount'}
1657 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1659 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1662 '', # 1 | N/A-Leave Empty CHAR 2
1663 '', # 2 | N/A-Leave Empty CHAR 15
1664 $tracctnum, # 3 | Transaction Account No CHAR 15
1665 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1666 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1667 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1668 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1669 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1670 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1671 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1672 '', # 10 | Ancillary Billing Information CHAR 30
1673 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1674 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1677 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1680 $duedate, # 14 | Bill Due Date CHAR 10
1682 $previous_balance, # 15 | Previous Balance NUM* 9
1683 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1684 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1685 $totaldue, # 18 | Total Amt Due NUM* 9
1686 $totaldue, # 19 | Total Amt Due NUM* 9
1687 '', # 20 | 30 Day Aging NUM* 9
1688 '', # 21 | 60 Day Aging NUM* 9
1689 '', # 22 | 90 Day Aging NUM* 9
1690 'N', # 23 | Y/N CHAR 1
1691 '', # 24 | Remittance automation CHAR 100
1692 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1693 $self->custnum, # 26 | Customer Reference Number CHAR 15
1694 '0', # 27 | Federal Tax*** NUM* 9
1695 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1696 '0', # 29 | Other Taxes & Fees*** NUM* 9
1699 } elsif ( $format eq 'oneline' ) { #name
1701 my ($previous_balance) = $self->previous;
1702 $previous_balance = sprintf('%.2f', $previous_balance);
1703 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1709 $self->_items_pkg, #_items_nontax? no sections or anything
1714 $cust_main->agentnum,
1715 $cust_main->agent->agent,
1719 $cust_main->company,
1720 $cust_main->address1,
1721 $cust_main->address2,
1727 time2str("%x", $self->_date),
1732 $self->due_date2str("%x"),
1737 } elsif ( $format eq 'bridgestone' ) {
1739 # bypass the CSV stuff and just return this
1740 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1741 my $zip = $cust_main->zip;
1743 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1747 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1749 $cust_main->display_custnum,
1751 uc(substr($cust_main->contact_firstlast,0,30)),
1752 uc(substr($cust_main->company ,0,30)),
1753 uc(substr($cust_main->address1 ,0,30)),
1754 uc(substr($cust_main->address2 ,0,30)),
1755 uc(substr($cust_main->city ,0,20)),
1756 uc($cust_main->state),
1762 } elsif ( $format eq 'ics' ) {
1764 my $bill = $cust_main->bill_location;
1765 my $zip = $bill->zip;
1769 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1774 # minor false laziness with print_generic
1775 my ($previous_balance) = $self->previous;
1776 my $balance_due = $self->owed + $previous_balance;
1777 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1778 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1781 if ( $self->due_date and $time >= $self->due_date ) {
1782 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1786 my $header = sprintf(
1787 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1788 $cust_main->display_custnum, #BID
1789 uc($cust_main->first), #FNAME
1790 uc($cust_main->last), #LNAME
1791 '00', #BATCH, should this ever be anything else?
1792 uc($cust_main->company), #COMP
1793 uc($bill->address1), #STREET1
1794 uc($bill->address2), #STREET2
1795 uc($bill->city), #CITY
1796 uc($bill->state), #STATE
1799 time2str('%Y%m%d', $self->_date), #BILL_DATE
1800 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1801 ( map {sprintf('%0.2f', $_)}
1802 $balance_due, #AMNT_DUE
1803 $previous_balance, #PREV_BAL
1804 $payment_total, #PYMT_RCVD
1805 $credit_total, #CREDITS
1806 $previous_balance, #BEG_BAL--is this correct?
1807 $self->charged, #NEW_CHRG
1810 $past_due, #PAST_MSG
1814 my %svc_class = ('' => ''); # maybe cache this more persistently?
1816 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1818 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1819 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1823 my @dates = ( $self->_date, undef );
1824 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1825 $dates[1] = $prev->sdate; #questionable
1828 # generate an 01 detail for each service
1829 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1830 foreach my $cust_svc ( @svcs ) {
1831 $show_pkgnum = ''; # hide it if we're showing svcnums
1833 my $svcpart = $cust_svc->svcpart;
1834 if (!exists($svc_class{$svcpart})) {
1835 my $classnum = $cust_svc->part_svc->classnum;
1836 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1838 $svc_class{$svcpart} = $part_svc_class ?
1839 $part_svc_class->classname :
1843 my @h_label = $cust_svc->label(@dates, 'I');
1844 push @details, sprintf('01%-9s%-20s%-47s',
1846 $svc_class{$svcpart},
1849 } #foreach $cust_svc
1852 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1853 if ($cust_bill_pkg->recur > 0) {
1854 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1855 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1857 push @details, sprintf('02%-6s%-60s%-10s',
1860 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1862 } #foreach $cust_bill_pkg
1864 # Tag this row so that we know whether this is one page (1), two pages
1865 # (2), # or "big" (B). The tag will be stripped off before uploading.
1866 if ( scalar(@details) < 12 ) {
1868 } elsif ( scalar(@details) < 58 ) {
1874 return join('', $header, @details, "\n");
1882 time2str("%x", $self->_date),
1883 sprintf("%.2f", $self->charged),
1884 ( map { $cust_main->getfield($_) }
1885 qw( first last company address1 address2 city state zip country ) ),
1887 ) or die "can't create csv";
1890 my $header = $csv->string. "\n";
1893 if ( lc($opt{'format'}) eq 'billco' ) {
1896 my %items_opt = ( format => 'template',
1897 escape_function => sub { shift } );
1898 # I don't know what characters billco actually tolerates in spool entries.
1899 # Text::CSV will take care of delimiters, though.
1901 my @items = ( $self->_items_pkg(%items_opt),
1902 $self->_items_fee(%items_opt) );
1903 foreach my $item (@items) {
1905 my $description = $item->{'description'};
1906 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1907 $description .= ': ' . $item->{ext_description}[0];
1911 '', # 1 | N/A-Leave Empty CHAR 2
1912 '', # 2 | N/A-Leave Empty CHAR 15
1913 $tracctnum, # 3 | Account Number CHAR 15
1914 $self->invnum, # 4 | Invoice Number CHAR 15
1915 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1916 $description, # 6 | Transaction Detail CHAR 100
1917 $item->{'amount'}, # 7 | Amount NUM* 9
1918 '', # 8 | Line Format Control** CHAR 2
1919 '', # 9 | Grouping Code CHAR 2
1920 '', # 10 | User Defined CHAR 15
1923 $detail .= $csv->string. "\n";
1927 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1933 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1935 my($pkg, $setup, $recur, $sdate, $edate);
1936 if ( $cust_bill_pkg->pkgnum ) {
1938 ($pkg, $setup, $recur, $sdate, $edate) = (
1939 $cust_bill_pkg->part_pkg->pkg,
1940 ( $cust_bill_pkg->setup != 0
1941 ? sprintf("%.2f", $cust_bill_pkg->setup )
1943 ( $cust_bill_pkg->recur != 0
1944 ? sprintf("%.2f", $cust_bill_pkg->recur )
1946 ( $cust_bill_pkg->sdate
1947 ? time2str("%x", $cust_bill_pkg->sdate)
1949 ($cust_bill_pkg->edate
1950 ? time2str("%x", $cust_bill_pkg->edate)
1954 } else { #pkgnum tax
1955 next unless $cust_bill_pkg->setup != 0;
1956 $pkg = $cust_bill_pkg->desc;
1957 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1958 ( $sdate, $edate ) = ( '', '' );
1964 ( map { '' } (1..11) ),
1965 ($pkg, $setup, $recur, $sdate, $edate)
1966 ) or die "can't create csv";
1968 $detail .= $csv->string. "\n";
1974 ( $header, $detail );
1979 croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
1984 Attempts to pay this invoice with a credit card payment via a
1985 Business::OnlinePayment realtime gateway. See
1986 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1987 for supported processors.
1993 $self->realtime_bop( 'CC', @_ );
1998 Attempts to pay this invoice with an electronic check (ACH) payment via a
1999 Business::OnlinePayment realtime gateway. See
2000 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2001 for supported processors.
2007 $self->realtime_bop( 'ECHECK', @_ );
2012 Attempts to pay this invoice with phone bill (LEC) payment via a
2013 Business::OnlinePayment realtime gateway. See
2014 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2015 for supported processors.
2021 $self->realtime_bop( 'LEC', @_ );
2025 my( $self, $method ) = (shift,shift);
2026 my $conf = $self->conf;
2029 my $cust_main = $self->cust_main;
2030 my $balance = $cust_main->balance;
2031 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2032 $amount = sprintf("%.2f", $amount);
2033 return "not run (balance $balance)" unless $amount > 0;
2035 my $description = 'Internet Services';
2036 if ( $conf->exists('business-onlinepayment-description') ) {
2037 my $dtempl = $conf->config('business-onlinepayment-description');
2039 my $agent_obj = $cust_main->agent
2040 or die "can't retreive agent for $cust_main (agentnum ".
2041 $cust_main->agentnum. ")";
2042 my $agent = $agent_obj->agent;
2043 my $pkgs = join(', ',
2044 map { $_->part_pkg->pkg }
2045 grep { $_->pkgnum } $self->cust_bill_pkg
2047 $description = eval qq("$dtempl");
2050 $cust_main->realtime_bop($method, $amount,
2051 'description' => $description,
2052 'invnum' => $self->invnum,
2053 #this didn't do what we want, it just calls apply_payments_and_credits
2055 'apply_to_invoice' => 1,
2058 #this changes application behavior: auto payments
2059 #triggered against a specific invoice are now applied
2060 #to that invoice instead of oldest open.
2066 =item batch_card OPTION => VALUE...
2068 Adds a payment for this invoice to the pending credit card batch (see
2069 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2070 runs the payment using a realtime gateway.
2075 my ($self, %options) = @_;
2076 my $cust_main = $self->cust_main;
2078 $options{invnum} = $self->invnum;
2080 $cust_main->batch_card(%options);
2083 sub _agent_template {
2085 $self->cust_main->agent_template;
2088 sub _agent_invoice_from {
2090 $self->cust_main->agent_invoice_from;
2093 =item invoice_barcode DIR_OR_FALSE
2095 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2096 it is taken as the temp directory where the PNG file will be generated and the
2097 PNG file name is returned. Otherwise, the PNG image itself is returned.
2101 sub invoice_barcode {
2102 my ($self, $dir) = (shift,shift);
2104 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2105 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2106 my $gd = $gdbar->plot(Height => 30);
2109 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2113 ) or die "can't open temp file: $!\n";
2114 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2115 my $png_file = $bh->filename;
2122 =item invnum_date_pretty
2124 Returns a string with the invoice number and date, for example:
2125 "Invoice #54 (3/20/2008)".
2127 Intended for back-end context, with regard to translation and date formatting.
2131 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2132 # for backend use (and also does the wrong thing, localizing for end customer
2133 # instead of backoffice configured date format)
2134 sub invnum_date_pretty {
2136 #$self->mt('Invoice #').
2137 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2138 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2141 #sub _items_extra_usage_sections {
2143 # my $escape = shift;
2145 # my %sections = ();
2147 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2148 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2150 # next unless $cust_bill_pkg->pkgnum > 0;
2152 # foreach my $section ( keys %usage_class ) {
2154 # my $usage = $cust_bill_pkg->usage($section);
2156 # next unless $usage && $usage > 0;
2158 # $sections{$section} ||= 0;
2159 # $sections{$section} += $usage;
2165 # map { { 'description' => &{$escape}($_),
2166 # 'subtotal' => $sections{$_},
2167 # 'summarized' => '',
2168 # 'tax_section' => '',
2171 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2175 sub _items_extra_usage_sections {
2177 my $conf = $self->conf;
2185 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2187 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2188 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2189 next unless $cust_bill_pkg->pkgnum > 0;
2191 foreach my $classnum ( keys %usage_class ) {
2192 my $section = $usage_class{$classnum}->classname;
2193 $classnums{$section} = $classnum;
2195 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2196 my $amount = $detail->amount;
2197 next unless $amount && $amount > 0;
2199 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2200 $sections{$section}{amount} += $amount; #subtotal
2201 $sections{$section}{calls}++;
2202 $sections{$section}{duration} += $detail->duration;
2204 my $desc = $detail->regionname;
2205 my $description = $desc;
2206 $description = substr($desc, 0, $maxlength). '...'
2207 if $format eq 'latex' && length($desc) > $maxlength;
2209 $lines{$section}{$desc} ||= {
2210 description => &{$escape}($description),
2211 #pkgpart => $part_pkg->pkgpart,
2212 pkgnum => $cust_bill_pkg->pkgnum,
2217 #unit_amount => $cust_bill_pkg->unitrecur,
2218 quantity => $cust_bill_pkg->quantity,
2219 product_code => 'N/A',
2220 ext_description => [],
2223 $lines{$section}{$desc}{amount} += $amount;
2224 $lines{$section}{$desc}{calls}++;
2225 $lines{$section}{$desc}{duration} += $detail->duration;
2231 my %sectionmap = ();
2232 foreach (keys %sections) {
2233 my $usage_class = $usage_class{$classnums{$_}};
2234 $sectionmap{$_} = { 'description' => &{$escape}($_),
2235 'amount' => $sections{$_}{amount}, #subtotal
2236 'calls' => $sections{$_}{calls},
2237 'duration' => $sections{$_}{duration},
2239 'tax_section' => '',
2240 'sort_weight' => $usage_class->weight,
2241 ( $usage_class->format
2242 ? ( map { $_ => $usage_class->$_($format) }
2243 qw( description_generator header_generator total_generator total_line_generator )
2250 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2254 foreach my $section ( keys %lines ) {
2255 foreach my $line ( keys %{$lines{$section}} ) {
2256 my $l = $lines{$section}{$line};
2257 $l->{section} = $sectionmap{$section};
2258 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2259 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2264 return(\@sections, \@lines);
2270 my $end = $self->_date;
2272 # start at date of previous invoice + 1 second or 0 if no previous invoice
2273 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2274 $start = 0 if !$start;
2277 my $cust_main = $self->cust_main;
2278 my @pkgs = $cust_main->all_pkgs;
2279 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2282 foreach my $pkg ( @pkgs ) {
2283 my @h_cust_svc = $pkg->h_cust_svc($end);
2284 foreach my $h_cust_svc ( @h_cust_svc ) {
2285 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2286 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2288 my $inserted = $h_cust_svc->date_inserted;
2289 my $deleted = $h_cust_svc->date_deleted;
2290 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2292 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2294 # DID either activated or ported in; cannot be both for same DID simultaneously
2295 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2296 && (!$phone_inserted->lnp_status
2297 || $phone_inserted->lnp_status eq ''
2298 || $phone_inserted->lnp_status eq 'native')) {
2301 else { # this one not so clean, should probably move to (h_)svc_phone
2302 local($FS::Record::qsearch_qualify_columns) = 0;
2303 my $phone_portedin = qsearchs( 'h_svc_phone',
2304 { 'svcnum' => $h_cust_svc->svcnum,
2305 'lnp_status' => 'portedin' },
2306 FS::h_svc_phone->sql_h_searchs($end),
2308 $num_portedin++ if $phone_portedin;
2311 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2312 if($deleted >= $start && $deleted <= $end && $phone_deleted
2313 && (!$phone_deleted->lnp_status
2314 || $phone_deleted->lnp_status ne 'portingout')) {
2317 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2318 && $phone_deleted->lnp_status
2319 && $phone_deleted->lnp_status eq 'portingout') {
2323 # increment usage minutes
2324 if ( $phone_inserted ) {
2325 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2326 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2329 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2332 # don't look at this service again
2333 push @seen, $h_cust_svc->svcnum;
2337 $minutes = sprintf("%d", $minutes);
2338 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2339 . "$num_deactivated Ported-Out: $num_portedout ",
2340 "Total Minutes: $minutes");
2343 sub _items_accountcode_cdr {
2348 my $section = { 'amount' => 0,
2351 'sort_weight' => '',
2353 'description' => 'Usage by Account Code',
2359 my %accountcodes = ();
2361 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2362 next unless $cust_bill_pkg->pkgnum > 0;
2364 my @header = $cust_bill_pkg->details_header;
2365 next unless scalar(@header);
2366 $section->{'header'} = join(',',@header);
2368 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2370 $section->{'header'} = $detail->formatted('format' => $format)
2371 if($detail->detail eq $section->{'header'});
2373 my $accountcode = $detail->accountcode;
2374 next unless $accountcode;
2376 my $amount = $detail->amount;
2377 next unless $amount && $amount > 0;
2379 $accountcodes{$accountcode} ||= {
2380 description => $accountcode,
2387 product_code => 'N/A',
2388 section => $section,
2389 ext_description => [ $section->{'header'} ],
2393 $section->{'amount'} += $amount;
2394 $accountcodes{$accountcode}{'amount'} += $amount;
2395 $accountcodes{$accountcode}{calls}++;
2396 $accountcodes{$accountcode}{duration} += $detail->duration;
2397 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2401 foreach my $l ( values %accountcodes ) {
2402 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2403 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2404 foreach my $sorted_detail ( @sorted_detail ) {
2405 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2407 delete $l->{detail_temp};
2411 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2413 return ($section,\@sorted_lines);
2416 sub _items_svc_phone_sections {
2418 my $conf = $self->conf;
2426 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2428 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2429 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2431 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2432 next unless $cust_bill_pkg->pkgnum > 0;
2434 my @header = $cust_bill_pkg->details_header;
2435 next unless scalar(@header);
2437 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2439 my $phonenum = $detail->phonenum;
2440 next unless $phonenum;
2442 my $amount = $detail->amount;
2443 next unless $amount && $amount > 0;
2445 $sections{$phonenum} ||= { 'amount' => 0,
2448 'sort_weight' => -1,
2449 'phonenum' => $phonenum,
2451 $sections{$phonenum}{amount} += $amount; #subtotal
2452 $sections{$phonenum}{calls}++;
2453 $sections{$phonenum}{duration} += $detail->duration;
2455 my $desc = $detail->regionname;
2456 my $description = $desc;
2457 $description = substr($desc, 0, $maxlength). '...'
2458 if $format eq 'latex' && length($desc) > $maxlength;
2460 $lines{$phonenum}{$desc} ||= {
2461 description => &{$escape}($description),
2462 #pkgpart => $part_pkg->pkgpart,
2470 product_code => 'N/A',
2471 ext_description => [],
2474 $lines{$phonenum}{$desc}{amount} += $amount;
2475 $lines{$phonenum}{$desc}{calls}++;
2476 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2478 my $line = $usage_class{$detail->classnum}->classname;
2479 $sections{"$phonenum $line"} ||=
2483 'sort_weight' => $usage_class{$detail->classnum}->weight,
2484 'phonenum' => $phonenum,
2485 'header' => [ @header ],
2487 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2488 $sections{"$phonenum $line"}{calls}++;
2489 $sections{"$phonenum $line"}{duration} += $detail->duration;
2491 $lines{"$phonenum $line"}{$desc} ||= {
2492 description => &{$escape}($description),
2493 #pkgpart => $part_pkg->pkgpart,
2501 product_code => 'N/A',
2502 ext_description => [],
2505 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2506 $lines{"$phonenum $line"}{$desc}{calls}++;
2507 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2508 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2509 $detail->formatted('format' => $format);
2514 my %sectionmap = ();
2515 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2516 foreach ( keys %sections ) {
2517 my @header = @{ $sections{$_}{header} || [] };
2519 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2520 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2521 my $usage_class = $summary ? $simple : $usage_simple;
2522 my $ending = $summary ? ' usage charges' : '';
2525 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2527 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2528 'amount' => $sections{$_}{amount}, #subtotal
2529 'calls' => $sections{$_}{calls},
2530 'duration' => $sections{$_}{duration},
2532 'tax_section' => '',
2533 'phonenum' => $sections{$_}{phonenum},
2534 'sort_weight' => $sections{$_}{sort_weight},
2535 'post_total' => $summary, #inspire pagebreak
2537 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2538 qw( description_generator
2541 total_line_generator
2548 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2549 $a->{sort_weight} <=> $b->{sort_weight}
2554 foreach my $section ( keys %lines ) {
2555 foreach my $line ( keys %{$lines{$section}} ) {
2556 my $l = $lines{$section}{$line};
2557 $l->{section} = $sectionmap{$section};
2558 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2559 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2564 if($conf->exists('phone_usage_class_summary')) {
2565 # this only works with Latex
2569 # after this, we'll have only two sections per DID:
2570 # Calls Summary and Calls Detail
2571 foreach my $section ( @sections ) {
2572 if($section->{'post_total'}) {
2573 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2574 $section->{'total_line_generator'} = sub { '' };
2575 $section->{'total_generator'} = sub { '' };
2576 $section->{'header_generator'} = sub { '' };
2577 $section->{'description_generator'} = '';
2578 push @newsections, $section;
2579 my %calls_detail = %$section;
2580 $calls_detail{'post_total'} = '';
2581 $calls_detail{'sort_weight'} = '';
2582 $calls_detail{'description_generator'} = sub { '' };
2583 $calls_detail{'header_generator'} = sub {
2584 return ' & Date/Time & Called Number & Duration & Price'
2585 if $format eq 'latex';
2588 $calls_detail{'description'} = 'Calls Detail: '
2589 . $section->{'phonenum'};
2590 push @newsections, \%calls_detail;
2594 # after this, each usage class is collapsed/summarized into a single
2595 # line under the Calls Summary section
2596 foreach my $newsection ( @newsections ) {
2597 if($newsection->{'post_total'}) { # this means Calls Summary
2598 foreach my $section ( @sections ) {
2599 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2600 && !$section->{'post_total'});
2601 my $newdesc = $section->{'description'};
2602 my $tn = $section->{'phonenum'};
2603 $newdesc =~ s/$tn//g;
2604 my $line = { ext_description => [],
2608 calls => $section->{'calls'},
2609 section => $newsection,
2610 duration => $section->{'duration'},
2611 description => $newdesc,
2612 amount => sprintf("%.2f",$section->{'amount'}),
2613 product_code => 'N/A',
2615 push @newlines, $line;
2620 # after this, Calls Details is populated with all CDRs
2621 foreach my $newsection ( @newsections ) {
2622 if(!$newsection->{'post_total'}) { # this means Calls Details
2623 foreach my $line ( @lines ) {
2624 next unless (scalar(@{$line->{'ext_description'}}) &&
2625 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2627 my @extdesc = @{$line->{'ext_description'}};
2629 foreach my $extdesc ( @extdesc ) {
2630 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2631 push @newextdesc, $extdesc;
2633 $line->{'ext_description'} = \@newextdesc;
2634 $line->{'section'} = $newsection;
2635 push @newlines, $line;
2640 return(\@newsections, \@newlines);
2643 return(\@sections, \@lines);
2647 =sub _items_usage_class_summary OPTIONS
2649 Returns a list of detail items summarizing the usage charges on this
2650 invoice. Each one will have 'amount', 'description' (the usage charge name),
2651 and 'usage_classnum'.
2653 OPTIONS can include 'escape' (a function to escape the descriptions).
2657 sub _items_usage_class_summary {
2661 my $escape = $opt{escape} || sub { $_[0] };
2662 my $invnum = $self->invnum;
2663 my @classes = qsearch({
2664 'table' => 'usage_class',
2665 'select' => 'classnum, classname, SUM(amount) AS amount',
2666 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2667 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2668 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2669 ' GROUP BY classnum, classname, weight'.
2670 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2671 ' ORDER BY weight ASC',
2675 description => &{$escape}($self->mt('Usage Summary')),
2679 foreach my $class (@classes) {
2681 'description' => &{$escape}($class->classname),
2682 'amount' => sprintf('%.2f', $class->amount),
2683 'usage_classnum' => $class->classnum,
2684 'section' => $section,
2690 sub _items_previous {
2692 my $conf = $self->conf;
2693 my $cust_main = $self->cust_main;
2694 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2696 foreach ( @pr_cust_bill ) {
2697 my $date = $conf->exists('invoice_show_prior_due_date')
2698 ? 'due '. $_->due_date2str('short')
2699 : $self->time2str_local('short', $_->_date);
2701 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2702 #'pkgpart' => 'N/A',
2704 'amount' => sprintf("%.2f", $_->owed),
2710 # 'description' => 'Previous Balance',
2711 # #'pkgpart' => 'N/A',
2712 # 'pkgnum' => 'N/A',
2713 # 'amount' => sprintf("%10.2f", $pr_total ),
2714 # 'ext_description' => [ map {
2715 # "Invoice ". $_->invnum.
2716 # " (". time2str("%x",$_->_date). ") ".
2717 # sprintf("%10.2f", $_->owed)
2718 # } @pr_cust_bill ],
2723 sub _items_credits {
2724 my( $self, %opt ) = @_;
2725 my $trim_len = $opt{'trim_len'} || 40;
2730 if ( $self->conf->exists('previous_balance-payments_since') ) {
2731 if ( $opt{'template'} eq 'statement' ) {
2732 # then the current bill is a "statement" (i.e. an invoice sent as
2733 # a payment receipt)
2734 # and in that case we want to see payments on or after THIS invoice
2735 @objects = qsearch('cust_credit', {
2736 'custnum' => $self->custnum,
2737 '_date' => {op => '>=', value => $self->_date},
2741 $date = $self->previous_bill->_date if $self->previous_bill;
2742 @objects = qsearch('cust_credit', {
2743 'custnum' => $self->custnum,
2744 '_date' => {op => '>=', value => $date},
2748 @objects = $self->cust_credited;
2751 foreach my $obj ( @objects ) {
2752 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2754 my $reason = substr($cust_credit->reason, 0, $trim_len);
2755 $reason .= '...' if length($reason) < length($cust_credit->reason);
2756 $reason = " ($reason) " if $reason;
2759 #'description' => 'Credit ref\#'. $_->crednum.
2760 # " (". time2str("%x",$_->cust_credit->_date) .")".
2762 'description' => $self->mt('Credit applied').' '.
2763 $self->time2str_local('short', $obj->_date). $reason,
2764 'amount' => sprintf("%.2f",$obj->amount),
2772 sub _items_payments {
2777 my $detailed = $self->conf->exists('invoice_payment_details');
2779 if ( $self->conf->exists('previous_balance-payments_since') ) {
2780 # then show payments dated on/after the previous bill...
2781 if ( $opt{'template'} eq 'statement' ) {
2782 # then the current bill is a "statement" (i.e. an invoice sent as
2783 # a payment receipt)
2784 # and in that case we want to see payments on or after THIS invoice
2785 @objects = qsearch('cust_pay', {
2786 'custnum' => $self->custnum,
2787 '_date' => {op => '>=', value => $self->_date},
2790 # the normal case: payments on or after the previous invoice
2792 $date = $self->previous_bill->_date if $self->previous_bill;
2793 @objects = qsearch('cust_pay', {
2794 'custnum' => $self->custnum,
2795 '_date' => {op => '>=', value => $date},
2797 # and before the current bill...
2798 @objects = grep { $_->_date < $self->_date } @objects;
2801 @objects = $self->cust_bill_pay;
2804 foreach my $obj (@objects) {
2805 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2806 my $desc = $self->mt('Payment received').' '.
2807 $self->time2str_local('short', $cust_pay->_date );
2808 $desc .= $self->mt(' via ') .
2809 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2813 'description' => $desc,
2814 'amount' => sprintf("%.2f", $obj->amount )
2824 my $conf = $self->conf;
2827 my ($pr_total) = $self->previous;
2828 my ($previous_charges_desc, $new_charges_desc, $new_charges_amount);
2830 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2831 # can we do some caching on this stuff? it's going to change infrequently
2833 $previous_charges_desc = $self->mt(
2834 $conf->config('previous_balance-text') || 'Previous Balance'
2837 # then return separate lines for previous balance and total new charges
2840 { total_item => $previous_charges_desc,
2841 total_amount => sprintf('%.2f',$pr_total)
2844 $new_charges_desc = $self->mt(
2845 $conf->config('previous_balance-text-total_new_charges')
2846 || 'Total New Charges'
2849 $new_charges_amount = $self->charged;
2853 $new_charges_desc = $self->mt('Total Charges');
2854 $new_charges_amount = sprintf('%.2f',$self->charged + $pr_total);
2858 if ( $conf->exists('invoice_show_prior_due_date') ) {
2859 # then the due date should be shown with Total New Charges,
2860 # and should NOT be shown with the Balance Due message.
2861 if ( $self->due_date ) {
2862 # localize the "Please pay by" message and the date itself
2863 # (grammar issues with this, yeah)
2864 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2865 $self->due_date2str('short');
2866 } elsif ( $self->terms ) {
2867 # phrases like "due on receipt" should be localized
2868 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2873 { total_item => $new_charges_desc,
2874 total_amount => $new_charges_amount,
2882 =item call_details [ OPTION => VALUE ... ]
2884 Returns an array of CSV strings representing the call details for this invoice
2885 The only option available is the boolean prepend_billed_number
2890 my ($self, %opt) = @_;
2892 my $format_function = sub { shift };
2894 if ($opt{prepend_billed_number}) {
2895 $format_function = sub {
2899 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2904 my @details = map { $_->details( 'format_function' => $format_function,
2905 'escape_function' => sub{ return() },
2909 $self->cust_bill_pkg;
2910 my $header = $details[0];
2911 ( $header, grep { $_ ne $header } @details );
2921 =item process_reprint
2925 sub process_reprint {
2926 process_re_X('print', @_);
2929 =item process_reemail
2933 sub process_reemail {
2934 process_re_X('email', @_);
2942 process_re_X('fax', @_);
2950 process_re_X('ftp', @_);
2957 sub process_respool {
2958 process_re_X('spool', @_);
2963 my( $method, $job ) = ( shift, shift );
2964 warn "$me process_re_X $method for job $job\n" if $DEBUG;
2967 warn Dumper($param) if $DEBUG;
2978 # spool_invoice ftp_invoice fax_invoice print_invoice
2979 my($method, $job, %param ) = @_;
2981 warn "re_X $method for job $job with param:\n".
2982 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
2985 #some false laziness w/search/cust_bill.html
2987 my $orderby = 'ORDER BY cust_bill._date';
2989 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
2991 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
2993 my @cust_bill = qsearch( {
2994 #'select' => "cust_bill.*",
2995 'table' => 'cust_bill',
2996 'addl_from' => $addl_from,
2998 'extra_sql' => $extra_sql,
2999 'order_by' => $orderby,
3003 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3005 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3008 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3009 foreach my $cust_bill ( @cust_bill ) {
3010 $cust_bill->$method();
3012 if ( $job ) { #progressbar foo
3014 if ( time - $min_sec > $last ) {
3015 my $error = $job->update_statustext(
3016 int( 100 * $num / scalar(@cust_bill) )
3018 die $error if $error;
3029 +{ ( map { $_=>$self->$_ } $self->fields ),
3030 'owed' => $self->owed,
3031 #XXX last payment applied date
3037 =head1 CLASS METHODS
3043 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3048 my ($class, $start, $end) = @_;
3050 $class->paid_sql($start, $end). ' - '.
3051 $class->credited_sql($start, $end);
3056 Returns an SQL fragment to retreive the net amount (charged minus credited).
3061 my ($class, $start, $end) = @_;
3062 'charged - '. $class->credited_sql($start, $end);
3067 Returns an SQL fragment to retreive the amount paid against this invoice.
3072 my ($class, $start, $end) = @_;
3073 $start &&= "AND cust_bill_pay._date <= $start";
3074 $end &&= "AND cust_bill_pay._date > $end";
3075 $start = '' unless defined($start);
3076 $end = '' unless defined($end);
3077 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3078 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3083 Returns an SQL fragment to retreive the amount credited against this invoice.
3088 my ($class, $start, $end) = @_;
3089 $start &&= "AND cust_credit_bill._date <= $start";
3090 $end &&= "AND cust_credit_bill._date > $end";
3091 $start = '' unless defined($start);
3092 $end = '' unless defined($end);
3093 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3094 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3099 Returns an SQL fragment to retrieve the due date of an invoice.
3100 Currently only supported on PostgreSQL.
3105 die "don't use: doesn't account for agent-specific invoice_default_terms";
3107 #we're passed a $conf but not a specific customer (that's in the query), so
3108 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3109 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3112 my $conf = new FS::Conf;
3116 cust_bill.invoice_terms,
3117 cust_main.invoice_terms,
3118 \''.($conf->config('invoice_default_terms') || '').'\'
3119 ), E\'Net (\\\\d+)\'
3121 ) * 86400 + cust_bill._date'
3132 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3133 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base