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'; }
147 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
148 # (except email_subject and invnum_date_pretty)
151 $self->conf->config('notice_name') || 'Invoice'
154 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
155 sub cust_unlinked_msg {
157 "WARNING: can't find cust_main.custnum ". $self->custnum.
158 ' (cust_bill.invnum '. $self->invnum. ')';
163 Adds this invoice to the database ("Posts" the invoice). If there is an error,
164 returns the error, otherwise returns false.
170 warn "$me insert called\n" if $DEBUG;
172 local $SIG{HUP} = 'IGNORE';
173 local $SIG{INT} = 'IGNORE';
174 local $SIG{QUIT} = 'IGNORE';
175 local $SIG{TERM} = 'IGNORE';
176 local $SIG{TSTP} = 'IGNORE';
177 local $SIG{PIPE} = 'IGNORE';
179 my $oldAutoCommit = $FS::UID::AutoCommit;
180 local $FS::UID::AutoCommit = 0;
183 my $error = $self->SUPER::insert;
185 $dbh->rollback if $oldAutoCommit;
189 if ( $self->get('cust_bill_pkg') ) {
190 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
191 $cust_bill_pkg->invnum($self->invnum);
192 my $error = $cust_bill_pkg->insert;
194 $dbh->rollback if $oldAutoCommit;
195 return "can't create invoice line item: $error";
200 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
207 Voids this invoice: deletes the invoice and adds a record of the voided invoice
208 to the FS::cust_bill_void table (and related tables starting from
209 FS::cust_bill_pkg_void).
215 my $reason = scalar(@_) ? shift : '';
217 local $SIG{HUP} = 'IGNORE';
218 local $SIG{INT} = 'IGNORE';
219 local $SIG{QUIT} = 'IGNORE';
220 local $SIG{TERM} = 'IGNORE';
221 local $SIG{TSTP} = 'IGNORE';
222 local $SIG{PIPE} = 'IGNORE';
224 my $oldAutoCommit = $FS::UID::AutoCommit;
225 local $FS::UID::AutoCommit = 0;
228 my $cust_bill_void = new FS::cust_bill_void ( {
229 map { $_ => $self->get($_) } $self->fields
231 $cust_bill_void->reason($reason);
232 my $error = $cust_bill_void->insert;
234 $dbh->rollback if $oldAutoCommit;
238 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
239 my $error = $cust_bill_pkg->void($reason);
241 $dbh->rollback if $oldAutoCommit;
246 $error = $self->delete;
248 $dbh->rollback if $oldAutoCommit;
252 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
260 This method now works but you probably shouldn't use it. Instead, apply a
261 credit against the invoice, or use the new void method.
263 Using this method to delete invoices outright is really, really bad. There
264 would be no record you ever posted this invoice, and there are no check to
265 make sure charged = 0 or that there are no associated cust_bill_pkg records.
267 Really, don't use it.
273 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
275 local $SIG{HUP} = 'IGNORE';
276 local $SIG{INT} = 'IGNORE';
277 local $SIG{QUIT} = 'IGNORE';
278 local $SIG{TERM} = 'IGNORE';
279 local $SIG{TSTP} = 'IGNORE';
280 local $SIG{PIPE} = 'IGNORE';
282 my $oldAutoCommit = $FS::UID::AutoCommit;
283 local $FS::UID::AutoCommit = 0;
286 foreach my $table (qw(
294 #cust_event # problematic
296 foreach my $linked ( $self->$table() ) {
297 my $error = $linked->delete;
299 $dbh->rollback if $oldAutoCommit;
306 my $error = $self->SUPER::delete(@_);
308 $dbh->rollback if $oldAutoCommit;
312 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
318 =item replace [ OLD_RECORD ]
320 You can, but probably shouldn't modify invoices...
322 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
323 supplied, replaces this record. If there is an error, returns the error,
324 otherwise returns false.
328 #replace can be inherited from Record.pm
330 # replace_check is now the preferred way to #implement replace data checks
331 # (so $object->replace() works without an argument)
334 my( $new, $old ) = ( shift, shift );
335 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
336 #return "Can't change _date!" unless $old->_date eq $new->_date;
337 return "Can't change _date" unless $old->_date == $new->_date;
338 return "Can't change charged" unless $old->charged == $new->charged
339 || $old->pending eq 'Y'
340 || $old->charged == 0
341 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
347 =item add_cc_surcharge
353 sub add_cc_surcharge {
354 my ($self, $pkgnum, $amount) = (shift, shift, shift);
357 my $cust_bill_pkg = new FS::cust_bill_pkg({
358 'invnum' => $self->invnum,
362 $error = $cust_bill_pkg->insert;
363 return $error if $error;
365 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
366 $self->charged($self->charged+$amount);
367 $error = $self->replace;
368 return $error if $error;
370 $self->apply_payments_and_credits;
376 Checks all fields to make sure this is a valid invoice. If there is an error,
377 returns the error, otherwise returns false. Called by the insert and replace
386 $self->ut_numbern('invnum')
387 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
388 || $self->ut_numbern('_date')
389 || $self->ut_money('charged')
390 || $self->ut_numbern('printed')
391 || $self->ut_enum('closed', [ '', 'Y' ])
392 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
393 || $self->ut_numbern('agent_invid') #varchar?
394 || $self->ut_flag('pending')
396 return $error if $error;
398 $self->_date(time) unless $self->_date;
400 $self->printed(0) if $self->printed eq '';
407 Returns the displayed invoice number for this invoice: agent_invid if
408 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
414 if ( $self->agent_invid
415 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
416 return $self->agent_invid;
418 return $self->invnum;
424 Returns the customer's last invoice before this one.
430 if ( !$self->get('previous_bill') ) {
431 $self->set('previous_bill', qsearchs({
432 'table' => 'cust_bill',
433 'hashref' => { 'custnum' => $self->custnum,
434 '_date' => { op=>'<', value=>$self->_date } },
435 'order_by' => 'ORDER BY _date DESC LIMIT 1',
438 $self->get('previous_bill');
443 Returns a list consisting of the total previous balance for this customer,
444 followed by the previous outstanding invoices (as FS::cust_bill objects also).
450 # simple memoize; we use this a lot
451 if (!$self->get('previous')) {
453 my @cust_bill = sort { $a->_date <=> $b->_date }
454 grep { $_->owed != 0 }
455 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
456 #'_date' => { op=>'<', value=>$self->_date },
457 'invnum' => { op=>'<', value=>$self->invnum },
460 foreach ( @cust_bill ) { $total += $_->owed; }
461 $self->set('previous', [$total, @cust_bill]);
463 return @{ $self->get('previous') };
466 =item enable_previous
468 Whether to show the 'Previous Charges' section when printing this invoice.
469 The negation of the 'disable_previous_balance' config setting.
473 sub enable_previous {
475 my $agentnum = $self->cust_main->agentnum;
476 !$self->conf->exists('disable_previous_balance', $agentnum);
481 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
488 { 'table' => 'cust_bill_pkg',
489 'hashref' => { 'invnum' => $self->invnum },
490 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
491 # the AUTLOADED FK search. or should
492 # that default to ORDER by the pkey?
497 =item cust_bill_pkg_pkgnum PKGNUM
499 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
504 sub cust_bill_pkg_pkgnum {
505 my( $self, $pkgnum ) = @_;
507 { 'table' => 'cust_bill_pkg',
508 'hashref' => { 'invnum' => $self->invnum,
511 'order_by' => 'ORDER BY billpkgnum',
518 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
525 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
526 $self->cust_bill_pkg;
528 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
533 Returns true if any of the packages (or their definitions) corresponding to the
534 line items for this invoice have the no_auto flag set.
540 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
543 =item open_cust_bill_pkg
545 Returns the open line items for this invoice.
547 Note that cust_bill_pkg with both setup and recur fees are returned as two
548 separate line items, each with only one fee.
552 # modeled after cust_main::open_cust_bill
553 sub open_cust_bill_pkg {
556 # grep { $_->owed > 0 } $self->cust_bill_pkg
558 my %other = ( 'recur' => 'setup',
559 'setup' => 'recur', );
561 foreach my $field ( qw( recur setup )) {
562 push @open, map { $_->set( $other{$field}, 0 ); $_; }
563 grep { $_->owed($field) > 0 }
564 $self->cust_bill_pkg;
572 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
576 #false laziness w/cust_pkg.pm
580 'table' => 'cust_event',
581 'addl_from' => 'JOIN part_event USING ( eventpart )',
582 'hashref' => { 'tablenum' => $self->invnum },
583 'extra_sql' => " AND eventtable = 'cust_bill' ",
589 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
593 #false laziness w/cust_pkg.pm
597 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
598 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
599 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
600 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
601 $sth->fetchrow_arrayref->[0];
606 Returns the customer (see L<FS::cust_main>) for this invoice.
610 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice
612 Returns a list: an empty list on success or a list of errors.
619 grep { $_->suspend(@_) }
620 grep {! $_->getfield('cancel') }
625 =item cust_suspend_if_balance_over AMOUNT
627 Suspends the customer associated with this invoice if the total amount owed on
628 this invoice and all older invoices is greater than the specified amount.
630 Returns a list: an empty list on success or a list of errors.
634 sub cust_suspend_if_balance_over {
635 my( $self, $amount ) = ( shift, shift );
636 my $cust_main = $self->cust_main;
637 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
640 $cust_main->suspend(@_);
646 Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options
651 my( $self, %opt ) = @_;
653 warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
654 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
657 return ( 'Access denied' )
658 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
660 my @pkgs = $self->cust_pkg;
662 if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
664 my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
665 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
670 map { $_->cancel(%opt) }
671 grep { ! $_->getfield('cancel') }
677 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
683 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
684 sort { $a->_date <=> $b->_date }
685 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
690 =item cust_credit_bill
692 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
698 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
699 sort { $a->_date <=> $b->_date }
700 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
704 sub cust_credit_bill {
705 shift->cust_credited(@_);
708 #=item cust_bill_pay_pkgnum PKGNUM
710 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
711 #with matching pkgnum.
715 #sub cust_bill_pay_pkgnum {
716 # my( $self, $pkgnum ) = @_;
717 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
718 # sort { $a->_date <=> $b->_date }
719 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
720 # 'pkgnum' => $pkgnum,
725 =item cust_bill_pay_pkg PKGNUM
727 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
728 applied against the matching pkgnum.
732 sub cust_bill_pay_pkg {
733 my( $self, $pkgnum ) = @_;
736 'select' => 'cust_bill_pay_pkg.*',
737 'table' => 'cust_bill_pay_pkg',
738 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
739 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
740 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
741 " AND cust_bill_pkg.pkgnum = $pkgnum",
746 #=item cust_credited_pkgnum PKGNUM
748 #=item cust_credit_bill_pkgnum PKGNUM
750 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
751 #with matching pkgnum.
755 #sub cust_credited_pkgnum {
756 # my( $self, $pkgnum ) = @_;
757 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
758 # sort { $a->_date <=> $b->_date }
759 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
760 # 'pkgnum' => $pkgnum,
765 #sub cust_credit_bill_pkgnum {
766 # shift->cust_credited_pkgnum(@_);
769 =item cust_credit_bill_pkg PKGNUM
771 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
772 applied against the matching pkgnum.
776 sub cust_credit_bill_pkg {
777 my( $self, $pkgnum ) = @_;
780 'select' => 'cust_credit_bill_pkg.*',
781 'table' => 'cust_credit_bill_pkg',
782 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
783 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
784 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
785 " AND cust_bill_pkg.pkgnum = $pkgnum",
790 =item cust_bill_batch
792 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
796 sub cust_bill_batch {
798 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
803 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
804 hash keyed by term length.
810 FS::discount_plan->all($self);
815 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
822 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
824 foreach (@taxlines) { $total += $_->setup; }
830 Returns the amount owed (still outstanding) on this invoice, which is charged
831 minus all payment applications (see L<FS::cust_bill_pay>) and credit
832 applications (see L<FS::cust_credit_bill>).
838 my $balance = $self->charged;
839 $balance -= $_->amount foreach ( $self->cust_bill_pay );
840 $balance -= $_->amount foreach ( $self->cust_credited );
841 $balance = sprintf( "%.2f", $balance);
842 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
847 my( $self, $pkgnum ) = @_;
849 #my $balance = $self->charged;
851 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
853 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
854 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
856 $balance = sprintf( "%.2f", $balance);
857 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
863 Returns true if this invoice should be hidden. See the
864 selfservice-hide_invoices-taxclass configuraiton setting.
870 my $conf = $self->conf;
871 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
873 my @cust_bill_pkg = $self->cust_bill_pkg;
874 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
875 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
878 =item apply_payments_and_credits [ OPTION => VALUE ... ]
880 Applies unapplied payments and credits to this invoice.
882 A hash of optional arguments may be passed. Currently "manual" is supported.
883 If true, a payment receipt is sent instead of a statement when
884 'payment_receipt_email' configuration option is set.
886 If there is an error, returns the error, otherwise returns false.
890 sub apply_payments_and_credits {
891 my( $self, %options ) = @_;
892 my $conf = $self->conf;
894 local $SIG{HUP} = 'IGNORE';
895 local $SIG{INT} = 'IGNORE';
896 local $SIG{QUIT} = 'IGNORE';
897 local $SIG{TERM} = 'IGNORE';
898 local $SIG{TSTP} = 'IGNORE';
899 local $SIG{PIPE} = 'IGNORE';
901 my $oldAutoCommit = $FS::UID::AutoCommit;
902 local $FS::UID::AutoCommit = 0;
905 $self->select_for_update; #mutex
907 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
908 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
910 if ( $conf->exists('pkg-balances') ) {
911 # limit @payments & @credits to those w/ a pkgnum grepped from $self
912 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
913 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
914 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
917 while ( $self->owed > 0 and ( @payments || @credits ) ) {
920 if ( @payments && @credits ) {
922 #decide which goes first by weight of top (unapplied) line item
924 my @open_lineitems = $self->open_cust_bill_pkg;
927 max( map { $_->part_pkg->pay_weight || 0 }
932 my $max_credit_weight =
933 max( map { $_->part_pkg->credit_weight || 0 }
939 #if both are the same... payments first? it has to be something
940 if ( $max_pay_weight >= $max_credit_weight ) {
946 } elsif ( @payments ) {
948 } elsif ( @credits ) {
951 die "guru meditation #12 and 35";
955 if ( $app eq 'pay' ) {
957 my $payment = shift @payments;
958 $unapp_amount = $payment->unapplied;
959 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
960 $app->pkgnum( $payment->pkgnum )
961 if $conf->exists('pkg-balances') && $payment->pkgnum;
963 } elsif ( $app eq 'credit' ) {
965 my $credit = shift @credits;
966 $unapp_amount = $credit->credited;
967 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
968 $app->pkgnum( $credit->pkgnum )
969 if $conf->exists('pkg-balances') && $credit->pkgnum;
972 die "guru meditation #12 and 35";
976 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
977 warn "owed_pkgnum ". $app->pkgnum;
978 $owed = $self->owed_pkgnum($app->pkgnum);
982 next unless $owed > 0;
984 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
985 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
987 $app->invnum( $self->invnum );
989 my $error = $app->insert(%options);
991 $dbh->rollback if $oldAutoCommit;
992 return "Error inserting ". $app->table. " record: $error";
994 die $error if $error;
998 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1005 Sends this invoice to the destinations configured for this customer: sends
1006 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1008 Options can be passed as a hashref. Positional parameters are no longer
1011 I<template>: a suffix for alternate invoices
1013 I<agentnum>: obsolete, now does nothing.
1015 I<from> overrides the default email invoice From: address.
1017 I<amount>: obsolete, does nothing
1019 I<notice_name> overrides "Invoice" as the name of the sent document
1020 (templates from 10/2009 or newer required).
1022 I<lpr> overrides the system 'lpr' option as the command to print a document
1023 from standard input.
1029 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1030 my $conf = $self->conf;
1032 my $cust_main = $self->cust_main;
1034 my @invoicing_list = $cust_main->invoicing_list;
1037 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1038 && ! $cust_main->invoice_noemail;
1041 if grep { $_ eq 'POST' } @invoicing_list; #postal
1043 #this has never been used post-$ORIGINAL_ISP afaik
1044 $self->fax_invoice($opt)
1045 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1053 my $opt = shift || {};
1054 if ($opt and !ref($opt)) {
1055 die ref($self). '->email called with positional parameters';
1058 my $conf = $self->conf;
1060 my $from = delete $opt->{from};
1062 # this is where we set the From: address
1063 $from ||= $self->_agent_invoice_from || #XXX should go away
1064 $conf->invoice_from_full( $self->cust_main->agentnum );
1066 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1068 if ( ! @invoicing_list ) { #no recipients
1069 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1070 die 'No recipients for customer #'. $self->custnum;
1072 #default: better to notify this person than silence
1073 @invoicing_list = ($from);
1077 $self->SUPER::email( {
1079 'to' => \@invoicing_list,
1085 #this stays here for now because its explicitly used as
1086 # FS::cust_bill::queueable_email
1087 sub queueable_email {
1090 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1091 or die "invalid invoice number: " . $opt{invnum};
1094 $self->set('mode', $opt{mode});
1097 my %args = map {$_ => $opt{$_}}
1099 qw( from notice_name no_coupon template );
1101 my $error = $self->email( \%args );
1102 die $error if $error;
1108 my $conf = $self->conf;
1110 #my $template = scalar(@_) ? shift : '';
1113 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1116 my $cust_main = $self->cust_main;
1117 my $name = $cust_main->name;
1118 my $name_short = $cust_main->name_short;
1119 my $invoice_number = $self->invnum;
1120 my $invoice_date = $self->_date_pretty;
1122 eval qq("$subject");
1125 =item lpr_data HASHREF
1127 Returns the postscript or plaintext for this invoice as an arrayref.
1129 Options must be passed as a hashref. Positional parameters are no longer
1132 I<template>, if specified, is the name of a suffix for alternate invoices.
1134 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1140 my $conf = $self->conf;
1141 my $opt = shift || {};
1142 if ($opt and !ref($opt)) {
1143 # nobody does this anyway
1144 die "FS::cust_bill::lpr_data called with positional parameters";
1147 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1148 [ $self->$method( $opt ) ];
1153 Prints this invoice.
1155 Options must be passed as a hashref.
1157 I<template>, if specified, is the name of a suffix for alternate invoices.
1159 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1165 return if $self->hide;
1166 my $conf = $self->conf;
1167 my $opt = shift || {};
1168 if ($opt and !ref($opt)) {
1169 die "FS::cust_bill::print called with positional parameters";
1172 my $lpr = delete $opt->{lpr};
1173 if($conf->exists('invoice_print_pdf')) {
1174 # Add the invoice to the current batch.
1175 $self->batch_invoice($opt);
1179 $self->lpr_data($opt),
1180 'agentnum' => $self->cust_main->agentnum,
1186 =item fax_invoice HASHREF
1190 Options must be passed as a hashref.
1192 I<template>, if specified, is the name of a suffix for alternate invoices.
1194 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1200 return if $self->hide;
1201 my $conf = $self->conf;
1202 my $opt = shift || {};
1203 if ($opt and !ref($opt)) {
1204 die "FS::cust_bill::fax_invoice called with positional parameters";
1207 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1208 unless $conf->exists('invoice_latex');
1210 my $dialstring = $self->cust_main->getfield('fax');
1213 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1214 'dialstring' => $dialstring,
1216 die $error if $error;
1220 =item batch_invoice [ HASHREF ]
1222 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1223 isn't an open batch, one will be created.
1225 HASHREF may contain any options to be passed to C<print_pdf>.
1230 my ($self, $opt) = @_;
1231 my $bill_batch = $self->get_open_bill_batch;
1232 my $cust_bill_batch = FS::cust_bill_batch->new({
1233 batchnum => $bill_batch->batchnum,
1234 invnum => $self->invnum,
1236 return $cust_bill_batch->insert($opt);
1239 =item get_open_batch
1241 Returns the currently open batch as an FS::bill_batch object, creating a new
1242 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1247 sub get_open_bill_batch {
1249 my $conf = $self->conf;
1250 my $hashref = { status => 'O' };
1251 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1252 ? $self->cust_main->agentnum
1254 my $batch = qsearchs('bill_batch', $hashref);
1255 return $batch if $batch;
1256 $batch = FS::bill_batch->new($hashref);
1257 my $error = $batch->insert;
1258 die $error if $error;
1262 =item ftp_invoice [ TEMPLATENAME ]
1264 Sends this invoice data via FTP.
1266 TEMPLATENAME is unused?
1272 my $conf = $self->conf;
1273 my $template = scalar(@_) ? shift : '';
1276 'protocol' => 'ftp',
1277 'server' => $conf->config('cust_bill-ftpserver'),
1278 'username' => $conf->config('cust_bill-ftpusername'),
1279 'password' => $conf->config('cust_bill-ftppassword'),
1280 'dir' => $conf->config('cust_bill-ftpdir'),
1281 'format' => $conf->config('cust_bill-ftpformat'),
1285 =item spool_invoice [ TEMPLATENAME ]
1287 Spools this invoice data (see L<FS::spool_csv>)
1289 TEMPLATENAME is unused?
1295 my $conf = $self->conf;
1296 my $template = scalar(@_) ? shift : '';
1299 'format' => $conf->config('cust_bill-spoolformat'),
1300 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1304 =item send_csv OPTION => VALUE, ...
1306 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1310 protocol - currently only "ftp"
1316 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1317 and YYMMDDHHMMSS is a timestamp.
1319 See L</print_csv> for a description of the output format.
1324 my($self, %opt) = @_;
1328 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1329 mkdir $spooldir, 0700 unless -d $spooldir;
1331 # don't localize dates here, they're a defined format
1332 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1333 my $file = "$spooldir/$tracctnum.csv";
1335 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1337 open(CSV, ">$file") or die "can't open $file: $!";
1345 if ( $opt{protocol} eq 'ftp' ) {
1346 eval "use Net::FTP;";
1348 $net = Net::FTP->new($opt{server}) or die @$;
1350 die "unknown protocol: $opt{protocol}";
1353 $net->login( $opt{username}, $opt{password} )
1354 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1356 $net->binary or die "can't set binary mode";
1358 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1360 $net->put($file) or die "can't put $file: $!";
1370 Spools CSV invoice data.
1376 =item format - any of FS::Misc::::Invoicing::spool_formats
1378 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1379 customer has the corresponding invoice destinations set (see
1380 L<FS::cust_main_invoice>).
1382 =item agent_spools - if set to a true value, will spool to per-agent files
1383 rather than a single global file
1385 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1386 append to that spool. L<FS::Cron::upload> will then send the spool file to
1389 =item balanceover - if set, only spools the invoice if the total amount owed on
1390 this invoice and all older invoices is greater than the specified amount.
1392 =item time - the "current time". Controls the printing of past due messages
1400 my($self, %opt) = @_;
1402 my $time = $opt{'time'} || time;
1403 my $cust_main = $self->cust_main;
1405 if ( $opt{'dest'} ) {
1406 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1407 $cust_main->invoicing_list;
1408 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1409 || ! keys %invoicing_list;
1412 if ( $opt{'balanceover'} ) {
1414 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1417 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1418 mkdir $spooldir, 0700 unless -d $spooldir;
1420 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1423 if ( $opt{'agent_spools'} ) {
1424 $file = 'agentnum'.$cust_main->agentnum;
1429 if ( $opt{'upload_targetnum'} ) {
1430 $spooldir .= '/target'.$opt{'upload_targetnum'};
1431 mkdir $spooldir, 0700 unless -d $spooldir;
1432 } # otherwise it just goes into export.xxx/cust_bill
1434 if ( lc($opt{'format'}) eq 'billco' ) {
1438 $file = "$spooldir/$file.csv";
1440 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1442 open(CSV, ">>$file") or die "can't open $file: $!";
1443 flock(CSV, LOCK_EX);
1448 if ( lc($opt{'format'}) eq 'billco' ) {
1450 flock(CSV, LOCK_UN);
1453 $file =~ s/-header.csv$/-detail.csv/;
1455 open(CSV,">>$file") or die "can't open $file: $!";
1456 flock(CSV, LOCK_EX);
1460 print CSV $detail if defined($detail);
1462 flock(CSV, LOCK_UN);
1469 =item print_csv OPTION => VALUE, ...
1471 Returns CSV data for this invoice.
1475 format - 'default', 'billco', 'oneline', 'bridgestone'
1477 Returns a list consisting of two scalars. The first is a single line of CSV
1478 header information for this invoice. The second is one or more lines of CSV
1479 detail information for this invoice.
1481 If I<format> is not specified or "default", the fields of the CSV file are as
1484 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1485 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1489 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1491 B<record_type> is C<cust_bill> for the initial header line only. The
1492 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1493 fields are filled in.
1495 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1496 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1499 =item invnum - invoice number
1501 =item custnum - customer number
1503 =item _date - invoice date
1505 =item charged - total invoice amount
1507 =item first - customer first name
1509 =item last - customer first name
1511 =item company - company name
1513 =item address1 - address line 1
1515 =item address2 - address line 1
1525 =item pkg - line item description
1527 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1529 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1531 =item sdate - start date for recurring fee
1533 =item edate - end date for recurring fee
1537 If I<format> is "billco", the fields of the header CSV file are as follows:
1539 +-------------------------------------------------------------------+
1540 | FORMAT HEADER FILE |
1541 |-------------------------------------------------------------------|
1542 | Field | Description | Name | Type | Width |
1543 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1544 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1545 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1546 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1547 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1548 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1549 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1550 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1551 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1552 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1553 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1554 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1555 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1556 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1557 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1558 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1559 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1560 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1561 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1562 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1563 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1564 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1565 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1566 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1567 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1568 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1569 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1570 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1571 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1572 +-------+-------------------------------+------------+------+-------+
1574 If I<format> is "billco", the fields of the detail CSV file are as follows:
1576 FORMAT FOR DETAIL FILE
1578 Field | Description | Name | Type | Width
1579 1 | N/A-Leave Empty | RC | CHAR | 2
1580 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1581 3 | Account Number | TRACCTNUM | CHAR | 15
1582 4 | Invoice Number | TRINVOICE | CHAR | 15
1583 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1584 6 | Transaction Detail | DETAILS | CHAR | 100
1585 7 | Amount | AMT | NUM* | 9
1586 8 | Line Format Control** | LNCTRL | CHAR | 2
1587 9 | Grouping Code | GROUP | CHAR | 2
1588 10 | User Defined | ACCT CODE | CHAR | 15
1590 If format is 'oneline', there is no detail file. Each invoice has a
1591 header line only, with the fields:
1593 Agent number, agent name, customer number, first name, last name, address
1594 line 1, address line 2, city, state, zip, invoice date, invoice number,
1595 amount charged, amount due, previous balance, due date.
1597 and then, for each line item, three columns containing the package number,
1598 description, and amount.
1600 If format is 'bridgestone', there is no detail file. Each invoice has a
1601 header line with the following fields in a fixed-width format:
1603 Customer number (in display format), date, name (first last), company,
1604 address 1, address 2, city, state, zip.
1606 This is a mailing list format, and has no per-invoice fields. To avoid
1607 sending redundant notices, the spooling event should have a "once" or
1608 "once_percust_every" condition.
1613 my($self, %opt) = @_;
1615 eval "use Text::CSV_XS";
1618 my $cust_main = $self->cust_main;
1620 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1621 my $format = lc($opt{'format'});
1623 my $time = $opt{'time'} || time;
1625 my $tracctnum = ''; #leaking out from billco-specific sections :/
1626 if ( $format eq 'billco' ) {
1629 $self->conf->config('billco-account_num', $cust_main->agentnum);
1631 $tracctnum = $account_num eq 'display_custnum'
1632 ? $cust_main->display_custnum
1633 : $opt{'tracctnum'};
1636 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1638 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1640 my( $previous_balance, @unused ) = $self->previous; #previous balance
1642 my $pmt_cr_applied = 0;
1643 $pmt_cr_applied += $_->{'amount'}
1644 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1646 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1649 '', # 1 | N/A-Leave Empty CHAR 2
1650 '', # 2 | N/A-Leave Empty CHAR 15
1651 $tracctnum, # 3 | Transaction Account No CHAR 15
1652 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1653 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1654 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1655 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1656 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1657 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1658 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1659 '', # 10 | Ancillary Billing Information CHAR 30
1660 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1661 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1664 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1667 $duedate, # 14 | Bill Due Date CHAR 10
1669 $previous_balance, # 15 | Previous Balance NUM* 9
1670 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1671 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1672 $totaldue, # 18 | Total Amt Due NUM* 9
1673 $totaldue, # 19 | Total Amt Due NUM* 9
1674 '', # 20 | 30 Day Aging NUM* 9
1675 '', # 21 | 60 Day Aging NUM* 9
1676 '', # 22 | 90 Day Aging NUM* 9
1677 'N', # 23 | Y/N CHAR 1
1678 '', # 24 | Remittance automation CHAR 100
1679 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1680 $self->custnum, # 26 | Customer Reference Number CHAR 15
1681 '0', # 27 | Federal Tax*** NUM* 9
1682 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1683 '0', # 29 | Other Taxes & Fees*** NUM* 9
1686 } elsif ( $format eq 'oneline' ) { #name
1688 my ($previous_balance) = $self->previous;
1689 $previous_balance = sprintf('%.2f', $previous_balance);
1690 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1696 $self->_items_pkg, #_items_nontax? no sections or anything
1701 $cust_main->agentnum,
1702 $cust_main->agent->agent,
1706 $cust_main->company,
1707 $cust_main->address1,
1708 $cust_main->address2,
1714 time2str("%x", $self->_date),
1719 $self->due_date2str("%x"),
1724 } elsif ( $format eq 'bridgestone' ) {
1726 # bypass the CSV stuff and just return this
1727 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1728 my $zip = $cust_main->zip;
1730 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1734 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1736 $cust_main->display_custnum,
1738 uc(substr($cust_main->contact_firstlast,0,30)),
1739 uc(substr($cust_main->company ,0,30)),
1740 uc(substr($cust_main->address1 ,0,30)),
1741 uc(substr($cust_main->address2 ,0,30)),
1742 uc(substr($cust_main->city ,0,20)),
1743 uc($cust_main->state),
1749 } elsif ( $format eq 'ics' ) {
1751 my $bill = $cust_main->bill_location;
1752 my $zip = $bill->zip;
1756 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1761 # minor false laziness with print_generic
1762 my ($previous_balance) = $self->previous;
1763 my $balance_due = $self->owed + $previous_balance;
1764 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1765 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1768 if ( $self->due_date and $time >= $self->due_date ) {
1769 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1773 my $header = sprintf(
1774 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1775 $cust_main->display_custnum, #BID
1776 uc($cust_main->first), #FNAME
1777 uc($cust_main->last), #LNAME
1778 '00', #BATCH, should this ever be anything else?
1779 uc($cust_main->company), #COMP
1780 uc($bill->address1), #STREET1
1781 uc($bill->address2), #STREET2
1782 uc($bill->city), #CITY
1783 uc($bill->state), #STATE
1786 time2str('%Y%m%d', $self->_date), #BILL_DATE
1787 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1788 ( map {sprintf('%0.2f', $_)}
1789 $balance_due, #AMNT_DUE
1790 $previous_balance, #PREV_BAL
1791 $payment_total, #PYMT_RCVD
1792 $credit_total, #CREDITS
1793 $previous_balance, #BEG_BAL--is this correct?
1794 $self->charged, #NEW_CHRG
1797 $past_due, #PAST_MSG
1801 my %svc_class = ('' => ''); # maybe cache this more persistently?
1803 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1805 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1806 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1810 my @dates = ( $self->_date, undef );
1811 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1812 $dates[1] = $prev->sdate; #questionable
1815 # generate an 01 detail for each service
1816 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1817 foreach my $cust_svc ( @svcs ) {
1818 $show_pkgnum = ''; # hide it if we're showing svcnums
1820 my $svcpart = $cust_svc->svcpart;
1821 if (!exists($svc_class{$svcpart})) {
1822 my $classnum = $cust_svc->part_svc->classnum;
1823 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1825 $svc_class{$svcpart} = $part_svc_class ?
1826 $part_svc_class->classname :
1830 my @h_label = $cust_svc->label(@dates, 'I');
1831 push @details, sprintf('01%-9s%-20s%-47s',
1833 $svc_class{$svcpart},
1836 } #foreach $cust_svc
1839 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1840 if ($cust_bill_pkg->recur > 0) {
1841 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1842 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1844 push @details, sprintf('02%-6s%-60s%-10s',
1847 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1849 } #foreach $cust_bill_pkg
1851 # Tag this row so that we know whether this is one page (1), two pages
1852 # (2), # or "big" (B). The tag will be stripped off before uploading.
1853 if ( scalar(@details) < 12 ) {
1855 } elsif ( scalar(@details) < 58 ) {
1861 return join('', $header, @details, "\n");
1869 time2str("%x", $self->_date),
1870 sprintf("%.2f", $self->charged),
1871 ( map { $cust_main->getfield($_) }
1872 qw( first last company address1 address2 city state zip country ) ),
1874 ) or die "can't create csv";
1877 my $header = $csv->string. "\n";
1880 if ( lc($opt{'format'}) eq 'billco' ) {
1883 my %items_opt = ( format => 'template',
1884 escape_function => sub { shift } );
1885 # I don't know what characters billco actually tolerates in spool entries.
1886 # Text::CSV will take care of delimiters, though.
1888 my @items = ( $self->_items_pkg(%items_opt),
1889 $self->_items_fee(%items_opt) );
1890 foreach my $item (@items) {
1892 my $description = $item->{'description'};
1893 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1894 $description .= ': ' . $item->{ext_description}[0];
1898 '', # 1 | N/A-Leave Empty CHAR 2
1899 '', # 2 | N/A-Leave Empty CHAR 15
1900 $tracctnum, # 3 | Account Number CHAR 15
1901 $self->invnum, # 4 | Invoice Number CHAR 15
1902 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1903 $description, # 6 | Transaction Detail CHAR 100
1904 $item->{'amount'}, # 7 | Amount NUM* 9
1905 '', # 8 | Line Format Control** CHAR 2
1906 '', # 9 | Grouping Code CHAR 2
1907 '', # 10 | User Defined CHAR 15
1910 $detail .= $csv->string. "\n";
1914 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1920 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1922 my($pkg, $setup, $recur, $sdate, $edate);
1923 if ( $cust_bill_pkg->pkgnum ) {
1925 ($pkg, $setup, $recur, $sdate, $edate) = (
1926 $cust_bill_pkg->part_pkg->pkg,
1927 ( $cust_bill_pkg->setup != 0
1928 ? sprintf("%.2f", $cust_bill_pkg->setup )
1930 ( $cust_bill_pkg->recur != 0
1931 ? sprintf("%.2f", $cust_bill_pkg->recur )
1933 ( $cust_bill_pkg->sdate
1934 ? time2str("%x", $cust_bill_pkg->sdate)
1936 ($cust_bill_pkg->edate
1937 ? time2str("%x", $cust_bill_pkg->edate)
1941 } else { #pkgnum tax
1942 next unless $cust_bill_pkg->setup != 0;
1943 $pkg = $cust_bill_pkg->desc;
1944 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1945 ( $sdate, $edate ) = ( '', '' );
1951 ( map { '' } (1..11) ),
1952 ($pkg, $setup, $recur, $sdate, $edate)
1953 ) or die "can't create csv";
1955 $detail .= $csv->string. "\n";
1961 ( $header, $detail );
1966 croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
1971 Attempts to pay this invoice with a credit card payment via a
1972 Business::OnlinePayment realtime gateway. See
1973 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1974 for supported processors.
1980 $self->realtime_bop( 'CC', @_ );
1985 Attempts to pay this invoice with an electronic check (ACH) payment via a
1986 Business::OnlinePayment realtime gateway. See
1987 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1988 for supported processors.
1994 $self->realtime_bop( 'ECHECK', @_ );
1999 Attempts to pay this invoice with phone bill (LEC) payment via a
2000 Business::OnlinePayment realtime gateway. See
2001 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2002 for supported processors.
2008 $self->realtime_bop( 'LEC', @_ );
2012 my( $self, $method ) = (shift,shift);
2013 my $conf = $self->conf;
2016 my $cust_main = $self->cust_main;
2017 my $balance = $cust_main->balance;
2018 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2019 $amount = sprintf("%.2f", $amount);
2020 return "not run (balance $balance)" unless $amount > 0;
2022 my $description = 'Internet Services';
2023 if ( $conf->exists('business-onlinepayment-description') ) {
2024 my $dtempl = $conf->config('business-onlinepayment-description');
2026 my $agent_obj = $cust_main->agent
2027 or die "can't retreive agent for $cust_main (agentnum ".
2028 $cust_main->agentnum. ")";
2029 my $agent = $agent_obj->agent;
2030 my $pkgs = join(', ',
2031 map { $_->part_pkg->pkg }
2032 grep { $_->pkgnum } $self->cust_bill_pkg
2034 $description = eval qq("$dtempl");
2037 $cust_main->realtime_bop($method, $amount,
2038 'description' => $description,
2039 'invnum' => $self->invnum,
2040 #this didn't do what we want, it just calls apply_payments_and_credits
2042 'apply_to_invoice' => 1,
2045 #this changes application behavior: auto payments
2046 #triggered against a specific invoice are now applied
2047 #to that invoice instead of oldest open.
2053 =item batch_card OPTION => VALUE...
2055 Adds a payment for this invoice to the pending credit card batch (see
2056 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2057 runs the payment using a realtime gateway.
2062 my ($self, %options) = @_;
2063 my $cust_main = $self->cust_main;
2065 $options{invnum} = $self->invnum;
2067 $cust_main->batch_card(%options);
2070 sub _agent_template {
2072 $self->cust_main->agent_template;
2075 sub _agent_invoice_from {
2077 $self->cust_main->agent_invoice_from;
2080 =item invoice_barcode DIR_OR_FALSE
2082 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2083 it is taken as the temp directory where the PNG file will be generated and the
2084 PNG file name is returned. Otherwise, the PNG image itself is returned.
2088 sub invoice_barcode {
2089 my ($self, $dir) = (shift,shift);
2091 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2092 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2093 my $gd = $gdbar->plot(Height => 30);
2096 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2100 ) or die "can't open temp file: $!\n";
2101 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2102 my $png_file = $bh->filename;
2109 =item invnum_date_pretty
2111 Returns a string with the invoice number and date, for example:
2112 "Invoice #54 (3/20/2008)".
2114 Intended for back-end context, with regard to translation and date formatting.
2118 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2119 # for backend use (and also does the wrong thing, localizing for end customer
2120 # instead of backoffice configured date format)
2121 sub invnum_date_pretty {
2123 #$self->mt('Invoice #').
2124 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2125 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2128 #sub _items_extra_usage_sections {
2130 # my $escape = shift;
2132 # my %sections = ();
2134 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2135 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2137 # next unless $cust_bill_pkg->pkgnum > 0;
2139 # foreach my $section ( keys %usage_class ) {
2141 # my $usage = $cust_bill_pkg->usage($section);
2143 # next unless $usage && $usage > 0;
2145 # $sections{$section} ||= 0;
2146 # $sections{$section} += $usage;
2152 # map { { 'description' => &{$escape}($_),
2153 # 'subtotal' => $sections{$_},
2154 # 'summarized' => '',
2155 # 'tax_section' => '',
2158 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2162 sub _items_extra_usage_sections {
2164 my $conf = $self->conf;
2172 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2174 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2175 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2176 next unless $cust_bill_pkg->pkgnum > 0;
2178 foreach my $classnum ( keys %usage_class ) {
2179 my $section = $usage_class{$classnum}->classname;
2180 $classnums{$section} = $classnum;
2182 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2183 my $amount = $detail->amount;
2184 next unless $amount && $amount > 0;
2186 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2187 $sections{$section}{amount} += $amount; #subtotal
2188 $sections{$section}{calls}++;
2189 $sections{$section}{duration} += $detail->duration;
2191 my $desc = $detail->regionname;
2192 my $description = $desc;
2193 $description = substr($desc, 0, $maxlength). '...'
2194 if $format eq 'latex' && length($desc) > $maxlength;
2196 $lines{$section}{$desc} ||= {
2197 description => &{$escape}($description),
2198 #pkgpart => $part_pkg->pkgpart,
2199 pkgnum => $cust_bill_pkg->pkgnum,
2204 #unit_amount => $cust_bill_pkg->unitrecur,
2205 quantity => $cust_bill_pkg->quantity,
2206 product_code => 'N/A',
2207 ext_description => [],
2210 $lines{$section}{$desc}{amount} += $amount;
2211 $lines{$section}{$desc}{calls}++;
2212 $lines{$section}{$desc}{duration} += $detail->duration;
2218 my %sectionmap = ();
2219 foreach (keys %sections) {
2220 my $usage_class = $usage_class{$classnums{$_}};
2221 $sectionmap{$_} = { 'description' => &{$escape}($_),
2222 'amount' => $sections{$_}{amount}, #subtotal
2223 'calls' => $sections{$_}{calls},
2224 'duration' => $sections{$_}{duration},
2226 'tax_section' => '',
2227 'sort_weight' => $usage_class->weight,
2228 ( $usage_class->format
2229 ? ( map { $_ => $usage_class->$_($format) }
2230 qw( description_generator header_generator total_generator total_line_generator )
2237 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2241 foreach my $section ( keys %lines ) {
2242 foreach my $line ( keys %{$lines{$section}} ) {
2243 my $l = $lines{$section}{$line};
2244 $l->{section} = $sectionmap{$section};
2245 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2246 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2251 return(\@sections, \@lines);
2257 my $end = $self->_date;
2259 # start at date of previous invoice + 1 second or 0 if no previous invoice
2260 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2261 $start = 0 if !$start;
2264 my $cust_main = $self->cust_main;
2265 my @pkgs = $cust_main->all_pkgs;
2266 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2269 foreach my $pkg ( @pkgs ) {
2270 my @h_cust_svc = $pkg->h_cust_svc($end);
2271 foreach my $h_cust_svc ( @h_cust_svc ) {
2272 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2273 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2275 my $inserted = $h_cust_svc->date_inserted;
2276 my $deleted = $h_cust_svc->date_deleted;
2277 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2279 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2281 # DID either activated or ported in; cannot be both for same DID simultaneously
2282 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2283 && (!$phone_inserted->lnp_status
2284 || $phone_inserted->lnp_status eq ''
2285 || $phone_inserted->lnp_status eq 'native')) {
2288 else { # this one not so clean, should probably move to (h_)svc_phone
2289 local($FS::Record::qsearch_qualify_columns) = 0;
2290 my $phone_portedin = qsearchs( 'h_svc_phone',
2291 { 'svcnum' => $h_cust_svc->svcnum,
2292 'lnp_status' => 'portedin' },
2293 FS::h_svc_phone->sql_h_searchs($end),
2295 $num_portedin++ if $phone_portedin;
2298 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2299 if($deleted >= $start && $deleted <= $end && $phone_deleted
2300 && (!$phone_deleted->lnp_status
2301 || $phone_deleted->lnp_status ne 'portingout')) {
2304 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2305 && $phone_deleted->lnp_status
2306 && $phone_deleted->lnp_status eq 'portingout') {
2310 # increment usage minutes
2311 if ( $phone_inserted ) {
2312 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2313 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2316 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2319 # don't look at this service again
2320 push @seen, $h_cust_svc->svcnum;
2324 $minutes = sprintf("%d", $minutes);
2325 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2326 . "$num_deactivated Ported-Out: $num_portedout ",
2327 "Total Minutes: $minutes");
2330 sub _items_accountcode_cdr {
2335 my $section = { 'amount' => 0,
2338 'sort_weight' => '',
2340 'description' => 'Usage by Account Code',
2346 my %accountcodes = ();
2348 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2349 next unless $cust_bill_pkg->pkgnum > 0;
2351 my @header = $cust_bill_pkg->details_header;
2352 next unless scalar(@header);
2353 $section->{'header'} = join(',',@header);
2355 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2357 $section->{'header'} = $detail->formatted('format' => $format)
2358 if($detail->detail eq $section->{'header'});
2360 my $accountcode = $detail->accountcode;
2361 next unless $accountcode;
2363 my $amount = $detail->amount;
2364 next unless $amount && $amount > 0;
2366 $accountcodes{$accountcode} ||= {
2367 description => $accountcode,
2374 product_code => 'N/A',
2375 section => $section,
2376 ext_description => [ $section->{'header'} ],
2380 $section->{'amount'} += $amount;
2381 $accountcodes{$accountcode}{'amount'} += $amount;
2382 $accountcodes{$accountcode}{calls}++;
2383 $accountcodes{$accountcode}{duration} += $detail->duration;
2384 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2388 foreach my $l ( values %accountcodes ) {
2389 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2390 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2391 foreach my $sorted_detail ( @sorted_detail ) {
2392 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2394 delete $l->{detail_temp};
2398 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2400 return ($section,\@sorted_lines);
2403 sub _items_svc_phone_sections {
2405 my $conf = $self->conf;
2413 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2415 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2416 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2418 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2419 next unless $cust_bill_pkg->pkgnum > 0;
2421 my @header = $cust_bill_pkg->details_header;
2422 next unless scalar(@header);
2424 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2426 my $phonenum = $detail->phonenum;
2427 next unless $phonenum;
2429 my $amount = $detail->amount;
2430 next unless $amount && $amount > 0;
2432 $sections{$phonenum} ||= { 'amount' => 0,
2435 'sort_weight' => -1,
2436 'phonenum' => $phonenum,
2438 $sections{$phonenum}{amount} += $amount; #subtotal
2439 $sections{$phonenum}{calls}++;
2440 $sections{$phonenum}{duration} += $detail->duration;
2442 my $desc = $detail->regionname;
2443 my $description = $desc;
2444 $description = substr($desc, 0, $maxlength). '...'
2445 if $format eq 'latex' && length($desc) > $maxlength;
2447 $lines{$phonenum}{$desc} ||= {
2448 description => &{$escape}($description),
2449 #pkgpart => $part_pkg->pkgpart,
2457 product_code => 'N/A',
2458 ext_description => [],
2461 $lines{$phonenum}{$desc}{amount} += $amount;
2462 $lines{$phonenum}{$desc}{calls}++;
2463 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2465 my $line = $usage_class{$detail->classnum}->classname;
2466 $sections{"$phonenum $line"} ||=
2470 'sort_weight' => $usage_class{$detail->classnum}->weight,
2471 'phonenum' => $phonenum,
2472 'header' => [ @header ],
2474 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2475 $sections{"$phonenum $line"}{calls}++;
2476 $sections{"$phonenum $line"}{duration} += $detail->duration;
2478 $lines{"$phonenum $line"}{$desc} ||= {
2479 description => &{$escape}($description),
2480 #pkgpart => $part_pkg->pkgpart,
2488 product_code => 'N/A',
2489 ext_description => [],
2492 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2493 $lines{"$phonenum $line"}{$desc}{calls}++;
2494 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2495 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2496 $detail->formatted('format' => $format);
2501 my %sectionmap = ();
2502 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2503 foreach ( keys %sections ) {
2504 my @header = @{ $sections{$_}{header} || [] };
2506 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2507 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2508 my $usage_class = $summary ? $simple : $usage_simple;
2509 my $ending = $summary ? ' usage charges' : '';
2512 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2514 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2515 'amount' => $sections{$_}{amount}, #subtotal
2516 'calls' => $sections{$_}{calls},
2517 'duration' => $sections{$_}{duration},
2519 'tax_section' => '',
2520 'phonenum' => $sections{$_}{phonenum},
2521 'sort_weight' => $sections{$_}{sort_weight},
2522 'post_total' => $summary, #inspire pagebreak
2524 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2525 qw( description_generator
2528 total_line_generator
2535 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2536 $a->{sort_weight} <=> $b->{sort_weight}
2541 foreach my $section ( keys %lines ) {
2542 foreach my $line ( keys %{$lines{$section}} ) {
2543 my $l = $lines{$section}{$line};
2544 $l->{section} = $sectionmap{$section};
2545 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2546 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2551 if($conf->exists('phone_usage_class_summary')) {
2552 # this only works with Latex
2556 # after this, we'll have only two sections per DID:
2557 # Calls Summary and Calls Detail
2558 foreach my $section ( @sections ) {
2559 if($section->{'post_total'}) {
2560 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2561 $section->{'total_line_generator'} = sub { '' };
2562 $section->{'total_generator'} = sub { '' };
2563 $section->{'header_generator'} = sub { '' };
2564 $section->{'description_generator'} = '';
2565 push @newsections, $section;
2566 my %calls_detail = %$section;
2567 $calls_detail{'post_total'} = '';
2568 $calls_detail{'sort_weight'} = '';
2569 $calls_detail{'description_generator'} = sub { '' };
2570 $calls_detail{'header_generator'} = sub {
2571 return ' & Date/Time & Called Number & Duration & Price'
2572 if $format eq 'latex';
2575 $calls_detail{'description'} = 'Calls Detail: '
2576 . $section->{'phonenum'};
2577 push @newsections, \%calls_detail;
2581 # after this, each usage class is collapsed/summarized into a single
2582 # line under the Calls Summary section
2583 foreach my $newsection ( @newsections ) {
2584 if($newsection->{'post_total'}) { # this means Calls Summary
2585 foreach my $section ( @sections ) {
2586 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2587 && !$section->{'post_total'});
2588 my $newdesc = $section->{'description'};
2589 my $tn = $section->{'phonenum'};
2590 $newdesc =~ s/$tn//g;
2591 my $line = { ext_description => [],
2595 calls => $section->{'calls'},
2596 section => $newsection,
2597 duration => $section->{'duration'},
2598 description => $newdesc,
2599 amount => sprintf("%.2f",$section->{'amount'}),
2600 product_code => 'N/A',
2602 push @newlines, $line;
2607 # after this, Calls Details is populated with all CDRs
2608 foreach my $newsection ( @newsections ) {
2609 if(!$newsection->{'post_total'}) { # this means Calls Details
2610 foreach my $line ( @lines ) {
2611 next unless (scalar(@{$line->{'ext_description'}}) &&
2612 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2614 my @extdesc = @{$line->{'ext_description'}};
2616 foreach my $extdesc ( @extdesc ) {
2617 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2618 push @newextdesc, $extdesc;
2620 $line->{'ext_description'} = \@newextdesc;
2621 $line->{'section'} = $newsection;
2622 push @newlines, $line;
2627 return(\@newsections, \@newlines);
2630 return(\@sections, \@lines);
2634 =sub _items_usage_class_summary OPTIONS
2636 Returns a list of detail items summarizing the usage charges on this
2637 invoice. Each one will have 'amount', 'description' (the usage charge name),
2638 and 'usage_classnum'.
2640 OPTIONS can include 'escape' (a function to escape the descriptions).
2644 sub _items_usage_class_summary {
2648 my $escape = $opt{escape} || sub { $_[0] };
2649 my $invnum = $self->invnum;
2650 my @classes = qsearch({
2651 'table' => 'usage_class',
2652 'select' => 'classnum, classname, SUM(amount) AS amount',
2653 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2654 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2655 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2656 ' GROUP BY classnum, classname, weight'.
2657 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2658 ' ORDER BY weight ASC',
2662 description => &{$escape}($self->mt('Usage Summary')),
2666 foreach my $class (@classes) {
2668 'description' => &{$escape}($class->classname),
2669 'amount' => sprintf('%.2f', $class->amount),
2670 'usage_classnum' => $class->classnum,
2671 'section' => $section,
2677 sub _items_previous {
2679 my $conf = $self->conf;
2680 my $cust_main = $self->cust_main;
2681 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2683 foreach ( @pr_cust_bill ) {
2684 my $date = $conf->exists('invoice_show_prior_due_date')
2685 ? 'due '. $_->due_date2str('short')
2686 : $self->time2str_local('short', $_->_date);
2688 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2689 #'pkgpart' => 'N/A',
2691 'amount' => sprintf("%.2f", $_->owed),
2697 # 'description' => 'Previous Balance',
2698 # #'pkgpart' => 'N/A',
2699 # 'pkgnum' => 'N/A',
2700 # 'amount' => sprintf("%10.2f", $pr_total ),
2701 # 'ext_description' => [ map {
2702 # "Invoice ". $_->invnum.
2703 # " (". time2str("%x",$_->_date). ") ".
2704 # sprintf("%10.2f", $_->owed)
2705 # } @pr_cust_bill ],
2710 sub _items_credits {
2711 my( $self, %opt ) = @_;
2712 my $trim_len = $opt{'trim_len'} || 40;
2717 if ( $self->conf->exists('previous_balance-payments_since') ) {
2718 if ( $opt{'template'} eq 'statement' ) {
2719 # then the current bill is a "statement" (i.e. an invoice sent as
2720 # a payment receipt)
2721 # and in that case we want to see payments on or after THIS invoice
2722 @objects = qsearch('cust_credit', {
2723 'custnum' => $self->custnum,
2724 '_date' => {op => '>=', value => $self->_date},
2728 $date = $self->previous_bill->_date if $self->previous_bill;
2729 @objects = qsearch('cust_credit', {
2730 'custnum' => $self->custnum,
2731 '_date' => {op => '>=', value => $date},
2735 @objects = $self->cust_credited;
2738 foreach my $obj ( @objects ) {
2739 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2741 my $reason = substr($cust_credit->reason, 0, $trim_len);
2742 $reason .= '...' if length($reason) < length($cust_credit->reason);
2743 $reason = " ($reason) " if $reason;
2746 #'description' => 'Credit ref\#'. $_->crednum.
2747 # " (". time2str("%x",$_->cust_credit->_date) .")".
2749 'description' => $self->mt('Credit applied').' '.
2750 $self->time2str_local('short', $obj->_date). $reason,
2751 'amount' => sprintf("%.2f",$obj->amount),
2759 sub _items_payments {
2764 my $detailed = $self->conf->exists('invoice_payment_details');
2766 if ( $self->conf->exists('previous_balance-payments_since') ) {
2767 # then show payments dated on/after the previous bill...
2768 if ( $opt{'template'} eq 'statement' ) {
2769 # then the current bill is a "statement" (i.e. an invoice sent as
2770 # a payment receipt)
2771 # and in that case we want to see payments on or after THIS invoice
2772 @objects = qsearch('cust_pay', {
2773 'custnum' => $self->custnum,
2774 '_date' => {op => '>=', value => $self->_date},
2777 # the normal case: payments on or after the previous invoice
2779 $date = $self->previous_bill->_date if $self->previous_bill;
2780 @objects = qsearch('cust_pay', {
2781 'custnum' => $self->custnum,
2782 '_date' => {op => '>=', value => $date},
2784 # and before the current bill...
2785 @objects = grep { $_->_date < $self->_date } @objects;
2788 @objects = $self->cust_bill_pay;
2791 foreach my $obj (@objects) {
2792 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2793 my $desc = $self->mt('Payment received').' '.
2794 $self->time2str_local('short', $cust_pay->_date );
2795 $desc .= $self->mt(' via ') .
2796 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2800 'description' => $desc,
2801 'amount' => sprintf("%.2f", $obj->amount )
2811 my $conf = $self->conf;
2814 my ($pr_total) = $self->previous;
2815 my ($new_charges_desc, $new_charges_amount);
2817 if ( $conf->exists('previous_balance-exclude_from_total') ) {
2818 # then return separate lines for previous balance and total new charges
2821 { total_item => $self->mt('Previous Balance'),
2822 total_amount => sprintf('%.2f',$pr_total)
2825 $new_charges_desc = $self->mt(
2826 $conf->config('previous_balance-exclude_from_total')
2827 || 'Total New Charges'
2828 ); # localize 'Total New Charges' or whatever's in the config
2830 $new_charges_amount = $self->charged;
2834 $new_charges_desc = $self->mt('Total Charges');
2835 $new_charges_amount = sprintf('%.2f',$self->charged + $pr_total);
2839 if ( $conf->exists('invoice_show_prior_due_date') ) {
2840 # then the due date should be shown with Total New Charges,
2841 # and should NOT be shown with the Balance Due message.
2842 if ( $self->due_date ) {
2843 # localize the "Please pay by" message and the date itself
2844 # (grammar issues with this, yeah)
2845 $new_charges_desc .= ' - ' . $self->mt('Please pay by') . ' ' .
2846 $self->due_date2str('short');
2847 } elsif ( $self->terms ) {
2848 # phrases like "due on receipt" should be localized
2849 $new_charges_desc .= ' - ' . $self->mt($self->terms);
2854 { total_item => $new_charges_desc,
2855 total_amount => $new_charges_amount,
2863 =item call_details [ OPTION => VALUE ... ]
2865 Returns an array of CSV strings representing the call details for this invoice
2866 The only option available is the boolean prepend_billed_number
2871 my ($self, %opt) = @_;
2873 my $format_function = sub { shift };
2875 if ($opt{prepend_billed_number}) {
2876 $format_function = sub {
2880 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2885 my @details = map { $_->details( 'format_function' => $format_function,
2886 'escape_function' => sub{ return() },
2890 $self->cust_bill_pkg;
2891 my $header = $details[0];
2892 ( $header, grep { $_ ne $header } @details );
2902 =item process_reprint
2906 sub process_reprint {
2907 process_re_X('print', @_);
2910 =item process_reemail
2914 sub process_reemail {
2915 process_re_X('email', @_);
2923 process_re_X('fax', @_);
2931 process_re_X('ftp', @_);
2938 sub process_respool {
2939 process_re_X('spool', @_);
2944 my( $method, $job ) = ( shift, shift );
2945 warn "$me process_re_X $method for job $job\n" if $DEBUG;
2948 warn Dumper($param) if $DEBUG;
2959 # spool_invoice ftp_invoice fax_invoice print_invoice
2960 my($method, $job, %param ) = @_;
2962 warn "re_X $method for job $job with param:\n".
2963 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
2966 #some false laziness w/search/cust_bill.html
2968 my $orderby = 'ORDER BY cust_bill._date';
2970 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
2972 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
2974 my @cust_bill = qsearch( {
2975 #'select' => "cust_bill.*",
2976 'table' => 'cust_bill',
2977 'addl_from' => $addl_from,
2979 'extra_sql' => $extra_sql,
2980 'order_by' => $orderby,
2984 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
2986 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
2989 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
2990 foreach my $cust_bill ( @cust_bill ) {
2991 $cust_bill->$method();
2993 if ( $job ) { #progressbar foo
2995 if ( time - $min_sec > $last ) {
2996 my $error = $job->update_statustext(
2997 int( 100 * $num / scalar(@cust_bill) )
2999 die $error if $error;
3010 +{ ( map { $_=>$self->$_ } $self->fields ),
3011 'owed' => $self->owed,
3012 #XXX last payment applied date
3018 =head1 CLASS METHODS
3024 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3029 my ($class, $start, $end) = @_;
3031 $class->paid_sql($start, $end). ' - '.
3032 $class->credited_sql($start, $end);
3037 Returns an SQL fragment to retreive the net amount (charged minus credited).
3042 my ($class, $start, $end) = @_;
3043 'charged - '. $class->credited_sql($start, $end);
3048 Returns an SQL fragment to retreive the amount paid against this invoice.
3053 my ($class, $start, $end) = @_;
3054 $start &&= "AND cust_bill_pay._date <= $start";
3055 $end &&= "AND cust_bill_pay._date > $end";
3056 $start = '' unless defined($start);
3057 $end = '' unless defined($end);
3058 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3059 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3064 Returns an SQL fragment to retreive the amount credited against this invoice.
3069 my ($class, $start, $end) = @_;
3070 $start &&= "AND cust_credit_bill._date <= $start";
3071 $end &&= "AND cust_credit_bill._date > $end";
3072 $start = '' unless defined($start);
3073 $end = '' unless defined($end);
3074 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3075 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3080 Returns an SQL fragment to retrieve the due date of an invoice.
3081 Currently only supported on PostgreSQL.
3086 die "don't use: doesn't account for agent-specific invoice_default_terms";
3088 #we're passed a $conf but not a specific customer (that's in the query), so
3089 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3090 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3093 my $conf = new FS::Conf;
3097 cust_bill.invoice_terms,
3098 cust_main.invoice_terms,
3099 \''.($conf->config('invoice_default_terms') || '').'\'
3100 ), E\'Net (\\\\d+)\'
3102 ) * 86400 + cust_bill._date'
3113 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3114 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base