2 use base qw( FS::cust_bill::Search FS::Template_Mixin
3 FS::cust_main_Mixin FS::Record
7 use vars qw( $DEBUG $me );
9 use Fcntl qw(:flock); #for spool_csv
11 use List::Util qw(min max sum);
15 use Storable qw( freeze thaw );
17 use FS::UID qw( datasrc );
18 use FS::Misc qw( send_fax do_print );
19 use FS::Record qw( qsearch qsearchs dbh );
20 use FS::cust_statement;
21 use FS::cust_bill_pkg;
22 use FS::cust_bill_pkg_display;
23 use FS::cust_bill_pkg_detail;
27 use FS::cust_credit_bill;
29 use FS::cust_bill_event;
32 use FS::cust_bill_pay;
33 use FS::part_bill_event;
36 use FS::cust_bill_batch;
37 use FS::cust_bill_pay_pkg;
38 use FS::cust_credit_bill_pkg;
39 use FS::discount_plan;
40 use FS::cust_bill_void;
44 $me = '[FS::cust_bill]';
48 FS::cust_bill - Object methods for cust_bill records
54 $record = new FS::cust_bill \%hash;
55 $record = new FS::cust_bill { 'column' => 'value' };
57 $error = $record->insert;
59 $error = $new_record->replace($old_record);
61 $error = $record->delete;
63 $error = $record->check;
65 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
67 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
69 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
71 @cust_pay_objects = $cust_bill->cust_pay;
73 $tax_amount = $record->tax;
75 @lines = $cust_bill->print_text;
76 @lines = $cust_bill->print_text('time' => $time);
80 An FS::cust_bill object represents an invoice; a declaration that a customer
81 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
82 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
83 following fields are currently supported:
89 =item invnum - primary key (assigned automatically for new invoices)
91 =item custnum - customer (see L<FS::cust_main>)
93 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
94 L<Time::Local> and L<Date::Parse> for conversion functions.
96 =item charged - amount of this invoice
98 =item invoice_terms - optional terms override for this specific invoice
106 =item billing_balance - the customer's balance immediately before generating
107 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
108 to determine the customer's balance at a specific time.
110 =item previous_balance - the customer's balance immediately after generating
111 the invoice before this one. DEPRECATED.
113 =item printed - formerly used to track the number of times an invoice had
114 been printed; no longer used.
122 =item closed - books closed flag, empty or `Y'
124 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
126 =item agent_invid - legacy invoice number
128 =item promised_date - customer promised payment date, for collection
130 =item pending - invoice is still being generated, empty or 'Y'
140 Creates a new invoice. To add the invoice to the database, see L<"insert">.
141 Invoices are normally created by calling the bill method of a customer object
142 (see L<FS::cust_main>).
146 sub table { 'cust_bill'; }
148 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
149 # (except email_subject and invnum_date_pretty)
152 $self->conf->config('notice_name') || 'Invoice'
155 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
156 sub cust_unlinked_msg {
158 "WARNING: can't find cust_main.custnum ". $self->custnum.
159 ' (cust_bill.invnum '. $self->invnum. ')';
164 Adds this invoice to the database ("Posts" the invoice). If there is an error,
165 returns the error, otherwise returns false.
171 warn "$me insert called\n" if $DEBUG;
173 local $SIG{HUP} = 'IGNORE';
174 local $SIG{INT} = 'IGNORE';
175 local $SIG{QUIT} = 'IGNORE';
176 local $SIG{TERM} = 'IGNORE';
177 local $SIG{TSTP} = 'IGNORE';
178 local $SIG{PIPE} = 'IGNORE';
180 my $oldAutoCommit = $FS::UID::AutoCommit;
181 local $FS::UID::AutoCommit = 0;
184 my $error = $self->SUPER::insert;
186 $dbh->rollback if $oldAutoCommit;
190 if ( $self->get('cust_bill_pkg') ) {
191 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
192 $cust_bill_pkg->invnum($self->invnum);
193 my $error = $cust_bill_pkg->insert;
195 $dbh->rollback if $oldAutoCommit;
196 return "can't create invoice line item: $error";
201 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
208 Voids this invoice: deletes the invoice and adds a record of the voided invoice
209 to the FS::cust_bill_void table (and related tables starting from
210 FS::cust_bill_pkg_void).
216 my $reason = scalar(@_) ? shift : '';
218 local $SIG{HUP} = 'IGNORE';
219 local $SIG{INT} = 'IGNORE';
220 local $SIG{QUIT} = 'IGNORE';
221 local $SIG{TERM} = 'IGNORE';
222 local $SIG{TSTP} = 'IGNORE';
223 local $SIG{PIPE} = 'IGNORE';
225 my $oldAutoCommit = $FS::UID::AutoCommit;
226 local $FS::UID::AutoCommit = 0;
229 my $cust_bill_void = new FS::cust_bill_void ( {
230 map { $_ => $self->get($_) } $self->fields
232 $cust_bill_void->reason($reason);
233 my $error = $cust_bill_void->insert;
235 $dbh->rollback if $oldAutoCommit;
239 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
240 my $error = $cust_bill_pkg->void($reason);
242 $dbh->rollback if $oldAutoCommit;
247 $error = $self->delete;
249 $dbh->rollback if $oldAutoCommit;
253 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
261 This method now works but you probably shouldn't use it. Instead, apply a
262 credit against the invoice, or use the new void method.
264 Using this method to delete invoices outright is really, really bad. There
265 would be no record you ever posted this invoice, and there are no check to
266 make sure charged = 0 or that there are no associated cust_bill_pkg records.
268 Really, don't use it.
274 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
276 local $SIG{HUP} = 'IGNORE';
277 local $SIG{INT} = 'IGNORE';
278 local $SIG{QUIT} = 'IGNORE';
279 local $SIG{TERM} = 'IGNORE';
280 local $SIG{TSTP} = 'IGNORE';
281 local $SIG{PIPE} = 'IGNORE';
283 my $oldAutoCommit = $FS::UID::AutoCommit;
284 local $FS::UID::AutoCommit = 0;
287 foreach my $table (qw(
298 foreach my $linked ( $self->$table() ) {
299 my $error = $linked->delete;
301 $dbh->rollback if $oldAutoCommit;
308 my $error = $self->SUPER::delete(@_);
310 $dbh->rollback if $oldAutoCommit;
314 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
320 =item replace [ OLD_RECORD ]
322 You can, but probably shouldn't modify invoices...
324 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
325 supplied, replaces this record. If there is an error, returns the error,
326 otherwise returns false.
330 #replace can be inherited from Record.pm
332 # replace_check is now the preferred way to #implement replace data checks
333 # (so $object->replace() works without an argument)
336 my( $new, $old ) = ( shift, shift );
337 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
338 #return "Can't change _date!" unless $old->_date eq $new->_date;
339 return "Can't change _date" unless $old->_date == $new->_date;
340 return "Can't change charged" unless $old->charged == $new->charged
341 || $old->pending eq 'Y'
342 || $old->charged == 0
343 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
349 =item add_cc_surcharge
355 sub add_cc_surcharge {
356 my ($self, $pkgnum, $amount) = (shift, shift, shift);
359 my $cust_bill_pkg = new FS::cust_bill_pkg({
360 'invnum' => $self->invnum,
364 $error = $cust_bill_pkg->insert;
365 return $error if $error;
367 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
368 $self->charged($self->charged+$amount);
369 $error = $self->replace;
370 return $error if $error;
372 $self->apply_payments_and_credits;
378 Checks all fields to make sure this is a valid invoice. If there is an error,
379 returns the error, otherwise returns false. Called by the insert and replace
388 $self->ut_numbern('invnum')
389 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
390 || $self->ut_numbern('_date')
391 || $self->ut_money('charged')
392 || $self->ut_numbern('printed')
393 || $self->ut_enum('closed', [ '', 'Y' ])
394 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
395 || $self->ut_numbern('agent_invid') #varchar?
396 || $self->ut_flag('pending')
398 return $error if $error;
400 $self->_date(time) unless $self->_date;
402 $self->printed(0) if $self->printed eq '';
409 Returns the displayed invoice number for this invoice: agent_invid if
410 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
416 if ( $self->agent_invid
417 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
418 return $self->agent_invid;
420 return $self->invnum;
426 Returns the customer's last invoice before this one.
432 if ( !$self->get('previous_bill') ) {
433 $self->set('previous_bill', qsearchs({
434 'table' => 'cust_bill',
435 'hashref' => { 'custnum' => $self->custnum,
436 '_date' => { op=>'<', value=>$self->_date } },
437 'order_by' => 'ORDER BY _date DESC LIMIT 1',
440 $self->get('previous_bill');
445 Returns a list consisting of the total previous balance for this customer,
446 followed by the previous outstanding invoices (as FS::cust_bill objects also).
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; }
464 =item enable_previous
466 Whether to show the 'Previous Charges' section when printing this invoice.
467 The negation of the 'disable_previous_balance' config setting.
471 sub enable_previous {
473 my $agentnum = $self->cust_main->agentnum;
474 !$self->conf->exists('disable_previous_balance', $agentnum);
479 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
486 { 'table' => 'cust_bill_pkg',
487 'hashref' => { 'invnum' => $self->invnum },
488 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
489 # the AUTLOADED FK search. or should
490 # that default to ORDER by the pkey?
495 =item cust_bill_pkg_pkgnum PKGNUM
497 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
502 sub cust_bill_pkg_pkgnum {
503 my( $self, $pkgnum ) = @_;
505 { 'table' => 'cust_bill_pkg',
506 'hashref' => { 'invnum' => $self->invnum,
509 'order_by' => 'ORDER BY billpkgnum',
516 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
523 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
524 $self->cust_bill_pkg;
526 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
531 Returns true if any of the packages (or their definitions) corresponding to the
532 line items for this invoice have the no_auto flag set.
538 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
541 =item open_cust_bill_pkg
543 Returns the open line items for this invoice.
545 Note that cust_bill_pkg with both setup and recur fees are returned as two
546 separate line items, each with only one fee.
550 # modeled after cust_main::open_cust_bill
551 sub open_cust_bill_pkg {
554 # grep { $_->owed > 0 } $self->cust_bill_pkg
556 my %other = ( 'recur' => 'setup',
557 'setup' => 'recur', );
559 foreach my $field ( qw( recur setup )) {
560 push @open, map { $_->set( $other{$field}, 0 ); $_; }
561 grep { $_->owed($field) > 0 }
562 $self->cust_bill_pkg;
568 =item cust_bill_event
570 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
574 sub cust_bill_event {
576 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
579 =item num_cust_bill_event
581 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
585 sub num_cust_bill_event {
588 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
589 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
590 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
591 $sth->fetchrow_arrayref->[0];
596 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
600 #false laziness w/cust_pkg.pm
604 'table' => 'cust_event',
605 'addl_from' => 'JOIN part_event USING ( eventpart )',
606 'hashref' => { 'tablenum' => $self->invnum },
607 'extra_sql' => " AND eventtable = 'cust_bill' ",
613 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
617 #false laziness w/cust_pkg.pm
621 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
622 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
623 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
624 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
625 $sth->fetchrow_arrayref->[0];
630 Returns the customer (see L<FS::cust_main>) for this invoice.
634 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice
636 Returns a list: an empty list on success or a list of errors.
643 grep { $_->suspend(@_) }
644 grep {! $_->getfield('cancel') }
649 =item cust_suspend_if_balance_over AMOUNT
651 Suspends the customer associated with this invoice if the total amount owed on
652 this invoice and all older invoices is greater than the specified amount.
654 Returns a list: an empty list on success or a list of errors.
658 sub cust_suspend_if_balance_over {
659 my( $self, $amount ) = ( shift, shift );
660 my $cust_main = $self->cust_main;
661 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
664 $cust_main->suspend(@_);
670 Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options
675 my( $self, %opt ) = @_;
677 warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
678 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
681 return ( 'Access denied' )
682 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
684 my @pkgs = $self->cust_pkg;
686 if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
688 my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
689 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
694 map { $_->cancel(%opt) }
695 grep { ! $_->getfield('cancel') }
701 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
707 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
708 sort { $a->_date <=> $b->_date }
709 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
714 =item cust_credit_bill
716 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
722 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
723 sort { $a->_date <=> $b->_date }
724 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
728 sub cust_credit_bill {
729 shift->cust_credited(@_);
732 #=item cust_bill_pay_pkgnum PKGNUM
734 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
735 #with matching pkgnum.
739 #sub cust_bill_pay_pkgnum {
740 # my( $self, $pkgnum ) = @_;
741 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
742 # sort { $a->_date <=> $b->_date }
743 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
744 # 'pkgnum' => $pkgnum,
749 =item cust_bill_pay_pkg PKGNUM
751 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
752 applied against the matching pkgnum.
756 sub cust_bill_pay_pkg {
757 my( $self, $pkgnum ) = @_;
760 'select' => 'cust_bill_pay_pkg.*',
761 'table' => 'cust_bill_pay_pkg',
762 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
763 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
764 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
765 " AND cust_bill_pkg.pkgnum = $pkgnum",
770 #=item cust_credited_pkgnum PKGNUM
772 #=item cust_credit_bill_pkgnum PKGNUM
774 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
775 #with matching pkgnum.
779 #sub cust_credited_pkgnum {
780 # my( $self, $pkgnum ) = @_;
781 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
782 # sort { $a->_date <=> $b->_date }
783 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
784 # 'pkgnum' => $pkgnum,
789 #sub cust_credit_bill_pkgnum {
790 # shift->cust_credited_pkgnum(@_);
793 =item cust_credit_bill_pkg PKGNUM
795 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
796 applied against the matching pkgnum.
800 sub cust_credit_bill_pkg {
801 my( $self, $pkgnum ) = @_;
804 'select' => 'cust_credit_bill_pkg.*',
805 'table' => 'cust_credit_bill_pkg',
806 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
807 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
808 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
809 " AND cust_bill_pkg.pkgnum = $pkgnum",
814 =item cust_bill_batch
816 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
820 sub cust_bill_batch {
822 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
827 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
828 hash keyed by term length.
834 FS::discount_plan->all($self);
839 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
846 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
848 foreach (@taxlines) { $total += $_->setup; }
854 Returns the amount owed (still outstanding) on this invoice, which is charged
855 minus all payment applications (see L<FS::cust_bill_pay>) and credit
856 applications (see L<FS::cust_credit_bill>).
862 my $balance = $self->charged;
863 $balance -= $_->amount foreach ( $self->cust_bill_pay );
864 $balance -= $_->amount foreach ( $self->cust_credited );
865 $balance = sprintf( "%.2f", $balance);
866 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
871 my( $self, $pkgnum ) = @_;
873 #my $balance = $self->charged;
875 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
877 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
878 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
880 $balance = sprintf( "%.2f", $balance);
881 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
887 Returns true if this invoice should be hidden. See the
888 selfservice-hide_invoices-taxclass configuraiton setting.
894 my $conf = $self->conf;
895 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
897 my @cust_bill_pkg = $self->cust_bill_pkg;
898 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
899 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
902 =item apply_payments_and_credits [ OPTION => VALUE ... ]
904 Applies unapplied payments and credits to this invoice.
906 A hash of optional arguments may be passed. Currently "manual" is supported.
907 If true, a payment receipt is sent instead of a statement when
908 'payment_receipt_email' configuration option is set.
910 If there is an error, returns the error, otherwise returns false.
914 sub apply_payments_and_credits {
915 my( $self, %options ) = @_;
916 my $conf = $self->conf;
918 local $SIG{HUP} = 'IGNORE';
919 local $SIG{INT} = 'IGNORE';
920 local $SIG{QUIT} = 'IGNORE';
921 local $SIG{TERM} = 'IGNORE';
922 local $SIG{TSTP} = 'IGNORE';
923 local $SIG{PIPE} = 'IGNORE';
925 my $oldAutoCommit = $FS::UID::AutoCommit;
926 local $FS::UID::AutoCommit = 0;
929 $self->select_for_update; #mutex
931 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
932 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
934 if ( $conf->exists('pkg-balances') ) {
935 # limit @payments & @credits to those w/ a pkgnum grepped from $self
936 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
937 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
938 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
941 while ( $self->owed > 0 and ( @payments || @credits ) ) {
944 if ( @payments && @credits ) {
946 #decide which goes first by weight of top (unapplied) line item
948 my @open_lineitems = $self->open_cust_bill_pkg;
951 max( map { $_->part_pkg->pay_weight || 0 }
956 my $max_credit_weight =
957 max( map { $_->part_pkg->credit_weight || 0 }
963 #if both are the same... payments first? it has to be something
964 if ( $max_pay_weight >= $max_credit_weight ) {
970 } elsif ( @payments ) {
972 } elsif ( @credits ) {
975 die "guru meditation #12 and 35";
979 if ( $app eq 'pay' ) {
981 my $payment = shift @payments;
982 $unapp_amount = $payment->unapplied;
983 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
984 $app->pkgnum( $payment->pkgnum )
985 if $conf->exists('pkg-balances') && $payment->pkgnum;
987 } elsif ( $app eq 'credit' ) {
989 my $credit = shift @credits;
990 $unapp_amount = $credit->credited;
991 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
992 $app->pkgnum( $credit->pkgnum )
993 if $conf->exists('pkg-balances') && $credit->pkgnum;
996 die "guru meditation #12 and 35";
1000 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1001 warn "owed_pkgnum ". $app->pkgnum;
1002 $owed = $self->owed_pkgnum($app->pkgnum);
1004 $owed = $self->owed;
1006 next unless $owed > 0;
1008 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1009 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1011 $app->invnum( $self->invnum );
1013 my $error = $app->insert(%options);
1015 $dbh->rollback if $oldAutoCommit;
1016 return "Error inserting ". $app->table. " record: $error";
1018 die $error if $error;
1022 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1029 Sends this invoice to the destinations configured for this customer: sends
1030 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1032 Options can be passed as a hashref. Positional parameters are no longer
1035 I<template>: a suffix for alternate invoices
1037 I<agentnum>: obsolete, now does nothing.
1039 I<from> overrides the default email invoice From: address.
1041 I<amount>: obsolete, does nothing
1043 I<notice_name> overrides "Invoice" as the name of the sent document
1044 (templates from 10/2009 or newer required).
1046 I<lpr> overrides the system 'lpr' option as the command to print a document
1047 from standard input.
1053 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1054 my $conf = $self->conf;
1056 my $cust_main = $self->cust_main;
1058 my @invoicing_list = $cust_main->invoicing_list;
1061 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1062 && ! $cust_main->invoice_noemail;
1065 if grep { $_ eq 'POST' } @invoicing_list; #postal
1067 #this has never been used post-$ORIGINAL_ISP afaik
1068 $self->fax_invoice($opt)
1069 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1077 my $opt = shift || {};
1078 if ($opt and !ref($opt)) {
1079 die ref($self). '->email called with positional parameters';
1082 my $conf = $self->conf;
1084 my $from = delete $opt->{from};
1086 # this is where we set the From: address
1087 $from ||= $self->_agent_invoice_from || #XXX should go away
1088 $conf->config('invoice_from_name', $self->cust_main->agentnum ) ?
1089 $conf->config('invoice_from_name', $self->cust_main->agentnum ) . ' <' .
1090 $conf->config('invoice_from', $self->cust_main->agentnum ) . '>' :
1091 $conf->config('invoice_from', $self->cust_main->agentnum );
1093 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1095 if ( ! @invoicing_list ) { #no recipients
1096 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1097 die 'No recipients for customer #'. $self->custnum;
1099 #default: better to notify this person than silence
1100 @invoicing_list = ($from);
1104 $self->SUPER::email( {
1106 'to' => \@invoicing_list,
1112 #this stays here for now because its explicitly used as
1113 # FS::cust_bill::queueable_email
1114 sub queueable_email {
1117 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1118 or die "invalid invoice number: " . $opt{invnum};
1120 my %args = map {$_ => $opt{$_}}
1122 qw( from notice_name no_coupon template );
1124 my $error = $self->email( \%args );
1125 die $error if $error;
1131 my $conf = $self->conf;
1133 #my $template = scalar(@_) ? shift : '';
1136 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1139 my $cust_main = $self->cust_main;
1140 my $name = $cust_main->name;
1141 my $name_short = $cust_main->name_short;
1142 my $invoice_number = $self->invnum;
1143 my $invoice_date = $self->_date_pretty;
1145 eval qq("$subject");
1148 =item lpr_data HASHREF
1150 Returns the postscript or plaintext for this invoice as an arrayref.
1152 Options must be passed as a hashref. Positional parameters are no longer
1155 I<template>, if specified, is the name of a suffix for alternate invoices.
1157 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1163 my $conf = $self->conf;
1164 my $opt = shift || {};
1165 if ($opt and !ref($opt)) {
1166 # nobody does this anyway
1167 die "FS::cust_bill::lpr_data called with positional parameters";
1170 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1171 [ $self->$method( $opt ) ];
1176 Prints this invoice.
1178 Options must be passed as a hashref.
1180 I<template>, if specified, is the name of a suffix for alternate invoices.
1182 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1188 return if $self->hide;
1189 my $conf = $self->conf;
1190 my $opt = shift || {};
1191 if ($opt and !ref($opt)) {
1192 die "FS::cust_bill::print called with positional parameters";
1195 my $lpr = delete $opt->{lpr};
1196 if($conf->exists('invoice_print_pdf')) {
1197 # Add the invoice to the current batch.
1198 $self->batch_invoice($opt);
1202 $self->lpr_data($opt),
1203 'agentnum' => $self->cust_main->agentnum,
1209 =item fax_invoice HASHREF
1213 Options must be passed as a hashref.
1215 I<template>, if specified, is the name of a suffix for alternate invoices.
1217 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1223 return if $self->hide;
1224 my $conf = $self->conf;
1225 my $opt = shift || {};
1226 if ($opt and !ref($opt)) {
1227 die "FS::cust_bill::fax_invoice called with positional parameters";
1230 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1231 unless $conf->exists('invoice_latex');
1233 my $dialstring = $self->cust_main->getfield('fax');
1236 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1237 'dialstring' => $dialstring,
1239 die $error if $error;
1243 =item batch_invoice [ HASHREF ]
1245 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1246 isn't an open batch, one will be created.
1248 HASHREF may contain any options to be passed to C<print_pdf>.
1253 my ($self, $opt) = @_;
1254 my $bill_batch = $self->get_open_bill_batch;
1255 my $cust_bill_batch = FS::cust_bill_batch->new({
1256 batchnum => $bill_batch->batchnum,
1257 invnum => $self->invnum,
1259 return $cust_bill_batch->insert($opt);
1262 =item get_open_batch
1264 Returns the currently open batch as an FS::bill_batch object, creating a new
1265 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1270 sub get_open_bill_batch {
1272 my $conf = $self->conf;
1273 my $hashref = { status => 'O' };
1274 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1275 ? $self->cust_main->agentnum
1277 my $batch = qsearchs('bill_batch', $hashref);
1278 return $batch if $batch;
1279 $batch = FS::bill_batch->new($hashref);
1280 my $error = $batch->insert;
1281 die $error if $error;
1285 =item ftp_invoice [ TEMPLATENAME ]
1287 Sends this invoice data via FTP.
1289 TEMPLATENAME is unused?
1295 my $conf = $self->conf;
1296 my $template = scalar(@_) ? shift : '';
1299 'protocol' => 'ftp',
1300 'server' => $conf->config('cust_bill-ftpserver'),
1301 'username' => $conf->config('cust_bill-ftpusername'),
1302 'password' => $conf->config('cust_bill-ftppassword'),
1303 'dir' => $conf->config('cust_bill-ftpdir'),
1304 'format' => $conf->config('cust_bill-ftpformat'),
1308 =item spool_invoice [ TEMPLATENAME ]
1310 Spools this invoice data (see L<FS::spool_csv>)
1312 TEMPLATENAME is unused?
1318 my $conf = $self->conf;
1319 my $template = scalar(@_) ? shift : '';
1322 'format' => $conf->config('cust_bill-spoolformat'),
1323 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1327 =item send_csv OPTION => VALUE, ...
1329 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1333 protocol - currently only "ftp"
1339 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1340 and YYMMDDHHMMSS is a timestamp.
1342 See L</print_csv> for a description of the output format.
1347 my($self, %opt) = @_;
1351 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1352 mkdir $spooldir, 0700 unless -d $spooldir;
1354 # don't localize dates here, they're a defined format
1355 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1356 my $file = "$spooldir/$tracctnum.csv";
1358 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1360 open(CSV, ">$file") or die "can't open $file: $!";
1368 if ( $opt{protocol} eq 'ftp' ) {
1369 eval "use Net::FTP;";
1371 $net = Net::FTP->new($opt{server}) or die @$;
1373 die "unknown protocol: $opt{protocol}";
1376 $net->login( $opt{username}, $opt{password} )
1377 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1379 $net->binary or die "can't set binary mode";
1381 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1383 $net->put($file) or die "can't put $file: $!";
1393 Spools CSV invoice data.
1399 =item format - any of FS::Misc::::Invoicing::spool_formats
1401 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1402 customer has the corresponding invoice destinations set (see
1403 L<FS::cust_main_invoice>).
1405 =item agent_spools - if set to a true value, will spool to per-agent files
1406 rather than a single global file
1408 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1409 append to that spool. L<FS::Cron::upload> will then send the spool file to
1412 =item balanceover - if set, only spools the invoice if the total amount owed on
1413 this invoice and all older invoices is greater than the specified amount.
1415 =item time - the "current time". Controls the printing of past due messages
1423 my($self, %opt) = @_;
1425 my $time = $opt{'time'} || time;
1426 my $cust_main = $self->cust_main;
1428 if ( $opt{'dest'} ) {
1429 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1430 $cust_main->invoicing_list;
1431 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1432 || ! keys %invoicing_list;
1435 if ( $opt{'balanceover'} ) {
1437 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1440 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1441 mkdir $spooldir, 0700 unless -d $spooldir;
1443 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1446 if ( $opt{'agent_spools'} ) {
1447 $file = 'agentnum'.$cust_main->agentnum;
1452 if ( $opt{'upload_targetnum'} ) {
1453 $spooldir .= '/target'.$opt{'upload_targetnum'};
1454 mkdir $spooldir, 0700 unless -d $spooldir;
1455 } # otherwise it just goes into export.xxx/cust_bill
1457 if ( lc($opt{'format'}) eq 'billco' ) {
1461 $file = "$spooldir/$file.csv";
1463 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1465 open(CSV, ">>$file") or die "can't open $file: $!";
1466 flock(CSV, LOCK_EX);
1471 if ( lc($opt{'format'}) eq 'billco' ) {
1473 flock(CSV, LOCK_UN);
1476 $file =~ s/-header.csv$/-detail.csv/;
1478 open(CSV,">>$file") or die "can't open $file: $!";
1479 flock(CSV, LOCK_EX);
1483 print CSV $detail if defined($detail);
1485 flock(CSV, LOCK_UN);
1492 =item print_csv OPTION => VALUE, ...
1494 Returns CSV data for this invoice.
1498 format - 'default', 'billco', 'oneline', 'bridgestone'
1500 Returns a list consisting of two scalars. The first is a single line of CSV
1501 header information for this invoice. The second is one or more lines of CSV
1502 detail information for this invoice.
1504 If I<format> is not specified or "default", the fields of the CSV file are as
1507 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1508 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1512 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1514 B<record_type> is C<cust_bill> for the initial header line only. The
1515 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1516 fields are filled in.
1518 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1519 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1522 =item invnum - invoice number
1524 =item custnum - customer number
1526 =item _date - invoice date
1528 =item charged - total invoice amount
1530 =item first - customer first name
1532 =item last - customer first name
1534 =item company - company name
1536 =item address1 - address line 1
1538 =item address2 - address line 1
1548 =item pkg - line item description
1550 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1552 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1554 =item sdate - start date for recurring fee
1556 =item edate - end date for recurring fee
1560 If I<format> is "billco", the fields of the header CSV file are as follows:
1562 +-------------------------------------------------------------------+
1563 | FORMAT HEADER FILE |
1564 |-------------------------------------------------------------------|
1565 | Field | Description | Name | Type | Width |
1566 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1567 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1568 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1569 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1570 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1571 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1572 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1573 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1574 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1575 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1576 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1577 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1578 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1579 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1580 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1581 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1582 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1583 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1584 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1585 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1586 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1587 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1588 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1589 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1590 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1591 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1592 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1593 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1594 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1595 +-------+-------------------------------+------------+------+-------+
1597 If I<format> is "billco", the fields of the detail CSV file are as follows:
1599 FORMAT FOR DETAIL FILE
1601 Field | Description | Name | Type | Width
1602 1 | N/A-Leave Empty | RC | CHAR | 2
1603 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1604 3 | Account Number | TRACCTNUM | CHAR | 15
1605 4 | Invoice Number | TRINVOICE | CHAR | 15
1606 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1607 6 | Transaction Detail | DETAILS | CHAR | 100
1608 7 | Amount | AMT | NUM* | 9
1609 8 | Line Format Control** | LNCTRL | CHAR | 2
1610 9 | Grouping Code | GROUP | CHAR | 2
1611 10 | User Defined | ACCT CODE | CHAR | 15
1613 If format is 'oneline', there is no detail file. Each invoice has a
1614 header line only, with the fields:
1616 Agent number, agent name, customer number, first name, last name, address
1617 line 1, address line 2, city, state, zip, invoice date, invoice number,
1618 amount charged, amount due, previous balance, due date.
1620 and then, for each line item, three columns containing the package number,
1621 description, and amount.
1623 If format is 'bridgestone', there is no detail file. Each invoice has a
1624 header line with the following fields in a fixed-width format:
1626 Customer number (in display format), date, name (first last), company,
1627 address 1, address 2, city, state, zip.
1629 This is a mailing list format, and has no per-invoice fields. To avoid
1630 sending redundant notices, the spooling event should have a "once" or
1631 "once_percust_every" condition.
1636 my($self, %opt) = @_;
1638 eval "use Text::CSV_XS";
1641 my $cust_main = $self->cust_main;
1643 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1644 my $format = lc($opt{'format'});
1646 my $time = $opt{'time'} || time;
1648 my $tracctnum = ''; #leaking out from billco-specific sections :/
1649 if ( $format eq 'billco' ) {
1652 $self->conf->config('billco-account_num', $cust_main->agentnum);
1654 $tracctnum = $account_num eq 'display_custnum'
1655 ? $cust_main->display_custnum
1656 : $opt{'tracctnum'};
1659 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1661 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1663 my( $previous_balance, @unused ) = $self->previous; #previous balance
1665 my $pmt_cr_applied = 0;
1666 $pmt_cr_applied += $_->{'amount'}
1667 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1669 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1672 '', # 1 | N/A-Leave Empty CHAR 2
1673 '', # 2 | N/A-Leave Empty CHAR 15
1674 $tracctnum, # 3 | Transaction Account No CHAR 15
1675 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1676 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1677 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1678 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1679 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1680 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1681 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1682 '', # 10 | Ancillary Billing Information CHAR 30
1683 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1684 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1687 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1690 $duedate, # 14 | Bill Due Date CHAR 10
1692 $previous_balance, # 15 | Previous Balance NUM* 9
1693 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1694 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1695 $totaldue, # 18 | Total Amt Due NUM* 9
1696 $totaldue, # 19 | Total Amt Due NUM* 9
1697 '', # 20 | 30 Day Aging NUM* 9
1698 '', # 21 | 60 Day Aging NUM* 9
1699 '', # 22 | 90 Day Aging NUM* 9
1700 'N', # 23 | Y/N CHAR 1
1701 '', # 24 | Remittance automation CHAR 100
1702 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1703 $self->custnum, # 26 | Customer Reference Number CHAR 15
1704 '0', # 27 | Federal Tax*** NUM* 9
1705 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1706 '0', # 29 | Other Taxes & Fees*** NUM* 9
1709 } elsif ( $format eq 'oneline' ) { #name
1711 my ($previous_balance) = $self->previous;
1712 $previous_balance = sprintf('%.2f', $previous_balance);
1713 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1719 $self->_items_pkg, #_items_nontax? no sections or anything
1724 $cust_main->agentnum,
1725 $cust_main->agent->agent,
1729 $cust_main->company,
1730 $cust_main->address1,
1731 $cust_main->address2,
1737 time2str("%x", $self->_date),
1742 $self->due_date2str("%x"),
1747 } elsif ( $format eq 'bridgestone' ) {
1749 # bypass the CSV stuff and just return this
1750 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1751 my $zip = $cust_main->zip;
1753 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1757 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1759 $cust_main->display_custnum,
1761 uc(substr($cust_main->contact_firstlast,0,30)),
1762 uc(substr($cust_main->company ,0,30)),
1763 uc(substr($cust_main->address1 ,0,30)),
1764 uc(substr($cust_main->address2 ,0,30)),
1765 uc(substr($cust_main->city ,0,20)),
1766 uc($cust_main->state),
1772 } elsif ( $format eq 'ics' ) {
1774 my $bill = $cust_main->bill_location;
1775 my $zip = $bill->zip;
1779 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1784 # minor false laziness with print_generic
1785 my ($previous_balance) = $self->previous;
1786 my $balance_due = $self->owed + $previous_balance;
1787 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1788 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1791 if ( $self->due_date and $time >= $self->due_date ) {
1792 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1796 my $header = sprintf(
1797 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1798 $cust_main->display_custnum, #BID
1799 uc($cust_main->first), #FNAME
1800 uc($cust_main->last), #LNAME
1801 '00', #BATCH, should this ever be anything else?
1802 uc($cust_main->company), #COMP
1803 uc($bill->address1), #STREET1
1804 uc($bill->address2), #STREET2
1805 uc($bill->city), #CITY
1806 uc($bill->state), #STATE
1809 time2str('%Y%m%d', $self->_date), #BILL_DATE
1810 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1811 ( map {sprintf('%0.2f', $_)}
1812 $balance_due, #AMNT_DUE
1813 $previous_balance, #PREV_BAL
1814 $payment_total, #PYMT_RCVD
1815 $credit_total, #CREDITS
1816 $previous_balance, #BEG_BAL--is this correct?
1817 $self->charged, #NEW_CHRG
1820 $past_due, #PAST_MSG
1824 my %svc_class = ('' => ''); # maybe cache this more persistently?
1826 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1828 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1829 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1833 my @dates = ( $self->_date, undef );
1834 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1835 $dates[1] = $prev->sdate; #questionable
1838 # generate an 01 detail for each service
1839 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1840 foreach my $cust_svc ( @svcs ) {
1841 $show_pkgnum = ''; # hide it if we're showing svcnums
1843 my $svcpart = $cust_svc->svcpart;
1844 if (!exists($svc_class{$svcpart})) {
1845 my $classnum = $cust_svc->part_svc->classnum;
1846 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1848 $svc_class{$svcpart} = $part_svc_class ?
1849 $part_svc_class->classname :
1853 my @h_label = $cust_svc->label(@dates, 'I');
1854 push @details, sprintf('01%-9s%-20s%-47s',
1856 $svc_class{$svcpart},
1859 } #foreach $cust_svc
1862 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1863 if ($cust_bill_pkg->recur > 0) {
1864 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1865 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1867 push @details, sprintf('02%-6s%-60s%-10s',
1870 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1872 } #foreach $cust_bill_pkg
1874 # Tag this row so that we know whether this is one page (1), two pages
1875 # (2), # or "big" (B). The tag will be stripped off before uploading.
1876 if ( scalar(@details) < 12 ) {
1878 } elsif ( scalar(@details) < 58 ) {
1884 return join('', $header, @details, "\n");
1892 time2str("%x", $self->_date),
1893 sprintf("%.2f", $self->charged),
1894 ( map { $cust_main->getfield($_) }
1895 qw( first last company address1 address2 city state zip country ) ),
1897 ) or die "can't create csv";
1900 my $header = $csv->string. "\n";
1903 if ( lc($opt{'format'}) eq 'billco' ) {
1906 foreach my $item ( $self->_items_pkg ) {
1909 '', # 1 | N/A-Leave Empty CHAR 2
1910 '', # 2 | N/A-Leave Empty CHAR 15
1911 $tracctnum, # 3 | Account Number CHAR 15
1912 $self->invnum, # 4 | Invoice Number CHAR 15
1913 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1914 $item->{'description'}, # 6 | Transaction Detail CHAR 100
1915 $item->{'amount'}, # 7 | Amount NUM* 9
1916 '', # 8 | Line Format Control** CHAR 2
1917 '', # 9 | Grouping Code CHAR 2
1918 '', # 10 | User Defined CHAR 15
1921 $detail .= $csv->string. "\n";
1925 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
1931 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1933 my($pkg, $setup, $recur, $sdate, $edate);
1934 if ( $cust_bill_pkg->pkgnum ) {
1936 ($pkg, $setup, $recur, $sdate, $edate) = (
1937 $cust_bill_pkg->part_pkg->pkg,
1938 ( $cust_bill_pkg->setup != 0
1939 ? sprintf("%.2f", $cust_bill_pkg->setup )
1941 ( $cust_bill_pkg->recur != 0
1942 ? sprintf("%.2f", $cust_bill_pkg->recur )
1944 ( $cust_bill_pkg->sdate
1945 ? time2str("%x", $cust_bill_pkg->sdate)
1947 ($cust_bill_pkg->edate
1948 ? time2str("%x", $cust_bill_pkg->edate)
1952 } else { #pkgnum tax
1953 next unless $cust_bill_pkg->setup != 0;
1954 $pkg = $cust_bill_pkg->desc;
1955 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1956 ( $sdate, $edate ) = ( '', '' );
1962 ( map { '' } (1..11) ),
1963 ($pkg, $setup, $recur, $sdate, $edate)
1964 ) or die "can't create csv";
1966 $detail .= $csv->string. "\n";
1972 ( $header, $detail );
1978 Pays this invoice with a compliemntary payment. If there is an error,
1979 returns the error, otherwise returns false.
1985 my $cust_pay = new FS::cust_pay ( {
1986 'invnum' => $self->invnum,
1987 'paid' => $self->owed,
1990 'payinfo' => $self->cust_main->payinfo,
1998 Attempts to pay this invoice with a credit card 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( 'CC', @_ );
2012 Attempts to pay this invoice with an electronic check (ACH) 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( 'ECHECK', @_ );
2026 Attempts to pay this invoice with phone bill (LEC) payment via a
2027 Business::OnlinePayment realtime gateway. See
2028 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2029 for supported processors.
2035 $self->realtime_bop( 'LEC', @_ );
2039 my( $self, $method ) = (shift,shift);
2040 my $conf = $self->conf;
2043 my $cust_main = $self->cust_main;
2044 my $balance = $cust_main->balance;
2045 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2046 $amount = sprintf("%.2f", $amount);
2047 return "not run (balance $balance)" unless $amount > 0;
2049 my $description = 'Internet Services';
2050 if ( $conf->exists('business-onlinepayment-description') ) {
2051 my $dtempl = $conf->config('business-onlinepayment-description');
2053 my $agent_obj = $cust_main->agent
2054 or die "can't retreive agent for $cust_main (agentnum ".
2055 $cust_main->agentnum. ")";
2056 my $agent = $agent_obj->agent;
2057 my $pkgs = join(', ',
2058 map { $_->part_pkg->pkg }
2059 grep { $_->pkgnum } $self->cust_bill_pkg
2061 $description = eval qq("$dtempl");
2064 $cust_main->realtime_bop($method, $amount,
2065 'description' => $description,
2066 'invnum' => $self->invnum,
2067 #this didn't do what we want, it just calls apply_payments_and_credits
2069 'apply_to_invoice' => 1,
2072 #this changes application behavior: auto payments
2073 #triggered against a specific invoice are now applied
2074 #to that invoice instead of oldest open.
2080 =item batch_card OPTION => VALUE...
2082 Adds a payment for this invoice to the pending credit card batch (see
2083 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2084 runs the payment using a realtime gateway.
2089 my ($self, %options) = @_;
2090 my $cust_main = $self->cust_main;
2092 $options{invnum} = $self->invnum;
2094 $cust_main->batch_card(%options);
2097 sub _agent_template {
2099 $self->cust_main->agent_template;
2102 sub _agent_invoice_from {
2104 $self->cust_main->agent_invoice_from;
2107 =item invoice_barcode DIR_OR_FALSE
2109 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2110 it is taken as the temp directory where the PNG file will be generated and the
2111 PNG file name is returned. Otherwise, the PNG image itself is returned.
2115 sub invoice_barcode {
2116 my ($self, $dir) = (shift,shift);
2118 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2119 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2120 my $gd = $gdbar->plot(Height => 30);
2123 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2127 ) or die "can't open temp file: $!\n";
2128 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2129 my $png_file = $bh->filename;
2136 =item invnum_date_pretty
2138 Returns a string with the invoice number and date, for example:
2139 "Invoice #54 (3/20/2008)".
2141 Intended for back-end context, with regard to translation and date formatting.
2145 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2146 # for backend use (and also does the wrong thing, localizing for end customer
2147 # instead of backoffice configured date format)
2148 sub invnum_date_pretty {
2150 #$self->mt('Invoice #').
2151 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2152 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2155 #sub _items_extra_usage_sections {
2157 # my $escape = shift;
2159 # my %sections = ();
2161 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2162 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2164 # next unless $cust_bill_pkg->pkgnum > 0;
2166 # foreach my $section ( keys %usage_class ) {
2168 # my $usage = $cust_bill_pkg->usage($section);
2170 # next unless $usage && $usage > 0;
2172 # $sections{$section} ||= 0;
2173 # $sections{$section} += $usage;
2179 # map { { 'description' => &{$escape}($_),
2180 # 'subtotal' => $sections{$_},
2181 # 'summarized' => '',
2182 # 'tax_section' => '',
2185 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2189 sub _items_extra_usage_sections {
2191 my $conf = $self->conf;
2199 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2201 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2202 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2203 next unless $cust_bill_pkg->pkgnum > 0;
2205 foreach my $classnum ( keys %usage_class ) {
2206 my $section = $usage_class{$classnum}->classname;
2207 $classnums{$section} = $classnum;
2209 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2210 my $amount = $detail->amount;
2211 next unless $amount && $amount > 0;
2213 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2214 $sections{$section}{amount} += $amount; #subtotal
2215 $sections{$section}{calls}++;
2216 $sections{$section}{duration} += $detail->duration;
2218 my $desc = $detail->regionname;
2219 my $description = $desc;
2220 $description = substr($desc, 0, $maxlength). '...'
2221 if $format eq 'latex' && length($desc) > $maxlength;
2223 $lines{$section}{$desc} ||= {
2224 description => &{$escape}($description),
2225 #pkgpart => $part_pkg->pkgpart,
2226 pkgnum => $cust_bill_pkg->pkgnum,
2231 #unit_amount => $cust_bill_pkg->unitrecur,
2232 quantity => $cust_bill_pkg->quantity,
2233 product_code => 'N/A',
2234 ext_description => [],
2237 $lines{$section}{$desc}{amount} += $amount;
2238 $lines{$section}{$desc}{calls}++;
2239 $lines{$section}{$desc}{duration} += $detail->duration;
2245 my %sectionmap = ();
2246 foreach (keys %sections) {
2247 my $usage_class = $usage_class{$classnums{$_}};
2248 $sectionmap{$_} = { 'description' => &{$escape}($_),
2249 'amount' => $sections{$_}{amount}, #subtotal
2250 'calls' => $sections{$_}{calls},
2251 'duration' => $sections{$_}{duration},
2253 'tax_section' => '',
2254 'sort_weight' => $usage_class->weight,
2255 ( $usage_class->format
2256 ? ( map { $_ => $usage_class->$_($format) }
2257 qw( description_generator header_generator total_generator total_line_generator )
2264 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2268 foreach my $section ( keys %lines ) {
2269 foreach my $line ( keys %{$lines{$section}} ) {
2270 my $l = $lines{$section}{$line};
2271 $l->{section} = $sectionmap{$section};
2272 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2273 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2278 return(\@sections, \@lines);
2284 my $end = $self->_date;
2286 # start at date of previous invoice + 1 second or 0 if no previous invoice
2287 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2288 $start = 0 if !$start;
2291 my $cust_main = $self->cust_main;
2292 my @pkgs = $cust_main->all_pkgs;
2293 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2296 foreach my $pkg ( @pkgs ) {
2297 my @h_cust_svc = $pkg->h_cust_svc($end);
2298 foreach my $h_cust_svc ( @h_cust_svc ) {
2299 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2300 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2302 my $inserted = $h_cust_svc->date_inserted;
2303 my $deleted = $h_cust_svc->date_deleted;
2304 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2306 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2308 # DID either activated or ported in; cannot be both for same DID simultaneously
2309 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2310 && (!$phone_inserted->lnp_status
2311 || $phone_inserted->lnp_status eq ''
2312 || $phone_inserted->lnp_status eq 'native')) {
2315 else { # this one not so clean, should probably move to (h_)svc_phone
2316 local($FS::Record::qsearch_qualify_columns) = 0;
2317 my $phone_portedin = qsearchs( 'h_svc_phone',
2318 { 'svcnum' => $h_cust_svc->svcnum,
2319 'lnp_status' => 'portedin' },
2320 FS::h_svc_phone->sql_h_searchs($end),
2322 $num_portedin++ if $phone_portedin;
2325 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2326 if($deleted >= $start && $deleted <= $end && $phone_deleted
2327 && (!$phone_deleted->lnp_status
2328 || $phone_deleted->lnp_status ne 'portingout')) {
2331 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2332 && $phone_deleted->lnp_status
2333 && $phone_deleted->lnp_status eq 'portingout') {
2337 # increment usage minutes
2338 if ( $phone_inserted ) {
2339 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2340 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2343 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2346 # don't look at this service again
2347 push @seen, $h_cust_svc->svcnum;
2351 $minutes = sprintf("%d", $minutes);
2352 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2353 . "$num_deactivated Ported-Out: $num_portedout ",
2354 "Total Minutes: $minutes");
2357 sub _items_accountcode_cdr {
2362 my $section = { 'amount' => 0,
2365 'sort_weight' => '',
2367 'description' => 'Usage by Account Code',
2373 my %accountcodes = ();
2375 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2376 next unless $cust_bill_pkg->pkgnum > 0;
2378 my @header = $cust_bill_pkg->details_header;
2379 next unless scalar(@header);
2380 $section->{'header'} = join(',',@header);
2382 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2384 $section->{'header'} = $detail->formatted('format' => $format)
2385 if($detail->detail eq $section->{'header'});
2387 my $accountcode = $detail->accountcode;
2388 next unless $accountcode;
2390 my $amount = $detail->amount;
2391 next unless $amount && $amount > 0;
2393 $accountcodes{$accountcode} ||= {
2394 description => $accountcode,
2401 product_code => 'N/A',
2402 section => $section,
2403 ext_description => [ $section->{'header'} ],
2407 $section->{'amount'} += $amount;
2408 $accountcodes{$accountcode}{'amount'} += $amount;
2409 $accountcodes{$accountcode}{calls}++;
2410 $accountcodes{$accountcode}{duration} += $detail->duration;
2411 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2415 foreach my $l ( values %accountcodes ) {
2416 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2417 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2418 foreach my $sorted_detail ( @sorted_detail ) {
2419 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2421 delete $l->{detail_temp};
2425 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2427 return ($section,\@sorted_lines);
2430 sub _items_svc_phone_sections {
2432 my $conf = $self->conf;
2440 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2442 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2443 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2445 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2446 next unless $cust_bill_pkg->pkgnum > 0;
2448 my @header = $cust_bill_pkg->details_header;
2449 next unless scalar(@header);
2451 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2453 my $phonenum = $detail->phonenum;
2454 next unless $phonenum;
2456 my $amount = $detail->amount;
2457 next unless $amount && $amount > 0;
2459 $sections{$phonenum} ||= { 'amount' => 0,
2462 'sort_weight' => -1,
2463 'phonenum' => $phonenum,
2465 $sections{$phonenum}{amount} += $amount; #subtotal
2466 $sections{$phonenum}{calls}++;
2467 $sections{$phonenum}{duration} += $detail->duration;
2469 my $desc = $detail->regionname;
2470 my $description = $desc;
2471 $description = substr($desc, 0, $maxlength). '...'
2472 if $format eq 'latex' && length($desc) > $maxlength;
2474 $lines{$phonenum}{$desc} ||= {
2475 description => &{$escape}($description),
2476 #pkgpart => $part_pkg->pkgpart,
2484 product_code => 'N/A',
2485 ext_description => [],
2488 $lines{$phonenum}{$desc}{amount} += $amount;
2489 $lines{$phonenum}{$desc}{calls}++;
2490 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2492 my $line = $usage_class{$detail->classnum}->classname;
2493 $sections{"$phonenum $line"} ||=
2497 'sort_weight' => $usage_class{$detail->classnum}->weight,
2498 'phonenum' => $phonenum,
2499 'header' => [ @header ],
2501 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2502 $sections{"$phonenum $line"}{calls}++;
2503 $sections{"$phonenum $line"}{duration} += $detail->duration;
2505 $lines{"$phonenum $line"}{$desc} ||= {
2506 description => &{$escape}($description),
2507 #pkgpart => $part_pkg->pkgpart,
2515 product_code => 'N/A',
2516 ext_description => [],
2519 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2520 $lines{"$phonenum $line"}{$desc}{calls}++;
2521 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2522 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2523 $detail->formatted('format' => $format);
2528 my %sectionmap = ();
2529 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2530 foreach ( keys %sections ) {
2531 my @header = @{ $sections{$_}{header} || [] };
2533 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2534 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2535 my $usage_class = $summary ? $simple : $usage_simple;
2536 my $ending = $summary ? ' usage charges' : '';
2539 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2541 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2542 'amount' => $sections{$_}{amount}, #subtotal
2543 'calls' => $sections{$_}{calls},
2544 'duration' => $sections{$_}{duration},
2546 'tax_section' => '',
2547 'phonenum' => $sections{$_}{phonenum},
2548 'sort_weight' => $sections{$_}{sort_weight},
2549 'post_total' => $summary, #inspire pagebreak
2551 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2552 qw( description_generator
2555 total_line_generator
2562 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2563 $a->{sort_weight} <=> $b->{sort_weight}
2568 foreach my $section ( keys %lines ) {
2569 foreach my $line ( keys %{$lines{$section}} ) {
2570 my $l = $lines{$section}{$line};
2571 $l->{section} = $sectionmap{$section};
2572 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2573 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2578 if($conf->exists('phone_usage_class_summary')) {
2579 # this only works with Latex
2583 # after this, we'll have only two sections per DID:
2584 # Calls Summary and Calls Detail
2585 foreach my $section ( @sections ) {
2586 if($section->{'post_total'}) {
2587 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2588 $section->{'total_line_generator'} = sub { '' };
2589 $section->{'total_generator'} = sub { '' };
2590 $section->{'header_generator'} = sub { '' };
2591 $section->{'description_generator'} = '';
2592 push @newsections, $section;
2593 my %calls_detail = %$section;
2594 $calls_detail{'post_total'} = '';
2595 $calls_detail{'sort_weight'} = '';
2596 $calls_detail{'description_generator'} = sub { '' };
2597 $calls_detail{'header_generator'} = sub {
2598 return ' & Date/Time & Called Number & Duration & Price'
2599 if $format eq 'latex';
2602 $calls_detail{'description'} = 'Calls Detail: '
2603 . $section->{'phonenum'};
2604 push @newsections, \%calls_detail;
2608 # after this, each usage class is collapsed/summarized into a single
2609 # line under the Calls Summary section
2610 foreach my $newsection ( @newsections ) {
2611 if($newsection->{'post_total'}) { # this means Calls Summary
2612 foreach my $section ( @sections ) {
2613 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2614 && !$section->{'post_total'});
2615 my $newdesc = $section->{'description'};
2616 my $tn = $section->{'phonenum'};
2617 $newdesc =~ s/$tn//g;
2618 my $line = { ext_description => [],
2622 calls => $section->{'calls'},
2623 section => $newsection,
2624 duration => $section->{'duration'},
2625 description => $newdesc,
2626 amount => sprintf("%.2f",$section->{'amount'}),
2627 product_code => 'N/A',
2629 push @newlines, $line;
2634 # after this, Calls Details is populated with all CDRs
2635 foreach my $newsection ( @newsections ) {
2636 if(!$newsection->{'post_total'}) { # this means Calls Details
2637 foreach my $line ( @lines ) {
2638 next unless (scalar(@{$line->{'ext_description'}}) &&
2639 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2641 my @extdesc = @{$line->{'ext_description'}};
2643 foreach my $extdesc ( @extdesc ) {
2644 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2645 push @newextdesc, $extdesc;
2647 $line->{'ext_description'} = \@newextdesc;
2648 $line->{'section'} = $newsection;
2649 push @newlines, $line;
2654 return(\@newsections, \@newlines);
2657 return(\@sections, \@lines);
2661 =sub _items_usage_class_summary OPTIONS
2663 Returns a list of detail items summarizing the usage charges on this
2664 invoice. Each one will have 'amount', 'description' (the usage charge name),
2665 and 'usage_classnum'.
2667 OPTIONS can include 'escape' (a function to escape the descriptions).
2671 sub _items_usage_class_summary {
2675 my $escape = $opt{escape} || sub { $_[0] };
2676 my $invnum = $self->invnum;
2677 my @classes = qsearch({
2678 'table' => 'usage_class',
2679 'select' => 'classnum, classname, SUM(amount) AS amount',
2680 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2681 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2682 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2683 ' GROUP BY classnum, classname, weight'.
2684 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2685 ' ORDER BY weight ASC',
2689 description => &{$escape}($self->mt('Usage Summary')),
2693 foreach my $class (@classes) {
2695 'description' => &{$escape}($class->classname),
2696 'amount' => sprintf('%.2f', $class->amount),
2697 'usage_classnum' => $class->classnum,
2698 'section' => $section,
2704 sub _items_previous {
2706 my $conf = $self->conf;
2707 my $cust_main = $self->cust_main;
2708 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2710 foreach ( @pr_cust_bill ) {
2711 my $date = $conf->exists('invoice_show_prior_due_date')
2712 ? 'due '. $_->due_date2str('short')
2713 : $self->time2str_local('short', $_->_date);
2715 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2716 #'pkgpart' => 'N/A',
2718 'amount' => sprintf("%.2f", $_->owed),
2724 # 'description' => 'Previous Balance',
2725 # #'pkgpart' => 'N/A',
2726 # 'pkgnum' => 'N/A',
2727 # 'amount' => sprintf("%10.2f", $pr_total ),
2728 # 'ext_description' => [ map {
2729 # "Invoice ". $_->invnum.
2730 # " (". time2str("%x",$_->_date). ") ".
2731 # sprintf("%10.2f", $_->owed)
2732 # } @pr_cust_bill ],
2737 sub _items_credits {
2738 my( $self, %opt ) = @_;
2739 my $trim_len = $opt{'trim_len'} || 60;
2744 if ( $self->conf->exists('previous_balance-payments_since') ) {
2745 if ( $opt{'template'} eq 'statement' ) {
2746 # then the current bill is a "statement" (i.e. an invoice sent as
2747 # a payment receipt)
2748 # and in that case we want to see payments on or after THIS invoice
2749 @objects = qsearch('cust_credit', {
2750 'custnum' => $self->custnum,
2751 '_date' => {op => '>=', value => $self->_date},
2755 $date = $self->previous_bill->_date if $self->previous_bill;
2756 @objects = qsearch('cust_credit', {
2757 'custnum' => $self->custnum,
2758 '_date' => {op => '>=', value => $date},
2762 @objects = $self->cust_credited;
2765 foreach my $obj ( @objects ) {
2766 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
2768 my $reason = substr($cust_credit->reason, 0, $trim_len);
2769 $reason .= '...' if length($reason) < length($cust_credit->reason);
2770 $reason = " ($reason) " if $reason;
2773 #'description' => 'Credit ref\#'. $_->crednum.
2774 # " (". time2str("%x",$_->cust_credit->_date) .")".
2776 'description' => $self->mt('Credit applied').' '.
2777 $self->time2str_local('short', $obj->_date). $reason,
2778 'amount' => sprintf("%.2f",$obj->amount),
2786 sub _items_payments {
2791 my $detailed = $self->conf->exists('invoice_payment_details');
2793 if ( $self->conf->exists('previous_balance-payments_since') ) {
2794 # then show payments dated on/after the previous bill...
2795 if ( $opt{'template'} eq 'statement' ) {
2796 # then the current bill is a "statement" (i.e. an invoice sent as
2797 # a payment receipt)
2798 # and in that case we want to see payments on or after THIS invoice
2799 @objects = qsearch('cust_pay', {
2800 'custnum' => $self->custnum,
2801 '_date' => {op => '>=', value => $self->_date},
2804 # the normal case: payments on or after the previous invoice
2806 $date = $self->previous_bill->_date if $self->previous_bill;
2807 @objects = qsearch('cust_pay', {
2808 'custnum' => $self->custnum,
2809 '_date' => {op => '>=', value => $date},
2811 # and before the current bill...
2812 @objects = grep { $_->_date < $self->_date } @objects;
2815 @objects = $self->cust_bill_pay;
2818 foreach my $obj (@objects) {
2819 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
2820 my $desc = $self->mt('Payment received').' '.
2821 $self->time2str_local('short', $cust_pay->_date );
2822 $desc .= $self->mt(' via ') .
2823 $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
2827 'description' => $desc,
2828 'amount' => sprintf("%.2f", $obj->amount )
2836 =item call_details [ OPTION => VALUE ... ]
2838 Returns an array of CSV strings representing the call details for this invoice
2839 The only option available is the boolean prepend_billed_number
2844 my ($self, %opt) = @_;
2846 my $format_function = sub { shift };
2848 if ($opt{prepend_billed_number}) {
2849 $format_function = sub {
2853 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
2858 my @details = map { $_->details( 'format_function' => $format_function,
2859 'escape_function' => sub{ return() },
2863 $self->cust_bill_pkg;
2864 my $header = $details[0];
2865 ( $header, grep { $_ ne $header } @details );
2875 =item process_reprint
2879 sub process_reprint {
2880 process_re_X('print', @_);
2883 =item process_reemail
2887 sub process_reemail {
2888 process_re_X('email', @_);
2896 process_re_X('fax', @_);
2904 process_re_X('ftp', @_);
2911 sub process_respool {
2912 process_re_X('spool', @_);
2917 my( $method, $job ) = ( shift, shift );
2918 warn "$me process_re_X $method for job $job\n" if $DEBUG;
2921 warn Dumper($param) if $DEBUG;
2932 # spool_invoice ftp_invoice fax_invoice print_invoice
2933 my($method, $job, %param ) = @_;
2935 warn "re_X $method for job $job with param:\n".
2936 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
2939 #some false laziness w/search/cust_bill.html
2941 my $orderby = 'ORDER BY cust_bill._date';
2943 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
2945 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
2947 my @cust_bill = qsearch( {
2948 #'select' => "cust_bill.*",
2949 'table' => 'cust_bill',
2950 'addl_from' => $addl_from,
2952 'extra_sql' => $extra_sql,
2953 'order_by' => $orderby,
2957 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
2959 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
2962 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
2963 foreach my $cust_bill ( @cust_bill ) {
2964 $cust_bill->$method();
2966 if ( $job ) { #progressbar foo
2968 if ( time - $min_sec > $last ) {
2969 my $error = $job->update_statustext(
2970 int( 100 * $num / scalar(@cust_bill) )
2972 die $error if $error;
2983 +{ ( map { $_=>$self->$_ } $self->fields ),
2984 'owed' => $self->owed,
2985 #XXX last payment applied date
2991 =head1 CLASS METHODS
2997 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3002 my ($class, $start, $end) = @_;
3004 $class->paid_sql($start, $end). ' - '.
3005 $class->credited_sql($start, $end);
3010 Returns an SQL fragment to retreive the net amount (charged minus credited).
3015 my ($class, $start, $end) = @_;
3016 'charged - '. $class->credited_sql($start, $end);
3021 Returns an SQL fragment to retreive the amount paid against this invoice.
3026 my ($class, $start, $end) = @_;
3027 $start &&= "AND cust_bill_pay._date <= $start";
3028 $end &&= "AND cust_bill_pay._date > $end";
3029 $start = '' unless defined($start);
3030 $end = '' unless defined($end);
3031 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3032 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3037 Returns an SQL fragment to retreive the amount credited against this invoice.
3042 my ($class, $start, $end) = @_;
3043 $start &&= "AND cust_credit_bill._date <= $start";
3044 $end &&= "AND cust_credit_bill._date > $end";
3045 $start = '' unless defined($start);
3046 $end = '' unless defined($end);
3047 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3048 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3053 Returns an SQL fragment to retrieve the due date of an invoice.
3054 Currently only supported on PostgreSQL.
3059 die "don't use: doesn't account for agent-specific invoice_default_terms";
3061 #we're passed a $conf but not a specific customer (that's in the query), so
3062 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3063 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3066 my $conf = new FS::Conf;
3070 cust_bill.invoice_terms,
3071 cust_main.invoice_terms,
3072 \''.($conf->config('invoice_default_terms') || '').'\'
3073 ), E\'Net (\\\\d+)\'
3075 ) * 86400 + cust_bill._date'
3086 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3087 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base