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);
17 use Storable qw( freeze thaw );
19 use FS::UID qw( datasrc );
20 use FS::Misc qw( send_fax do_print );
21 use FS::Record qw( qsearch qsearchs dbh );
22 use FS::cust_statement;
23 use FS::cust_bill_pkg;
24 use FS::cust_bill_pkg_display;
25 use FS::cust_bill_pkg_detail;
29 use FS::cust_credit_bill;
33 use FS::cust_bill_pay;
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;
46 $me = '[FS::cust_bill]';
50 FS::cust_bill - Object methods for cust_bill records
56 $record = new FS::cust_bill \%hash;
57 $record = new FS::cust_bill { 'column' => 'value' };
59 $error = $record->insert;
61 $error = $new_record->replace($old_record);
63 $error = $record->delete;
65 $error = $record->check;
67 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
69 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
71 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
73 @cust_pay_objects = $cust_bill->cust_pay;
75 $tax_amount = $record->tax;
77 @lines = $cust_bill->print_text;
78 @lines = $cust_bill->print_text('time' => $time);
82 An FS::cust_bill object represents an invoice; a declaration that a customer
83 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
84 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
85 following fields are currently supported:
91 =item invnum - primary key (assigned automatically for new invoices)
93 =item custnum - customer (see L<FS::cust_main>)
95 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
96 L<Time::Local> and L<Date::Parse> for conversion functions.
98 =item charged - amount of this invoice
100 =item invoice_terms - optional terms override for this specific invoice
108 =item billing_balance - the customer's balance immediately before generating
109 this invoice. DEPRECATED. Use the L<FS::cust_main/balance_date> method
110 to determine the customer's balance at a specific time.
112 =item previous_balance - the customer's balance immediately after generating
113 the invoice before this one. DEPRECATED.
115 =item printed - formerly used to track the number of times an invoice had
116 been printed; no longer used.
124 =item closed - books closed flag, empty or `Y'
126 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
128 =item agent_invid - legacy invoice number
130 =item promised_date - customer promised payment date, for collection
132 =item pending - invoice is still being generated, empty or 'Y'
142 Creates a new invoice. To add the invoice to the database, see L<"insert">.
143 Invoices are normally created by calling the bill method of a customer object
144 (see L<FS::cust_main>).
148 sub table { 'cust_bill'; }
149 sub template_conf { 'invoice_'; }
151 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
152 # (except email_subject and invnum_date_pretty)
155 $self->conf->config('notice_name') || 'Invoice'
158 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
159 sub cust_unlinked_msg {
161 "WARNING: can't find cust_main.custnum ". $self->custnum.
162 ' (cust_bill.invnum '. $self->invnum. ')';
167 Adds this invoice to the database ("Posts" the invoice). If there is an error,
168 returns the error, otherwise returns false.
174 warn "$me insert called\n" if $DEBUG;
176 local $SIG{HUP} = 'IGNORE';
177 local $SIG{INT} = 'IGNORE';
178 local $SIG{QUIT} = 'IGNORE';
179 local $SIG{TERM} = 'IGNORE';
180 local $SIG{TSTP} = 'IGNORE';
181 local $SIG{PIPE} = 'IGNORE';
183 my $oldAutoCommit = $FS::UID::AutoCommit;
184 local $FS::UID::AutoCommit = 0;
187 my $error = $self->SUPER::insert;
189 $dbh->rollback if $oldAutoCommit;
193 if ( $self->get('cust_bill_pkg') ) {
194 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
195 $cust_bill_pkg->invnum($self->invnum);
196 my $error = $cust_bill_pkg->insert;
198 $dbh->rollback if $oldAutoCommit;
199 return "can't create invoice line item: $error";
204 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
209 =item void [ REASON [ , REPROCESS_CDRS ] ]
211 Voids this invoice: deletes the invoice and adds a record of the voided invoice
212 to the FS::cust_bill_void table (and related tables starting from
213 FS::cust_bill_pkg_void).
219 my $reason = scalar(@_) ? shift : '';
220 my $reprocess_cdrs = scalar(@_) ? shift : '';
222 unless (ref($reason) || !$reason) {
223 $reason = FS::reason->new_or_existing(
225 'type' => 'Invoice void',
230 local $SIG{HUP} = 'IGNORE';
231 local $SIG{INT} = 'IGNORE';
232 local $SIG{QUIT} = 'IGNORE';
233 local $SIG{TERM} = 'IGNORE';
234 local $SIG{TSTP} = 'IGNORE';
235 local $SIG{PIPE} = 'IGNORE';
237 my $oldAutoCommit = $FS::UID::AutoCommit;
238 local $FS::UID::AutoCommit = 0;
241 my $cust_bill_void = new FS::cust_bill_void ( {
242 map { $_ => $self->get($_) } $self->fields
244 $cust_bill_void->reasonnum($reason->reasonnum) if $reason;
245 my $error = $cust_bill_void->insert;
247 $dbh->rollback if $oldAutoCommit;
251 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
252 my $error = $cust_bill_pkg->void($reason, $reprocess_cdrs);
254 $dbh->rollback if $oldAutoCommit;
259 $error = $self->_delete;
261 $dbh->rollback if $oldAutoCommit;
265 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
271 # removed docs entirely and renamed method to _delete to further indicate it is
272 # internal-only and discourage use
276 # DO NOT USE THIS METHOD. Instead, apply a credit against the invoice, or use
277 # the B<void> method.
279 # This is only for internal use by V<void>, which is what you should be using.
281 # DO NOT USE THIS METHOD. Whatever reason you think you have is almost certainly
282 # wrong. Use B<void>, that's what it is for. Really. This means you.
288 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
290 local $SIG{HUP} = 'IGNORE';
291 local $SIG{INT} = 'IGNORE';
292 local $SIG{QUIT} = 'IGNORE';
293 local $SIG{TERM} = 'IGNORE';
294 local $SIG{TSTP} = 'IGNORE';
295 local $SIG{PIPE} = 'IGNORE';
297 my $oldAutoCommit = $FS::UID::AutoCommit;
298 local $FS::UID::AutoCommit = 0;
301 foreach my $table (qw(
308 #cust_event # problematic
309 #cust_pay_batch # unnecessary
311 foreach my $linked ( $self->$table() ) {
312 my $error = $linked->delete;
314 $dbh->rollback if $oldAutoCommit;
321 my $error = $self->SUPER::delete(@_);
323 $dbh->rollback if $oldAutoCommit;
327 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
333 =item replace [ OLD_RECORD ]
335 You can, but probably shouldn't modify invoices...
337 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
338 supplied, replaces this record. If there is an error, returns the error,
339 otherwise returns false.
343 #replace can be inherited from Record.pm
345 # replace_check is now the preferred way to #implement replace data checks
346 # (so $object->replace() works without an argument)
349 my( $new, $old ) = ( shift, shift );
350 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
351 #return "Can't change _date!" unless $old->_date eq $new->_date;
352 return "Can't change _date" unless $old->_date == $new->_date;
353 return "Can't change charged" unless $old->charged == $new->charged
354 || $old->pending eq 'Y'
355 || $old->charged == 0
356 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
362 =item add_cc_surcharge
368 sub add_cc_surcharge {
369 my ($self, $pkgnum, $amount) = (shift, shift, shift);
372 my $cust_bill_pkg = new FS::cust_bill_pkg({
373 'invnum' => $self->invnum,
377 $error = $cust_bill_pkg->insert;
378 return $error if $error;
380 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
381 $self->charged($self->charged+$amount);
382 $error = $self->replace;
383 return $error if $error;
385 $self->apply_payments_and_credits;
391 Checks all fields to make sure this is a valid invoice. If there is an error,
392 returns the error, otherwise returns false. Called by the insert and replace
401 $self->ut_numbern('invnum')
402 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
403 || $self->ut_numbern('_date')
404 || $self->ut_money('charged')
405 || $self->ut_numbern('printed')
406 || $self->ut_enum('closed', [ '', 'Y' ])
407 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
408 || $self->ut_numbern('agent_invid') #varchar?
409 || $self->ut_flag('pending')
411 return $error if $error;
413 $self->_date(time) unless $self->_date;
415 $self->printed(0) if $self->printed eq '';
422 Returns the displayed invoice number for this invoice: agent_invid if
423 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
429 if ( $self->agent_invid
430 && FS::Conf->new->exists('cust_bill-default_agent_invid') ) {
431 return $self->agent_invid;
433 return $self->invnum;
439 Returns the customer's last invoice before this one.
445 if ( !$self->get('previous_bill') ) {
446 $self->set('previous_bill', qsearchs({
447 'table' => 'cust_bill',
448 'hashref' => { 'custnum' => $self->custnum,
449 '_date' => { op=>'<', value=>$self->_date } },
450 'order_by' => 'ORDER BY _date DESC LIMIT 1',
453 $self->get('previous_bill');
458 Returns the customer's invoice that follows this one
464 if (!$self->get('following_bill')) {
465 $self->set('following_bill', qsearchs({
466 table => 'cust_bill',
468 custnum => $self->custnum,
469 invnum => { op => '>', value => $self->invnum },
471 order_by => 'ORDER BY invnum ASC LIMIT 1',
474 $self->get('following_bill');
479 Returns a list consisting of the total previous balance for this customer,
480 followed by the previous outstanding invoices (as FS::cust_bill objects also).
486 # simple memoize; we use this a lot
487 if (!$self->get('previous')) {
489 my @cust_bill = sort { $a->_date <=> $b->_date }
490 grep { $_->owed != 0 }
491 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
492 #'_date' => { op=>'<', value=>$self->_date },
493 'invnum' => { op=>'<', value=>$self->invnum },
496 foreach ( @cust_bill ) { $total += $_->owed; }
497 $self->set('previous', [$total, @cust_bill]);
499 return @{ $self->get('previous') };
502 =item enable_previous
504 Whether to show the 'Previous Charges' section when printing this invoice.
505 The negation of the 'disable_previous_balance' config setting.
509 sub enable_previous {
511 my $agentnum = $self->cust_main->agentnum;
512 !$self->conf->exists('disable_previous_balance', $agentnum);
517 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
525 'select' => 'cust_bill_pkg.*, pkg_category.categoryname',
526 'table' => 'cust_bill_pkg',
527 'addl_from' => ' LEFT JOIN cust_pkg USING ( pkgnum ) '.
528 ' LEFT JOIN part_pkg USING ( pkgpart ) '.
529 ' LEFT JOIN pkg_class USING ( classnum ) '.
530 ' LEFT JOIN pkg_category USING ( categorynum ) ',
531 'hashref' => { 'invnum' => $self->invnum },
532 'order_by' => 'ORDER BY billpkgnum', #important? otherwise we could use
533 # the AUTLOADED FK search. or should
534 # that default to ORDER by the pkey?
539 =item cust_bill_pkg_pkgnum PKGNUM
541 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
546 sub cust_bill_pkg_pkgnum {
547 my( $self, $pkgnum ) = @_;
549 { 'table' => 'cust_bill_pkg',
550 'hashref' => { 'invnum' => $self->invnum,
553 'order_by' => 'ORDER BY billpkgnum',
560 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
567 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
568 $self->cust_bill_pkg;
570 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
575 Returns true if any of the packages (or their definitions) corresponding to the
576 line items for this invoice have the no_auto flag set.
582 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
585 =item open_cust_bill_pkg
587 Returns the open line items for this invoice.
589 Note that cust_bill_pkg with both setup and recur fees are returned as two
590 separate line items, each with only one fee.
594 # modeled after cust_main::open_cust_bill
595 sub open_cust_bill_pkg {
598 # grep { $_->owed > 0 } $self->cust_bill_pkg
600 my %other = ( 'recur' => 'setup',
601 'setup' => 'recur', );
603 foreach my $field ( qw( recur setup )) {
604 push @open, map { $_->set( $other{$field}, 0 ); $_; }
605 grep { $_->owed($field) > 0 }
606 $self->cust_bill_pkg;
614 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
618 #false laziness w/cust_pkg.pm
622 'table' => 'cust_event',
623 'addl_from' => 'JOIN part_event USING ( eventpart )',
624 'hashref' => { 'tablenum' => $self->invnum },
625 'extra_sql' => " AND eventtable = 'cust_bill' ",
631 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
635 #false laziness w/cust_pkg.pm
639 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
640 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
641 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
642 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
643 $sth->fetchrow_arrayref->[0];
648 Returns the customer (see L<FS::cust_main>) for this invoice.
652 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this invoice
654 Returns a list: an empty list on success or a list of errors.
661 grep { $_->suspend(@_) }
662 grep {! $_->getfield('cancel') }
667 =item cust_suspend_if_balance_over AMOUNT
669 Suspends the customer associated with this invoice if the total amount owed on
670 this invoice and all older invoices is greater than the specified amount.
672 Returns a list: an empty list on success or a list of errors.
676 sub cust_suspend_if_balance_over {
677 my( $self, $amount ) = ( shift, shift );
678 my $cust_main = $self->cust_main;
679 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
682 $cust_main->suspend(@_);
688 Cancel the packages on this invoice. Largely similar to the cust_main version, but does not bother yet with banned payment options
693 my( $self, %opt ) = @_;
695 warn "$me cancel called on cust_bill ". $self->invnum . " with options ".
696 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
699 return ( 'Access denied' )
700 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
702 my @pkgs = $self->cust_pkg;
704 if ( !$opt{nobill} && $self->conf->exists('bill_usage_on_cancel') ) {
706 my $error = $self->cust_main->bill( pkg_list => [ @pkgs ], cancel => 1 );
707 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
712 map { $_->cancel(%opt) }
713 grep { ! $_->getfield('cancel') }
719 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
725 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
726 sort { $a->_date <=> $b->_date }
727 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
732 =item cust_credit_bill
734 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
740 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
741 sort { $a->_date <=> $b->_date }
742 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
746 sub cust_credit_bill {
747 shift->cust_credited(@_);
750 #=item cust_bill_pay_pkgnum PKGNUM
752 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
753 #with matching pkgnum.
757 #sub cust_bill_pay_pkgnum {
758 # my( $self, $pkgnum ) = @_;
759 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
760 # sort { $a->_date <=> $b->_date }
761 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
762 # 'pkgnum' => $pkgnum,
767 =item cust_bill_pay_pkg PKGNUM
769 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
770 applied against the matching pkgnum.
774 sub cust_bill_pay_pkg {
775 my( $self, $pkgnum ) = @_;
778 'select' => 'cust_bill_pay_pkg.*',
779 'table' => 'cust_bill_pay_pkg',
780 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
781 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
782 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
783 " AND cust_bill_pkg.pkgnum = $pkgnum",
788 #=item cust_credited_pkgnum PKGNUM
790 #=item cust_credit_bill_pkgnum PKGNUM
792 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
793 #with matching pkgnum.
797 #sub cust_credited_pkgnum {
798 # my( $self, $pkgnum ) = @_;
799 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
800 # sort { $a->_date <=> $b->_date }
801 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
802 # 'pkgnum' => $pkgnum,
807 #sub cust_credit_bill_pkgnum {
808 # shift->cust_credited_pkgnum(@_);
811 =item cust_credit_bill_pkg PKGNUM
813 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
814 applied against the matching pkgnum.
818 sub cust_credit_bill_pkg {
819 my( $self, $pkgnum ) = @_;
822 'select' => 'cust_credit_bill_pkg.*',
823 'table' => 'cust_credit_bill_pkg',
824 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
825 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
826 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
827 " AND cust_bill_pkg.pkgnum = $pkgnum",
832 =item cust_bill_batch
834 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
838 sub cust_bill_batch {
840 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
845 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
846 hash keyed by term length.
852 FS::discount_plan->all($self);
857 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
864 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
866 foreach (@taxlines) { $total += $_->setup; }
872 Returns the amount owed (still outstanding) on this invoice, which is charged
873 minus all payment applications (see L<FS::cust_bill_pay>) and credit
874 applications (see L<FS::cust_credit_bill>).
880 my $balance = $self->charged;
881 $balance -= $_->amount foreach ( $self->cust_bill_pay );
882 $balance -= $_->amount foreach ( $self->cust_credited );
883 $balance = sprintf( "%.2f", $balance);
884 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
888 =item owed_on_invoice
890 Returns the amount to be displayed as the "Balance Due" on this
891 invoice. Amount returned depends on conf flags for invoicing
893 See L<FS::cust_bill::owed> for the true amount currently owed
897 sub owed_on_invoice {
900 #return $self->owed()
901 # unless $self->conf->exists('previous_balance-payments_since')
903 # Add charges from this invoice
904 my $owed = $self->charged();
906 # Add carried balances from previous invoices
907 # If previous items aren't to be displayed on the invoice,
908 # _items_previous() is aware of this and responds appropriately.
909 $owed += $_->{amount} for $self->_items_previous();
911 # Subtract payments and credits displayed on this invoice
912 $owed -= $_->{amount} for $self->_items_payments(), $self->_items_credits();
918 my( $self, $pkgnum ) = @_;
920 #my $balance = $self->charged;
922 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
924 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
925 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
927 $balance = sprintf( "%.2f", $balance);
928 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
934 Returns true if this invoice should be hidden. See the
935 selfservice-hide_invoices-taxclass configuraiton setting.
941 my $conf = $self->conf;
942 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
944 my @cust_bill_pkg = $self->cust_bill_pkg;
945 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
946 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
949 =item apply_payments_and_credits [ OPTION => VALUE ... ]
951 Applies unapplied payments and credits to this invoice.
952 Payments with the no_auto_apply flag set will not be applied.
954 A hash of optional arguments may be passed. Currently "manual" is supported.
955 If true, a payment receipt is sent instead of a statement when
956 'payment_receipt_email' configuration option is set.
958 If there is an error, returns the error, otherwise returns false.
962 sub apply_payments_and_credits {
963 my( $self, %options ) = @_;
964 my $conf = $self->conf;
966 local $SIG{HUP} = 'IGNORE';
967 local $SIG{INT} = 'IGNORE';
968 local $SIG{QUIT} = 'IGNORE';
969 local $SIG{TERM} = 'IGNORE';
970 local $SIG{TSTP} = 'IGNORE';
971 local $SIG{PIPE} = 'IGNORE';
973 my $oldAutoCommit = $FS::UID::AutoCommit;
974 local $FS::UID::AutoCommit = 0;
977 $self->select_for_update; #mutex
979 my @payments = grep { $_->unapplied > 0 }
980 grep { !$_->no_auto_apply }
981 $self->cust_main->cust_pay;
982 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
984 if ( $conf->exists('pkg-balances') ) {
985 # limit @payments & @credits to those w/ a pkgnum grepped from $self
986 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
987 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
988 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
991 while ( $self->owed > 0 and ( @payments || @credits ) ) {
994 if ( @payments && @credits ) {
996 #decide which goes first by weight of top (unapplied) line item
998 my @open_lineitems = $self->open_cust_bill_pkg;
1000 my $max_pay_weight =
1001 max( map { $_->part_pkg->pay_weight || 0 }
1003 map { $_->cust_pkg }
1006 my $max_credit_weight =
1007 max( map { $_->part_pkg->credit_weight || 0 }
1009 map { $_->cust_pkg }
1013 #if both are the same... payments first? it has to be something
1014 if ( $max_pay_weight >= $max_credit_weight ) {
1020 } elsif ( @payments ) {
1022 } elsif ( @credits ) {
1025 die "guru meditation #12 and 35";
1029 if ( $app eq 'pay' ) {
1031 my $payment = shift @payments;
1032 $unapp_amount = $payment->unapplied;
1033 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
1034 $app->pkgnum( $payment->pkgnum )
1035 if $conf->exists('pkg-balances') && $payment->pkgnum;
1037 } elsif ( $app eq 'credit' ) {
1039 my $credit = shift @credits;
1040 $unapp_amount = $credit->credited;
1041 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1042 $app->pkgnum( $credit->pkgnum )
1043 if $conf->exists('pkg-balances') && $credit->pkgnum;
1046 die "guru meditation #12 and 35";
1050 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1051 warn "owed_pkgnum ". $app->pkgnum;
1052 $owed = $self->owed_pkgnum($app->pkgnum);
1054 $owed = $self->owed;
1056 next unless $owed > 0;
1058 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1059 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1061 $app->invnum( $self->invnum );
1063 my $error = $app->insert(%options);
1065 $dbh->rollback if $oldAutoCommit;
1066 return "Error inserting ". $app->table. " record: $error";
1068 die $error if $error;
1072 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1079 Sends this invoice to the destinations configured for this customer: sends
1080 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1082 Options can be passed as a hashref. Positional parameters are no longer
1085 I<template>: a suffix for alternate invoices
1087 I<agentnum>: obsolete, now does nothing.
1089 I<from> overrides the default email invoice From: address.
1091 I<amount>: obsolete, does nothing
1093 I<notice_name> overrides "Invoice" as the name of the sent document
1094 (templates from 10/2009 or newer required).
1096 I<lpr> overrides the system 'lpr' option as the command to print a document
1097 from standard input.
1103 my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1104 my $conf = $self->conf;
1106 my $cust_main = $self->cust_main;
1108 my @invoicing_list = $cust_main->invoicing_list;
1111 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1112 && ! $cust_main->invoice_noemail;
1115 if grep { $_ eq 'POST' } @invoicing_list; #postal
1117 #this has never been used post-$ORIGINAL_ISP afaik
1118 $self->fax_invoice($opt)
1119 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1127 my $opt = shift || {};
1128 if ($opt and !ref($opt)) {
1129 die ref($self). '->email called with positional parameters';
1132 my $conf = $self->conf;
1134 my $from = delete $opt->{from};
1136 # this is where we set the From: address
1137 $from ||= $self->_agent_invoice_from || #XXX should go away
1138 $conf->invoice_from_full( $self->cust_main->agentnum );
1140 my @invoicing_list = $self->cust_main->invoicing_list_emailonly;
1142 if ( ! @invoicing_list ) { #no recipients
1143 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1144 die 'No recipients for customer #'. $self->custnum;
1146 #default: better to notify this person than silence
1147 @invoicing_list = ($from);
1151 $self->SUPER::email( {
1153 'to' => \@invoicing_list,
1159 #this stays here for now because its explicitly used as
1160 # FS::cust_bill::queueable_email
1161 sub queueable_email {
1164 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1165 or die "invalid invoice number: " . $opt{invnum};
1167 $self->set('mode', $opt{mode})
1170 my %args = map {$_ => $opt{$_}}
1172 qw( from notice_name no_coupon template );
1174 my $error = $self->email( \%args );
1175 die $error if $error;
1181 my $conf = $self->conf;
1183 #my $template = scalar(@_) ? shift : '';
1186 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1189 my $cust_main = $self->cust_main;
1190 my $name = $cust_main->name;
1191 my $name_short = $cust_main->name_short;
1192 my $invoice_number = $self->invnum;
1193 my $invoice_date = $self->_date_pretty;
1195 eval qq("$subject");
1200 'Invoice-'. $self->invnum. '.pdf';
1203 =item lpr_data HASHREF
1205 Returns the postscript or plaintext for this invoice as an arrayref.
1207 Options must be passed as a hashref. Positional parameters are no longer
1210 I<template>, if specified, is the name of a suffix for alternate invoices.
1212 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1218 my $conf = $self->conf;
1219 my $opt = shift || {};
1220 if ($opt and !ref($opt)) {
1221 # nobody does this anyway
1222 die "FS::cust_bill::lpr_data called with positional parameters";
1225 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1226 [ $self->$method( $opt ) ];
1231 Prints this invoice.
1233 Options must be passed as a hashref.
1235 I<template>, if specified, is the name of a suffix for alternate invoices.
1237 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1243 return if $self->hide;
1244 my $conf = $self->conf;
1245 my $opt = shift || {};
1246 if ($opt and !ref($opt)) {
1247 die "FS::cust_bill::print called with positional parameters";
1250 my $lpr = delete $opt->{lpr};
1251 if($conf->exists('invoice_print_pdf')) {
1252 # Add the invoice to the current batch.
1253 $self->batch_invoice($opt);
1257 $self->lpr_data($opt),
1258 'agentnum' => $self->cust_main->agentnum,
1264 =item fax_invoice HASHREF
1268 Options must be passed as a hashref.
1270 I<template>, if specified, is the name of a suffix for alternate invoices.
1272 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1278 return if $self->hide;
1279 my $conf = $self->conf;
1280 my $opt = shift || {};
1281 if ($opt and !ref($opt)) {
1282 die "FS::cust_bill::fax_invoice called with positional parameters";
1285 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1286 unless $conf->exists('invoice_latex');
1288 my $dialstring = $self->cust_main->getfield('fax');
1291 my $error = send_fax( 'docdata' => $self->lpr_data($opt),
1292 'dialstring' => $dialstring,
1294 die $error if $error;
1298 =item batch_invoice [ HASHREF ]
1300 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1301 isn't an open batch, one will be created.
1303 HASHREF may contain any options to be passed to C<print_pdf>.
1308 my ($self, $opt) = @_;
1309 my $bill_batch = $self->get_open_bill_batch;
1310 my $cust_bill_batch = FS::cust_bill_batch->new({
1311 batchnum => $bill_batch->batchnum,
1312 invnum => $self->invnum,
1314 if ( $self->mode ) {
1315 $opt->{mode} ||= $self->mode;
1316 $opt->{mode} = $opt->{mode}->modenum if ref $opt->{mode};
1318 return $cust_bill_batch->insert($opt);
1321 =item get_open_batch
1323 Returns the currently open batch as an FS::bill_batch object, creating a new
1324 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1329 sub get_open_bill_batch {
1331 my $conf = $self->conf;
1332 my $hashref = { status => 'O' };
1333 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1334 ? $self->cust_main->agentnum
1336 my $batch = qsearchs('bill_batch', $hashref);
1337 return $batch if $batch;
1338 $batch = FS::bill_batch->new($hashref);
1339 my $error = $batch->insert;
1340 die $error if $error;
1344 =item ftp_invoice [ TEMPLATENAME ]
1346 Sends this invoice data via FTP.
1348 TEMPLATENAME is unused?
1354 my $conf = $self->conf;
1355 my $template = scalar(@_) ? shift : '';
1358 'protocol' => 'ftp',
1359 'server' => $conf->config('cust_bill-ftpserver'),
1360 'username' => $conf->config('cust_bill-ftpusername'),
1361 'password' => $conf->config('cust_bill-ftppassword'),
1362 'dir' => $conf->config('cust_bill-ftpdir'),
1363 'format' => $conf->config('cust_bill-ftpformat'),
1367 =item spool_invoice [ TEMPLATENAME ]
1369 Spools this invoice data (see L<FS::spool_csv>)
1371 TEMPLATENAME is unused?
1377 my $conf = $self->conf;
1378 my $template = scalar(@_) ? shift : '';
1381 'format' => $conf->config('cust_bill-spoolformat'),
1382 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1386 =item send_csv OPTION => VALUE, ...
1388 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1392 protocol - currently only "ftp"
1398 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1399 and YYMMDDHHMMSS is a timestamp.
1401 See L</print_csv> for a description of the output format.
1406 my($self, %opt) = @_;
1410 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1411 mkdir $spooldir, 0700 unless -d $spooldir;
1413 # don't localize dates here, they're a defined format
1414 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1415 my $file = "$spooldir/$tracctnum.csv";
1417 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1419 open(CSV, ">$file") or die "can't open $file: $!";
1427 if ( $opt{protocol} eq 'ftp' ) {
1428 eval "use Net::FTP;";
1430 $net = Net::FTP->new($opt{server}) or die @$;
1432 die "unknown protocol: $opt{protocol}";
1435 $net->login( $opt{username}, $opt{password} )
1436 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1438 $net->binary or die "can't set binary mode";
1440 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1442 $net->put($file) or die "can't put $file: $!";
1452 Spools CSV invoice data.
1458 =item format - any of FS::Misc::::Invoicing::spool_formats
1460 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1461 customer has the corresponding invoice destinations set (see
1462 L<FS::cust_main_invoice>).
1464 =item agent_spools - if set to a true value, will spool to per-agent files
1465 rather than a single global file
1467 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1468 append to that spool. L<FS::Cron::upload> will then send the spool file to
1471 =item balanceover - if set, only spools the invoice if the total amount owed on
1472 this invoice and all older invoices is greater than the specified amount.
1474 =item time - the "current time". Controls the printing of past due messages
1482 my($self, %opt) = @_;
1484 my $time = $opt{'time'} || time;
1485 my $cust_main = $self->cust_main;
1487 if ( $opt{'dest'} ) {
1488 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1489 $cust_main->invoicing_list;
1490 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1491 || ! keys %invoicing_list;
1494 if ( $opt{'balanceover'} ) {
1496 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1499 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1500 mkdir $spooldir, 0700 unless -d $spooldir;
1502 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1505 if ( $opt{'agent_spools'} ) {
1506 $file = 'agentnum'.$cust_main->agentnum;
1511 if ( $opt{'upload_targetnum'} ) {
1512 $spooldir .= '/target'.$opt{'upload_targetnum'};
1513 mkdir $spooldir, 0700 unless -d $spooldir;
1514 } # otherwise it just goes into export.xxx/cust_bill
1516 if ( lc($opt{'format'}) eq 'billco' ) {
1520 $file = "$spooldir/$file.csv";
1522 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1524 open(CSV, ">>$file") or die "can't open $file: $!";
1525 flock(CSV, LOCK_EX);
1530 if ( lc($opt{'format'}) eq 'billco' ) {
1532 flock(CSV, LOCK_UN);
1535 $file =~ s/-header.csv$/-detail.csv/;
1537 open(CSV,">>$file") or die "can't open $file: $!";
1538 flock(CSV, LOCK_EX);
1542 print CSV $detail if defined($detail);
1544 flock(CSV, LOCK_UN);
1551 =item print_csv OPTION => VALUE, ...
1553 Returns CSV data for this invoice.
1557 format - 'default', 'billco', 'oneline', 'bridgestone'
1559 Returns a list consisting of two scalars. The first is a single line of CSV
1560 header information for this invoice. The second is one or more lines of CSV
1561 detail information for this invoice.
1563 If I<format> is not specified or "default", the fields of the CSV file are as
1566 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1567 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1571 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1573 B<record_type> is C<cust_bill> for the initial header line only. The
1574 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1575 fields are filled in.
1577 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1578 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1581 =item invnum - invoice number
1583 =item custnum - customer number
1585 =item _date - invoice date
1587 =item charged - total invoice amount
1589 =item first - customer first name
1591 =item last - customer first name
1593 =item company - company name
1595 =item address1 - address line 1
1597 =item address2 - address line 1
1607 =item pkg - line item description
1609 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1611 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1613 =item sdate - start date for recurring fee
1615 =item edate - end date for recurring fee
1619 If I<format> is "billco", the fields of the header CSV file are as follows:
1621 +-------------------------------------------------------------------+
1622 | FORMAT HEADER FILE |
1623 |-------------------------------------------------------------------|
1624 | Field | Description | Name | Type | Width |
1625 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1626 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1627 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1628 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1629 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1630 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1631 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1632 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
1633 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
1634 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
1635 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
1636 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
1637 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
1638 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
1639 | 15 | Previous Balance | BALFWD | NUM* | 9 |
1640 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
1641 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
1642 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
1643 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
1644 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
1645 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
1646 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
1647 | 23 | Y/N | AGESWITCH | CHAR | 1 |
1648 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
1649 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
1650 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
1651 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
1652 | 28 | State Tax*** | STATETAX | NUM* | 9 |
1653 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
1654 +-------+-------------------------------+------------+------+-------+
1656 If I<format> is "billco", the fields of the detail CSV file are as follows:
1658 FORMAT FOR DETAIL FILE
1660 Field | Description | Name | Type | Width
1661 1 | N/A-Leave Empty | RC | CHAR | 2
1662 2 | N/A-Leave Empty | CUSTID | CHAR | 15
1663 3 | Account Number | TRACCTNUM | CHAR | 15
1664 4 | Invoice Number | TRINVOICE | CHAR | 15
1665 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
1666 6 | Transaction Detail | DETAILS | CHAR | 100
1667 7 | Amount | AMT | NUM* | 9
1668 8 | Line Format Control** | LNCTRL | CHAR | 2
1669 9 | Grouping Code | GROUP | CHAR | 2
1670 10 | User Defined | ACCT CODE | CHAR | 15
1672 If format is 'oneline', there is no detail file. Each invoice has a
1673 header line only, with the fields:
1675 Agent number, agent name, customer number, first name, last name, address
1676 line 1, address line 2, city, state, zip, invoice date, invoice number,
1677 amount charged, amount due, previous balance, due date.
1679 and then, for each line item, three columns containing the package number,
1680 description, and amount.
1682 If format is 'bridgestone', there is no detail file. Each invoice has a
1683 header line with the following fields in a fixed-width format:
1685 Customer number (in display format), date, name (first last), company,
1686 address 1, address 2, city, state, zip.
1688 This is a mailing list format, and has no per-invoice fields. To avoid
1689 sending redundant notices, the spooling event should have a "once" or
1690 "once_percust_every" condition.
1695 my($self, %opt) = @_;
1697 eval "use Text::CSV_XS";
1700 my $cust_main = $self->cust_main;
1702 my $csv = Text::CSV_XS->new({'always_quote'=>1});
1703 my $format = lc($opt{'format'});
1705 my $time = $opt{'time'} || time;
1707 $self->set('_template', $opt{template})
1708 if exists $opt{template};
1710 my $tracctnum = ''; #leaking out from billco-specific sections :/
1711 if ( $format eq 'billco' ) {
1714 $self->conf->config('billco-account_num', $cust_main->agentnum);
1716 $tracctnum = $account_num eq 'display_custnum'
1717 ? $cust_main->display_custnum
1718 : $opt{'tracctnum'};
1721 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1723 my $duedate = $self->due_date2str('%m/%d/%Y'); # hardcoded, NOT date_format
1725 my( $previous_balance, @unused ) = $self->previous; #previous balance
1727 my $pmt_cr_applied = 0;
1728 $pmt_cr_applied += $_->{'amount'}
1729 foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1731 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1734 '', # 1 | N/A-Leave Empty CHAR 2
1735 '', # 2 | N/A-Leave Empty CHAR 15
1736 $tracctnum, # 3 | Transaction Account No CHAR 15
1737 $self->invnum, # 4 | Transaction Invoice No CHAR 15
1738 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
1739 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
1740 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
1741 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
1742 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
1743 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
1744 '', # 10 | Ancillary Billing Information CHAR 30
1745 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
1746 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
1749 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
1752 $duedate, # 14 | Bill Due Date CHAR 10
1754 $previous_balance, # 15 | Previous Balance NUM* 9
1755 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
1756 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
1757 $totaldue, # 18 | Total Amt Due NUM* 9
1758 $totaldue, # 19 | Total Amt Due NUM* 9
1759 '', # 20 | 30 Day Aging NUM* 9
1760 '', # 21 | 60 Day Aging NUM* 9
1761 '', # 22 | 90 Day Aging NUM* 9
1762 'N', # 23 | Y/N CHAR 1
1763 '', # 24 | Remittance automation CHAR 100
1764 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
1765 $self->custnum, # 26 | Customer Reference Number CHAR 15
1766 '0', # 27 | Federal Tax*** NUM* 9
1767 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
1768 '0', # 29 | Other Taxes & Fees*** NUM* 9
1771 } elsif ( $format eq 'oneline' ) { #name
1773 my ($previous_balance) = $self->previous;
1774 $previous_balance = sprintf('%.2f', $previous_balance);
1775 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1781 $self->_items_pkg, #_items_nontax? no sections or anything
1786 $cust_main->agentnum,
1787 $cust_main->agent->agent,
1791 $cust_main->company,
1792 $cust_main->address1,
1793 $cust_main->address2,
1799 time2str("%x", $self->_date),
1804 $self->due_date2str("%x"),
1809 } elsif ( $format eq 'bridgestone' ) {
1811 # bypass the CSV stuff and just return this
1812 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
1813 my $zip = $cust_main->zip;
1815 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
1819 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
1821 $cust_main->display_custnum,
1823 uc(substr($cust_main->contact_firstlast,0,30)),
1824 uc(substr($cust_main->company ,0,30)),
1825 uc(substr($cust_main->address1 ,0,30)),
1826 uc(substr($cust_main->address2 ,0,30)),
1827 uc(substr($cust_main->city ,0,20)),
1828 uc($cust_main->state),
1834 } elsif ( $format eq 'ics' ) {
1836 my $bill = $cust_main->bill_location;
1837 my $zip = $bill->zip;
1841 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
1846 # minor false laziness with print_generic
1847 my ($previous_balance) = $self->previous;
1848 my $balance_due = $self->owed + $previous_balance;
1849 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
1850 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
1853 if ( $self->due_date and $time >= $self->due_date ) {
1854 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
1858 my $header = sprintf(
1859 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
1860 $cust_main->display_custnum, #BID
1861 uc($cust_main->first), #FNAME
1862 uc($cust_main->last), #LNAME
1863 '00', #BATCH, should this ever be anything else?
1864 uc($cust_main->company), #COMP
1865 uc($bill->address1), #STREET1
1866 uc($bill->address2), #STREET2
1867 uc($bill->city), #CITY
1868 uc($bill->state), #STATE
1871 time2str('%Y%m%d', $self->_date), #BILL_DATE
1872 $self->due_date2str('%Y%m%d'), #DUE_DATE,
1873 ( map {sprintf('%0.2f', $_)}
1874 $balance_due, #AMNT_DUE
1875 $previous_balance, #PREV_BAL
1876 $payment_total, #PYMT_RCVD
1877 $credit_total, #CREDITS
1878 $previous_balance, #BEG_BAL--is this correct?
1879 $self->charged, #NEW_CHRG
1882 $past_due, #PAST_MSG
1886 my %svc_class = ('' => ''); # maybe cache this more persistently?
1888 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1890 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
1891 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
1895 my @dates = ( $self->_date, undef );
1896 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
1897 $dates[1] = $prev->sdate; #questionable
1900 # generate an 01 detail for each service
1901 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
1902 foreach my $cust_svc ( @svcs ) {
1903 $show_pkgnum = ''; # hide it if we're showing svcnums
1905 my $svcpart = $cust_svc->svcpart;
1906 if (!exists($svc_class{$svcpart})) {
1907 my $classnum = $cust_svc->part_svc->classnum;
1908 my $part_svc_class = FS::part_svc_class->by_key($classnum)
1910 $svc_class{$svcpart} = $part_svc_class ?
1911 $part_svc_class->classname :
1915 my @h_label = $cust_svc->label(@dates, 'I');
1916 push @details, sprintf('01%-9s%-20s%-47s',
1918 $svc_class{$svcpart},
1921 } #foreach $cust_svc
1924 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
1925 if ($cust_bill_pkg->recur > 0) {
1926 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
1927 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
1929 push @details, sprintf('02%-6s%-60s%-10s',
1932 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
1934 } #foreach $cust_bill_pkg
1936 # Tag this row so that we know whether this is one page (1), two pages
1937 # (2), # or "big" (B). The tag will be stripped off before uploading.
1938 if ( scalar(@details) < 12 ) {
1940 } elsif ( scalar(@details) < 58 ) {
1946 return join('', $header, @details, "\n");
1954 time2str("%x", $self->_date),
1955 sprintf("%.2f", $self->charged),
1956 ( map { $cust_main->getfield($_) }
1957 qw( first last company address1 address2 city state zip country ) ),
1959 ) or die "can't create csv";
1962 my $header = $csv->string. "\n";
1965 if ( lc($opt{'format'}) eq 'billco' ) {
1968 my %items_opt = ( format => 'template',
1969 escape_function => sub { shift } );
1970 # I don't know what characters billco actually tolerates in spool entries.
1971 # Text::CSV will take care of delimiters, though.
1973 my @items = ( $self->_items_pkg(%items_opt),
1974 $self->_items_fee(%items_opt) );
1975 foreach my $item (@items) {
1977 my $description = $item->{'description'};
1978 if ( $item->{'_is_discount'} and exists($item->{ext_description}[0]) ) {
1979 $description .= ': ' . $item->{ext_description}[0];
1983 '', # 1 | N/A-Leave Empty CHAR 2
1984 '', # 2 | N/A-Leave Empty CHAR 15
1985 $tracctnum, # 3 | Account Number CHAR 15
1986 $self->invnum, # 4 | Invoice Number CHAR 15
1987 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
1988 $description, # 6 | Transaction Detail CHAR 100
1989 $item->{'amount'}, # 7 | Amount NUM* 9
1990 '', # 8 | Line Format Control** CHAR 2
1991 '', # 9 | Grouping Code CHAR 2
1992 '', # 10 | User Defined CHAR 15
1995 $detail .= $csv->string. "\n";
1999 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2005 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2007 my($pkg, $setup, $recur, $sdate, $edate);
2008 if ( $cust_bill_pkg->pkgnum ) {
2010 ($pkg, $setup, $recur, $sdate, $edate) = (
2011 $cust_bill_pkg->part_pkg->pkg,
2012 ( $cust_bill_pkg->setup != 0
2013 ? sprintf("%.2f", $cust_bill_pkg->setup )
2015 ( $cust_bill_pkg->recur != 0
2016 ? sprintf("%.2f", $cust_bill_pkg->recur )
2018 ( $cust_bill_pkg->sdate
2019 ? time2str("%x", $cust_bill_pkg->sdate)
2021 ($cust_bill_pkg->edate
2022 ? time2str("%x", $cust_bill_pkg->edate)
2026 } else { #pkgnum tax
2027 next unless $cust_bill_pkg->setup != 0;
2028 $pkg = $cust_bill_pkg->desc;
2029 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2030 ( $sdate, $edate ) = ( '', '' );
2036 ( map { '' } (1..11) ),
2037 ($pkg, $setup, $recur, $sdate, $edate)
2038 ) or die "can't create csv";
2040 $detail .= $csv->string. "\n";
2046 ( $header, $detail );
2051 croak 'cust_bill->comp is deprecated (COMP payments are deprecated)';
2056 Attempts to pay this invoice with a credit card payment via a
2057 Business::OnlinePayment realtime gateway. See
2058 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2059 for supported processors.
2065 $self->realtime_bop( 'CC', @_ );
2070 Attempts to pay this invoice with an electronic check (ACH) payment via a
2071 Business::OnlinePayment realtime gateway. See
2072 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2073 for supported processors.
2079 $self->realtime_bop( 'ECHECK', @_ );
2084 Attempts to pay this invoice with phone bill (LEC) payment via a
2085 Business::OnlinePayment realtime gateway. See
2086 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2087 for supported processors.
2093 $self->realtime_bop( 'LEC', @_ );
2097 my( $self, $method ) = (shift,shift);
2098 my $conf = $self->conf;
2101 my $cust_main = $self->cust_main;
2102 my $balance = $cust_main->balance;
2103 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2104 $amount = sprintf("%.2f", $amount);
2105 return "not run (balance $balance)" unless $amount > 0;
2107 my $description = 'Internet Services';
2108 if ( $conf->exists('business-onlinepayment-description') ) {
2109 my $dtempl = $conf->config('business-onlinepayment-description');
2111 my $agent_obj = $cust_main->agent
2112 or die "can't retreive agent for $cust_main (agentnum ".
2113 $cust_main->agentnum. ")";
2114 my $agent = $agent_obj->agent;
2115 my $pkgs = join(', ',
2116 map { $_->part_pkg->pkg }
2117 grep { $_->pkgnum } $self->cust_bill_pkg
2119 $description = eval qq("$dtempl");
2122 $cust_main->realtime_bop($method, $amount,
2123 'description' => $description,
2124 'invnum' => $self->invnum,
2125 #this didn't do what we want, it just calls apply_payments_and_credits
2127 'apply_to_invoice' => 1,
2130 #this changes application behavior: auto payments
2131 #triggered against a specific invoice are now applied
2132 #to that invoice instead of oldest open.
2138 =item batch_card OPTION => VALUE...
2140 Adds a payment for this invoice to the pending credit card batch (see
2141 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2142 runs the payment using a realtime gateway.
2147 my ($self, %options) = @_;
2148 my $cust_main = $self->cust_main;
2150 $options{invnum} = $self->invnum;
2152 $cust_main->batch_card(%options);
2155 sub _agent_template {
2157 $self->cust_main->agent_template;
2160 sub _agent_invoice_from {
2162 $self->cust_main->agent_invoice_from;
2165 =item invoice_barcode DIR_OR_FALSE
2167 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2168 it is taken as the temp directory where the PNG file will be generated and the
2169 PNG file name is returned. Otherwise, the PNG image itself is returned.
2173 sub invoice_barcode {
2174 my ($self, $dir) = (shift,shift);
2176 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2177 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2178 my $gd = $gdbar->plot(Height => 30);
2181 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2185 ) or die "can't open temp file: $!\n";
2186 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2187 my $png_file = $bh->filename;
2194 =item invnum_date_pretty
2196 Returns a string with the invoice number and date, for example:
2197 "Invoice #54 (3/20/2008)".
2199 Intended for back-end context, with regard to translation and date formatting.
2203 #note: this uses _date_pretty_unlocalized because _date_pretty is too expensive
2204 # for backend use (and also does the wrong thing, localizing for end customer
2205 # instead of backoffice configured date format)
2206 sub invnum_date_pretty {
2208 #$self->mt('Invoice #').
2209 'Invoice #'. #XXX should be translated ala web UI user (not invoice customer)
2210 $self->invnum. ' ('. $self->_date_pretty_unlocalized. ')';
2213 #sub _items_extra_usage_sections {
2215 # my $escape = shift;
2217 # my %sections = ();
2219 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2220 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2222 # next unless $cust_bill_pkg->pkgnum > 0;
2224 # foreach my $section ( keys %usage_class ) {
2226 # my $usage = $cust_bill_pkg->usage($section);
2228 # next unless $usage && $usage > 0;
2230 # $sections{$section} ||= 0;
2231 # $sections{$section} += $usage;
2237 # map { { 'description' => &{$escape}($_),
2238 # 'subtotal' => $sections{$_},
2239 # 'summarized' => '',
2240 # 'tax_section' => '',
2243 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2247 sub _items_extra_usage_sections {
2249 my $conf = $self->conf;
2257 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2259 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2260 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2261 next unless $cust_bill_pkg->pkgnum > 0;
2263 foreach my $classnum ( keys %usage_class ) {
2264 my $section = $usage_class{$classnum}->classname;
2265 $classnums{$section} = $classnum;
2267 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2268 my $amount = $detail->amount;
2269 next unless $amount && $amount > 0;
2271 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2272 $sections{$section}{amount} += $amount; #subtotal
2273 $sections{$section}{calls}++;
2274 $sections{$section}{duration} += $detail->duration;
2276 my $desc = $detail->regionname;
2277 my $description = $desc;
2278 $description = substr($desc, 0, $maxlength). '...'
2279 if $format eq 'latex' && length($desc) > $maxlength;
2281 $lines{$section}{$desc} ||= {
2282 description => &{$escape}($description),
2283 #pkgpart => $part_pkg->pkgpart,
2284 pkgnum => $cust_bill_pkg->pkgnum,
2289 #unit_amount => $cust_bill_pkg->unitrecur,
2290 quantity => $cust_bill_pkg->quantity,
2291 product_code => 'N/A',
2292 ext_description => [],
2295 $lines{$section}{$desc}{amount} += $amount;
2296 $lines{$section}{$desc}{calls}++;
2297 $lines{$section}{$desc}{duration} += $detail->duration;
2303 my %sectionmap = ();
2304 foreach (keys %sections) {
2305 my $usage_class = $usage_class{$classnums{$_}};
2306 $sectionmap{$_} = { 'description' => &{$escape}($_),
2307 'amount' => $sections{$_}{amount}, #subtotal
2308 'calls' => $sections{$_}{calls},
2309 'duration' => $sections{$_}{duration},
2311 'tax_section' => '',
2312 'sort_weight' => $usage_class->weight,
2313 ( $usage_class->format
2314 ? ( map { $_ => $usage_class->$_($format) }
2315 qw( description_generator header_generator total_generator total_line_generator )
2322 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2326 foreach my $section ( keys %lines ) {
2327 foreach my $line ( keys %{$lines{$section}} ) {
2328 my $l = $lines{$section}{$line};
2329 $l->{section} = $sectionmap{$section};
2330 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2331 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2336 return(\@sections, \@lines);
2342 my $end = $self->_date;
2344 # start at date of previous invoice + 1 second or 0 if no previous invoice
2345 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2346 $start = 0 if !$start;
2349 my $cust_main = $self->cust_main;
2350 my @pkgs = $cust_main->all_pkgs;
2351 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2354 foreach my $pkg ( @pkgs ) {
2355 my @h_cust_svc = $pkg->h_cust_svc($end);
2356 foreach my $h_cust_svc ( @h_cust_svc ) {
2357 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2358 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2360 my $inserted = $h_cust_svc->date_inserted;
2361 my $deleted = $h_cust_svc->date_deleted;
2362 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2364 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2366 # DID either activated or ported in; cannot be both for same DID simultaneously
2367 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2368 && (!$phone_inserted->lnp_status
2369 || $phone_inserted->lnp_status eq ''
2370 || $phone_inserted->lnp_status eq 'native')) {
2373 else { # this one not so clean, should probably move to (h_)svc_phone
2374 local($FS::Record::qsearch_qualify_columns) = 0;
2375 my $phone_portedin = qsearchs( 'h_svc_phone',
2376 { 'svcnum' => $h_cust_svc->svcnum,
2377 'lnp_status' => 'portedin' },
2378 FS::h_svc_phone->sql_h_searchs($end),
2380 $num_portedin++ if $phone_portedin;
2383 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2384 if($deleted >= $start && $deleted <= $end && $phone_deleted
2385 && (!$phone_deleted->lnp_status
2386 || $phone_deleted->lnp_status ne 'portingout')) {
2389 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2390 && $phone_deleted->lnp_status
2391 && $phone_deleted->lnp_status eq 'portingout') {
2395 # increment usage minutes
2396 if ( $phone_inserted ) {
2397 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2398 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2401 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2404 # don't look at this service again
2405 push @seen, $h_cust_svc->svcnum;
2409 $minutes = sprintf("%d", $minutes);
2410 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2411 . "$num_deactivated Ported-Out: $num_portedout ",
2412 "Total Minutes: $minutes");
2415 sub _items_accountcode_cdr {
2420 my $section = { 'amount' => 0,
2423 'sort_weight' => '',
2425 'description' => 'Usage by Account Code',
2431 my %accountcodes = ();
2433 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2434 next unless $cust_bill_pkg->pkgnum > 0;
2436 my @header = $cust_bill_pkg->details_header;
2437 next unless scalar(@header);
2438 $section->{'header'} = join(',',@header);
2440 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2442 $section->{'header'} = $detail->formatted('format' => $format)
2443 if($detail->detail eq $section->{'header'});
2445 my $accountcode = $detail->accountcode;
2446 next unless $accountcode;
2448 my $amount = $detail->amount;
2449 next unless $amount && $amount > 0;
2451 $accountcodes{$accountcode} ||= {
2452 description => $accountcode,
2459 product_code => 'N/A',
2460 section => $section,
2461 ext_description => [ $section->{'header'} ],
2465 $section->{'amount'} += $amount;
2466 $accountcodes{$accountcode}{'amount'} += $amount;
2467 $accountcodes{$accountcode}{calls}++;
2468 $accountcodes{$accountcode}{duration} += $detail->duration;
2469 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2473 foreach my $l ( values %accountcodes ) {
2474 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2475 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2476 foreach my $sorted_detail ( @sorted_detail ) {
2477 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2479 delete $l->{detail_temp};
2483 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2485 return ($section,\@sorted_lines);
2488 sub _items_svc_phone_sections {
2490 my $conf = $self->conf;
2498 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
2500 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2501 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2503 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2504 next unless $cust_bill_pkg->pkgnum > 0;
2506 my @header = $cust_bill_pkg->details_header;
2507 next unless scalar(@header);
2509 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2511 my $phonenum = $detail->phonenum;
2512 next unless $phonenum;
2514 my $amount = $detail->amount;
2515 next unless $amount && $amount > 0;
2517 $sections{$phonenum} ||= { 'amount' => 0,
2520 'sort_weight' => -1,
2521 'phonenum' => $phonenum,
2523 $sections{$phonenum}{amount} += $amount; #subtotal
2524 $sections{$phonenum}{calls}++;
2525 $sections{$phonenum}{duration} += $detail->duration;
2527 my $desc = $detail->regionname;
2528 my $description = $desc;
2529 $description = substr($desc, 0, $maxlength). '...'
2530 if $format eq 'latex' && length($desc) > $maxlength;
2532 $lines{$phonenum}{$desc} ||= {
2533 description => &{$escape}($description),
2534 #pkgpart => $part_pkg->pkgpart,
2542 product_code => 'N/A',
2543 ext_description => [],
2546 $lines{$phonenum}{$desc}{amount} += $amount;
2547 $lines{$phonenum}{$desc}{calls}++;
2548 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2550 my $line = $usage_class{$detail->classnum}->classname;
2551 $sections{"$phonenum $line"} ||=
2555 'sort_weight' => $usage_class{$detail->classnum}->weight,
2556 'phonenum' => $phonenum,
2557 'header' => [ @header ],
2559 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2560 $sections{"$phonenum $line"}{calls}++;
2561 $sections{"$phonenum $line"}{duration} += $detail->duration;
2563 $lines{"$phonenum $line"}{$desc} ||= {
2564 description => &{$escape}($description),
2565 #pkgpart => $part_pkg->pkgpart,
2573 product_code => 'N/A',
2574 ext_description => [],
2577 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2578 $lines{"$phonenum $line"}{$desc}{calls}++;
2579 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2580 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2581 $detail->formatted('format' => $format);
2586 my %sectionmap = ();
2587 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2588 foreach ( keys %sections ) {
2589 my @header = @{ $sections{$_}{header} || [] };
2591 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2592 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2593 my $usage_class = $summary ? $simple : $usage_simple;
2594 my $ending = $summary ? ' usage charges' : '';
2597 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2599 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2600 'amount' => $sections{$_}{amount}, #subtotal
2601 'calls' => $sections{$_}{calls},
2602 'duration' => $sections{$_}{duration},
2604 'tax_section' => '',
2605 'phonenum' => $sections{$_}{phonenum},
2606 'sort_weight' => $sections{$_}{sort_weight},
2607 'post_total' => $summary, #inspire pagebreak
2609 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2610 qw( description_generator
2613 total_line_generator
2620 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2621 $a->{sort_weight} <=> $b->{sort_weight}
2626 foreach my $section ( keys %lines ) {
2627 foreach my $line ( keys %{$lines{$section}} ) {
2628 my $l = $lines{$section}{$line};
2629 $l->{section} = $sectionmap{$section};
2630 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2631 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2636 if($conf->exists('phone_usage_class_summary')) {
2637 # this only works with Latex
2641 # after this, we'll have only two sections per DID:
2642 # Calls Summary and Calls Detail
2643 foreach my $section ( @sections ) {
2644 if($section->{'post_total'}) {
2645 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2646 $section->{'total_line_generator'} = sub { '' };
2647 $section->{'total_generator'} = sub { '' };
2648 $section->{'header_generator'} = sub { '' };
2649 $section->{'description_generator'} = '';
2650 push @newsections, $section;
2651 my %calls_detail = %$section;
2652 $calls_detail{'post_total'} = '';
2653 $calls_detail{'sort_weight'} = '';
2654 $calls_detail{'description_generator'} = sub { '' };
2655 $calls_detail{'header_generator'} = sub {
2656 return ' & Date/Time & Called Number & Duration & Price'
2657 if $format eq 'latex';
2660 $calls_detail{'description'} = 'Calls Detail: '
2661 . $section->{'phonenum'};
2662 push @newsections, \%calls_detail;
2666 # after this, each usage class is collapsed/summarized into a single
2667 # line under the Calls Summary section
2668 foreach my $newsection ( @newsections ) {
2669 if($newsection->{'post_total'}) { # this means Calls Summary
2670 foreach my $section ( @sections ) {
2671 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
2672 && !$section->{'post_total'});
2673 my $newdesc = $section->{'description'};
2674 my $tn = $section->{'phonenum'};
2675 $newdesc =~ s/$tn//g;
2676 my $line = { ext_description => [],
2680 calls => $section->{'calls'},
2681 section => $newsection,
2682 duration => $section->{'duration'},
2683 description => $newdesc,
2684 amount => sprintf("%.2f",$section->{'amount'}),
2685 product_code => 'N/A',
2687 push @newlines, $line;
2692 # after this, Calls Details is populated with all CDRs
2693 foreach my $newsection ( @newsections ) {
2694 if(!$newsection->{'post_total'}) { # this means Calls Details
2695 foreach my $line ( @lines ) {
2696 next unless (scalar(@{$line->{'ext_description'}}) &&
2697 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2699 my @extdesc = @{$line->{'ext_description'}};
2701 foreach my $extdesc ( @extdesc ) {
2702 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2703 push @newextdesc, $extdesc;
2705 $line->{'ext_description'} = \@newextdesc;
2706 $line->{'section'} = $newsection;
2707 push @newlines, $line;
2712 return(\@newsections, \@newlines);
2715 return(\@sections, \@lines);
2719 =item _items_usage_class_summary OPTIONS
2721 Returns a list of detail items summarizing the usage charges on this
2722 invoice. Each one will have 'amount', 'description' (the usage charge name),
2723 and 'usage_classnum'.
2725 OPTIONS can include 'escape' (a function to escape the descriptions).
2729 sub _items_usage_class_summary {
2733 my $escape = $opt{escape} || sub { $_[0] };
2734 my $money_char = $opt{money_char};
2735 my $invnum = $self->invnum;
2736 my @classes = qsearch({
2737 'table' => 'usage_class',
2738 'select' => 'classnum, classname, SUM(amount) AS amount,'.
2739 ' COUNT(*) AS calls, SUM(duration) AS duration',
2740 'addl_from' => ' LEFT JOIN cust_bill_pkg_detail USING (classnum)' .
2741 ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
2742 'extra_sql' => " WHERE cust_bill_pkg.invnum = $invnum".
2743 ' GROUP BY classnum, classname, weight'.
2744 ' HAVING (usage_class.disabled IS NULL OR SUM(amount) > 0)'.
2745 ' ORDER BY weight ASC',
2749 description => &{$escape}($self->mt('Usage Summary')),
2753 foreach my $class (@classes) {
2754 $section->{subtotal} += $class->get('amount');
2756 'description' => &{$escape}($class->classname),
2757 'amount' => $money_char.sprintf('%.2f', $class->get('amount')),
2758 'quantity' => $class->get('calls'),
2759 'duration' => $class->get('duration'),
2760 'usage_classnum' => $class->classnum,
2761 'section' => $section,
2764 $section->{subtotal} = $money_char.sprintf('%.2f', $section->{subtotal});
2768 =item _items_previous()
2770 Returns an array of hashrefs, each hashref representing a line-item on
2771 the current bill for previous unpaid invoices.
2773 keys for each previous_item:
2774 - amount (see notes)
2780 Payments and credits shown on this invoice may vary based on configuraiton.
2782 when conf flag previous_balance-payments_since is set:
2783 This method works backwards to rebuild the invoice as a snapshot in time.
2784 The invoice displayed will have the balances owed, and payments made,
2785 reflecting the state of the account at the time of invoice generation.
2789 sub _items_previous {
2794 if ($self->get('_items_previous')) {
2795 return sort { $a->{_date} <=> $b->{_date} }
2796 values %{ $self->get('_items_previous') };
2799 # Gets the customer's current balance and outstanding invoices.
2800 my ($prev_balance, @open_invoices) = $self->previous;
2802 my %invoices = map {
2803 $_->invnum => $self->__items_previous_map_invoice($_)
2806 # Which credits and payments displayed on the bill will vary based on
2807 # conf flag previous_balance-payments_since.
2808 my @credits = $self->_items_credits();
2809 my @payments = $self->_items_payments();
2812 if ($self->conf->exists('previous_balance-payments_since')) {
2813 # For each credit or payment, determine which invoices it was applied to.
2814 # Manipulate data displayed so the invoice displayed appears as a
2815 # snapshot in time... with previous balances and balance owed displayed
2816 # as they were at the time of invoice creation.
2818 my @credits_postbill = $self->_items_credits_postbill();
2819 my @payments_postbill = $self->_items_payments_postbill();
2824 # Each section below follows this pattern on a payment/credit
2826 # - Dupe check, avoid adjusting for the same item twice
2827 # - If invoice being adjusted for isn't in our list, add it
2828 # - Adjust the invoice balance to refelct balnace without the
2829 # credit or payment applied
2832 # Working with payments displayed on this bill
2833 for my $pmt_hash (@payments) {
2834 my $pmt_obj = qsearchs('cust_pay', {paynum => $pmt_hash->{paynum}});
2835 for my $cust_bill_pay ($pmt_obj->cust_bill_pay) {
2836 next if exists $pmnt_dupechk{$cust_bill_pay->billpaynum};
2837 $pmnt_dupechk{$cust_bill_pay->billpaynum} = 1;
2839 my $invnum = $cust_bill_pay->invnum;
2841 $invoices{$invnum} = $self->__items_previous_get_invoice($invnum)
2842 unless exists $invoices{$invnum};
2844 $invoices{$invnum}->{amount} += $cust_bill_pay->amount;
2848 # Working with credits displayed on this bill
2849 for my $cred_hash (@credits) {
2850 my $cred_obj = qsearchs('cust_credit', {crednum => $cred_hash->{crednum}});
2851 for my $cust_credit_bill ($cred_obj->cust_credit_bill) {
2852 next if exists $cred_dupechk{$cust_credit_bill->creditbillnum};
2853 $cred_dupechk{$cust_credit_bill->creditbillnum} = 1;
2855 my $invnum = $cust_credit_bill->invnum;
2857 $invoices{$invnum} = $self->__items_previous_get_invoice($invnum)
2858 unless exists $invoices{$invnum};
2860 $invoices{$invnum}->{amount} += $cust_credit_bill->amount;
2864 # Working with both credits and payments which are not displayed
2865 # on this bill, but which have affected this bill's balances
2866 for my $postbill (@payments_postbill, @credits_postbill) {
2868 if ($postbill->{billpaynum}) {
2869 next if exists $pmnt_dupechk{$postbill->{billpaynum}};
2870 $pmnt_dupechk{$postbill->{billpaynum}} = 1;
2871 } elsif ($postbill->{creditbillnum}) {
2872 next if exists $cred_dupechk{$postbill->{creditbillnum}};
2873 $cred_dupechk{$postbill->{creditbillnum}} = 1;
2875 die "Missing creditbillnum or billpaynum";
2878 my $invnum = $postbill->{invnum};
2880 $invoices{$invnum} = $self->__items_previous_get_invoice($invnum)
2881 unless exists $invoices{$invnum};
2883 $invoices{$invnum}->{amount} += $postbill->{amount};
2886 # Make sure current invoice doesn't appear in previous items
2887 delete $invoices{$self->invnum}
2888 if exists $invoices{$self->invnum};
2892 # Make sure amount is formatted as a dollar string
2893 # (Formatting should happen on the template side, but is not?)
2894 $invoices{$_}->{amount} = sprintf('%.2f',$invoices{$_}->{amount})
2897 $self->set('_items_previous', \%invoices);
2898 return sort { $a->{_date} <=> $b->{_date} } values %invoices;
2902 =item _items_previous_total
2904 Return sum of amounts from all items returned by _items_previous
2905 Results will vary based on invoicing conf flags
2909 sub _items_previous_total {
2912 $tot += $_->{amount} for $self->_items_previous();
2916 sub __items_previous_get_invoice {
2917 # Helper function for _items_previous
2919 # Read a record from cust_bill, return a hash of it's information
2920 my ($self, $invnum) = @_;
2921 die "Incorrect usage of __items_previous_get_invoice()" unless $invnum;
2923 my $cust_bill = qsearchs('cust_bill', {invnum => $invnum});
2924 return $self->__items_previous_map_invoice($cust_bill);
2927 sub __items_previous_map_invoice {
2928 # Helper function for _items_previous
2930 # Transform a cust_bill object into a simple hash reference of the type
2931 # required by _items_previous
2932 my ($self, $cust_bill) = @_;
2933 die "Incorrect usage of __items_previous_map_invoice" unless ref $cust_bill;
2935 my $date = $self->conf->exists('invoice_show_prior_due_date')
2936 ? 'due '.$cust_bill->due_date2str('short')
2937 : $self->time2str_local('short', $cust_bill->_date);
2940 invnum => $cust_bill->invnum,
2941 amount => $cust_bill->owed,
2943 _date => $cust_bill->_date,
2944 description => join(' ',
2945 $self->mt('Previous Balance, Invoice #'),
2952 =item _items_credits()
2954 Return array of hashrefs containing credits to be shown as line-items
2955 when rendering this bill.
2957 keys for each credit item:
2958 - crednum: id of payment
2959 - amount: payment amount
2960 - description: line item to be displayed on the bill
2962 This method has three ways it selects which credits to display on
2965 1) Default Case: No Conf flag for 'previous_balance-payments_since'
2967 Returns credits that have been applied to this bill only
2970 Conf flag set for 'previous_balance-payments_since'
2972 List all credits that have been recorded during the time period
2973 between the timestamps of the last invoice and this invoice
2976 Conf flag set for 'previous_balance-payments_since'
2977 $opt{'template'} eq 'statement'
2979 List all payments that have been recorded between the timestamps
2980 of the previous invoice and the following invoice.
2982 This is used to give the customer a receipt for a payment
2983 in the form of their last bill with the payment amended.
2985 I am concerned with this implementation, but leaving in place as is
2986 If this option is selected, while viewing an older bill, the old bill
2987 will show ALL future credits for future bills, but no charges for
2988 future bills. Somebody could be misled into believing they have a
2989 large account credit when they don't. Also, interrupts the chain of
2990 invoices as an account history... the customer could have two invoices
2991 in their fileing cabinet, for two different dates, both with a line item
2992 for the same duplicate credit. The accounting is technically accurate,
2993 but somebody could easily become confused and think two credits were
2994 made, when really those two line items on two different bills represent
2995 only a single credit
2999 sub _items_credits {
3004 return @{$self->get('_items_credits')} if $self->get('_items_credits');
3007 my $template = $opt{template} || $self->get('_template');
3008 my $trim_len = $opt{template} || $self->get('trim_len') || 40;
3011 my @cust_credit_objs;
3013 if ($self->conf->exists('previous_balance-payments_since')) {
3014 if ($template eq 'statement') {
3015 # Case 3 (see above)
3016 # Return credits timestamped between the previous and following bills
3018 my $previous_bill = $self->previous_bill;
3019 my $following_bill = $self->following_bill;
3021 my $date_start = ref $previous_bill ? $previous_bill->_date : 0;
3022 my $date_end = ref $following_bill ? $following_bill->_date : undef;
3025 table => 'cust_credit',
3027 custnum => $self->custnum,
3028 _date => { op => '>=', value => $date_start },
3031 $query{extra_sql} = " AND _date <= $date_end " if $date_end;
3033 @cust_credit_objs = qsearch(\%query);
3036 # Case 2 (see above)
3037 # Return credits timestamps between this and the previous bills
3040 my $date_end = $self->_date;
3042 my $previous_bill = $self->previous_bill;
3043 if (ref $previous_bill) {
3044 $date_start = $previous_bill->_date;
3047 @cust_credit_objs = qsearch({
3048 table => 'cust_credit',
3050 custnum => $self->custnum,
3051 _date => {op => '>=', value => $date_start},
3053 extra_sql => " AND _date <= $date_end ",
3058 # Case 1 (see above)
3059 # Return only credits that have been applied to this bill
3061 @cust_credit_objs = $self->cust_credited;
3065 # Translate objects into hashrefs
3066 foreach my $obj ( @cust_credit_objs ) {
3067 my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3069 amount => sprintf('%.2f',$cust_credit->amount),
3070 crednum => $cust_credit->crednum,
3071 _date => $cust_credit->_date,
3072 creditreason => $cust_credit->reason,
3075 my $reason = substr($cust_credit->reason, 0, $trim_len);
3076 $reason .= '...' if length($reason) < length($cust_credit->reason);
3077 $reason = "($reason)" if $reason;
3079 $r_obj{description} = join(' ',
3080 $self->mt('Credit applied'),
3081 $self->time2str_local('short', $cust_credit->_date),
3085 push @return, \%r_obj;
3087 $self->set('_items_credits',\@return);
3091 =item _items_credits_total
3093 Return the total of al items from _items_credits
3094 Will vary based on invoice display conf flag
3098 sub _items_credits_total {
3101 $tot += $_->{amount} for $self->_items_credits();
3107 =item _items_credits_postbill()
3109 Returns an array of hashrefs for credits where
3110 - Credit issued after this invoice
3111 - Credit applied to an invoice before this invoice
3113 Returned hashrefs are of the format returned by _items_credits()
3117 sub _items_credits_postbill {
3120 my @cust_credit_bill = qsearch({
3121 table => 'cust_credit_bill',
3122 select => join(', ',qw(
3123 cust_credit_bill.creditbillnum
3124 cust_credit_bill._date
3125 cust_credit_bill.invnum
3126 cust_credit_bill.amount
3128 addl_from => ' LEFT JOIN cust_credit'.
3129 ' ON (cust_credit_bill.crednum = cust_credit.crednum) ',
3130 extra_sql => ' WHERE cust_credit.custnum = '.$self->custnum.
3131 ' AND cust_credit_bill._date > '.$self->_date.
3132 ' AND cust_credit_bill.invnum < '.$self->invnum.' ',
3133 #! did not investigate why hashref doesn't work for this join query
3135 # 'cust_credit.custnum' => {op => '=', value => $self->custnum},
3136 # 'cust_credit_bill._date' => {op => '>', value => $self->_date},
3137 # 'cust_credit_bill.invnum' => {op => '<', value => $self->invnum},
3143 invnum => $_->invnum,
3144 amount => $_->amount,
3145 creditbillnum => $_->creditbillnum,
3146 }} @cust_credit_bill;
3149 =item _items_payments_postbill()
3151 Returns an array of hashrefs for payments where
3152 - Payment occured after this invoice
3153 - Payment applied to an invoice before this invoice
3155 Returned hashrefs are of the format returned by _items_payments()
3159 sub _items_payments_postbill {
3162 my @cust_bill_pay = qsearch({
3163 table => 'cust_bill_pay',
3164 select => join(', ',qw(
3165 cust_bill_pay.billpaynum
3167 cust_bill_pay.invnum
3168 cust_bill_pay.amount
3170 addl_from => ' LEFT JOIN cust_bill'.
3171 ' ON (cust_bill_pay.invnum = cust_bill.invnum) ',
3172 extra_sql => ' WHERE cust_bill.custnum = '.$self->custnum.
3173 ' AND cust_bill_pay._date > '.$self->_date.
3174 ' AND cust_bill_pay.invnum < '.$self->invnum.' ',
3179 invnum => $_->invnum,
3180 amount => $_->amount,
3181 billpaynum => $_->billpaynum,
3185 =item _items_payments()
3187 Return array of hashrefs containing payments to be shown as line-items
3188 when rendering this bill.
3190 keys for each payment item:
3191 - paynum: id of payment
3192 - amount: payment amount
3193 - description: line item to be displayed on the bill
3195 This method has three ways it selects which payments to display on
3198 1) Default Case: No Conf flag for 'previous_balance-payments_since'
3200 Returns payments that have been applied to this bill only
3203 Conf flag set for 'previous_balance-payments_since'
3205 List all payments that have been recorded between the timestamps
3206 of the previous invoice and this invoice
3209 Conf flag set for 'previous_balance-payments_since'
3210 $opt{'template'} eq 'statement'
3212 List all payments that have been recorded between the timestamps
3213 of the previous invoice and the following invoice.
3215 I am concerned with this implementation, but leaving in place as is
3216 If this option is selected, while viewing an older bill, the old bill
3217 will show ALL future payments for future bills, but no charges for
3218 future bills. Somebody could be misled into believing they have a
3219 large account credit when they don't. Also, interrupts the chain of
3220 invoices as an account history... the customer could have two invoices
3221 in their fileing cabinet, for two different dates, both with a line item
3222 for the same duplicate payment. The accounting is technically accurate,
3223 but somebody could easily become confused and think two payments were
3224 made, when really those two line items on two different bills represent
3225 only a single payment.
3229 sub _items_payments {
3234 return @{$self->get('_items_payments')} if $self->get('_items_payments');
3237 my $template = $opt{template} || $self->get('_template');
3242 my $c_invoice_payment_details = $self->conf->exists('invoice_payment_details');
3244 if ($self->conf->exists('previous_balance-payments_since')) {
3245 if ($template eq 'statement') {
3246 # Case 3 (see above)
3247 # Return payments timestamped between the previous and following bills
3249 my $previous_bill = $self->previous_bill;
3250 my $following_bill = $self->following_bill;
3252 my $date_start = ref $previous_bill ? $previous_bill->_date : 0;
3253 my $date_end = ref $following_bill ? $following_bill->_date : undef;
3256 table => 'cust_pay',
3258 custnum => $self->custnum,
3259 _date => { op => '>=', value => $date_start },
3262 $query{extra_sql} = " AND _date <= $date_end " if $date_end;
3264 @cust_pay_objs = qsearch(\%query);
3267 # Case 2 (see above)
3268 # Return payments timestamped between this and the previous bill
3271 my $date_end = $self->_date;
3273 my $previous_bill = $self->previous_bill;
3274 if (ref $previous_bill) {
3275 $date_start = $previous_bill->_date;
3278 @cust_pay_objs = qsearch({
3279 table => 'cust_pay',
3281 custnum => $self->custnum,
3282 _date => {op => '>=', value => $date_start},
3284 extra_sql => " AND _date <= $date_end ",
3289 # Case 1 (see above)
3290 # Return payments applied only to this bill
3292 @cust_pay_objs = $self->cust_bill_pay;
3298 [ $self->__items_payments_make_hashref(@cust_pay_objs) ]
3300 return @{ $self->get('_items_payments') };
3303 =item _items_payments_total
3305 Return a total of all records returned by _items_payments
3306 Results vary based on invoicing conf flags
3310 sub _items_payments_total {
3313 $tot += $_->{amount} for $self->_items_payments();
3317 sub __items_payments_make_hashref {
3318 # Transform a FS::cust_pay object into a simple hashref for invoice
3319 my ($self, @cust_pay_objs) = @_;
3320 my $c_invoice_payment_details = $self->conf->exists('invoice_payment_details');
3323 for my $obj (@cust_pay_objs) {
3325 # In case we're passed FS::cust_bill_pay (or something else?)
3326 # Below, we use $obj to render amount rather than $cust_apy.
3327 # If we were passed cust_bill_pay objs, then:
3328 # $obj->amount represents the amount applied to THIS invoice
3329 # $cust_pay->amount represents the total payment, which may have
3330 # been applied accross several invoices.
3331 # If we were passed cust_bill_pay objects, then the conf flag
3332 # previous_balance-payments_since is NOT set, so we should not
3333 # present any payments not applied to this invoice.
3334 my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3337 _date => $cust_pay->_date,
3338 amount => sprintf("%.2f", $obj->amount),
3339 paynum => $cust_pay->paynum,
3340 payinfo => $cust_pay->payby_payinfo_pretty(),
3341 description => join(' ',
3342 $self->mt('Payment received'),
3343 $self->time2str_local('short', $cust_pay->_date),
3347 if ($c_invoice_payment_details) {
3348 $r_obj{description} = join(' ',
3349 $r_obj{description},
3351 $cust_pay->payby_payinfo_pretty($self->cust_main->locale),
3355 push @return, \%r_obj;
3360 =item _items_total()
3362 Generate the line-items to be shown on the bill in the "Totals" section
3364 Returns a list of hashrefs, each with the keys:
3365 - total_item: description field
3366 - total_amount: dollar-formatted number amount
3368 Information presented by this method varies based on Conf
3370 Conf previous_balance-payments_due
3371 - default, flag not set
3372 Only transactions that were applied to this bill bill be
3373 displayed and calculated intothe total. If items exist in
3374 the past-due section, those items will disappear from this
3375 invoice if they have been paid off.
3377 - previous_balance-payments_due flag is set
3378 Transactions occuring after the timestsamp of this
3379 invoice are not reflected on invoice line items
3381 Only payments/credits applied between the previous invoice
3382 and this one are displayed and calculated into the total
3384 - previous_balance-payments_due && $opt{template} eq 'statement'
3385 Same as above, except payments/credits occuring before the date
3386 of the following invoice are also displayed and calculated into
3389 Conf previous_balance-exclude_from_total
3390 - default, flag not set
3391 The "Totals" section contains a single line item.
3392 The dollar amount of this line items is a sum of old and new charges
3393 - previous_balance-exclude_from_total flag is set
3394 The "Totals" section contains two line items.
3395 One for previous balance, one for new charges
3396 !NOTE: Avent virtualization flag 'disable_previous_balance' can
3397 override the global conf flag previous_balance-exclude_from_total
3399 Conf invoice_show_prior_due_date
3400 - default, flag not set
3401 Total line item in the "Totals" section does not mention due date
3402 - invoice_show_prior_due_date flag is set
3403 Total line item in the "Totals" section includes either the due
3404 date of the invoice, or the specified invoice terms
3405 ? Not sure why this is called "Prior" due date, since we seem to be
3406 displaying THIS due date...
3411 my $conf = $self->conf;
3413 my $c_multi_line_total = 0;
3414 $c_multi_line_total = 1
3415 if $conf->exists('previous_balance-exclude_from_total')
3416 && $self->enable_previous();
3419 my $invoice_charges = $self->charged();
3421 # _items_previous() is aware of conf flags
3422 my $previous_balance = 0;
3423 $previous_balance += $_->{amount} for $self->_items_previous();
3428 if ( $previous_balance && $c_multi_line_total ) {
3429 # previous balance, new charges on separate lines
3432 total_amount => sprintf('%.2f',$previous_balance),
3433 total_item => $self->mt(
3434 $conf->config('previous_balance-text') || 'Previous Balance'
3438 $total_charges = $invoice_charges;
3439 $total_descr = $self->mt(
3440 $conf->config('previous_balance-text-total_new_charges')
3441 || 'Total New Charges'
3445 # previous balance and new charges combined into a single total line
3446 $total_charges = $invoice_charges + $previous_balance;
3447 $total_descr = $self->mt('Total Charges');
3450 if ( $conf->exists('invoice_show_prior_due_date') && !$conf->exists('invoice_omit_due_date') ) {
3451 # then the due date should be shown with Total New Charges,
3452 # and should NOT be shown with the Balance Due message.
3454 if ( $self->due_date ) {
3455 $total_descr .= $self->invoice_pay_by_msg;
3456 } elsif ( $self->terms ) {
3457 $total_descr = join(' ',
3460 $self->mt($self->terms)
3466 total_amount => sprintf('%.2f', $total_charges),
3467 total_item => $total_descr,
3473 =item _items_aging_balances
3475 Returns an array of aged balance amounts from a given epoch timestamp.
3477 The time of day is ignored for this calculation, so that slight differences
3478 on the generation time of an invoice doesn't determine which column an
3479 aged balance falls into.
3481 Will not include any balances dated after the given timestamp in
3482 the calculated totals
3485 @aged_balances = $b->_items_aging_balances( $b->_date )
3496 sub _items_aging_balances {
3497 my ($self, $basetime) = @_;
3498 die "Incorrect usage of _items_aging_balances()" unless ref $self;
3500 $basetime = $self->_date unless $basetime;
3501 my @aging_balances = (0, 0, 0, 0);
3502 my @open_invoices = $self->_items_previous();
3503 my $d30 = 2592000; # 60 * 60 * 24 * 30,
3504 my $d60 = 5184000; # 60 * 60 * 24 * 60,
3505 my $d90 = 7776000; # 60 * 60 * 24 * 90
3507 # Move the clock back on our given day to 12:00:01 AM
3508 my $dt_basetime = DateTime->from_epoch(epoch => $basetime);
3509 my $dt_12am = DateTime->new(
3510 year => $dt_basetime->year,
3511 month => $dt_basetime->month,
3512 day => $dt_basetime->day,
3518 # set our epoch breakpoints
3519 $_ = $dt_12am - $_ for $d30, $d60, $d90;
3521 # grep the aged balances
3522 for my $oinv (@open_invoices) {
3523 if ($oinv->{_date} <= $basetime && $oinv->{_date} > $d30) {
3524 # If post invoice dated less than 30days ago
3525 $aging_balances[0] += $oinv->{amount};
3526 } elsif ($oinv->{_date} <= $d30 && $oinv->{_date} > $d60) {
3527 # If past invoice dated between 30-60 days ago
3528 $aging_balances[1] += $oinv->{amount};
3529 } elsif ($oinv->{_date} <= $d60 && $oinv->{_date} > $d90) {
3530 # If past invoice dated between 60-90 days ago
3531 $aging_balances[2] += $oinv->{amount};
3533 # If past invoice dated 90+ days ago
3534 $aging_balances[3] += $oinv->{amount};
3538 return map{ sprintf('%.2f',$_) } @aging_balances;
3541 =item has_call_details
3543 Returns true if this invoice has call details.
3547 sub has_call_details {
3550 SELECT 1 FROM cust_bill_pkg_detail
3551 LEFT JOIN cust_bill_pkg USING (billpkgnum)
3552 WHERE cust_bill_pkg_detail.format = 'C'
3553 AND cust_bill_pkg.invnum = ?
3558 =item call_details [ OPTION => VALUE ... ]
3560 Returns an array of CSV strings representing the call details for this invoice
3561 The only option available is the boolean prepend_billed_number
3566 my ($self, %opt) = @_;
3568 my $format_function = sub { shift };
3570 if ($opt{prepend_billed_number}) {
3571 $format_function = sub {
3575 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3580 my @details = map { $_->details( 'format_function' => $format_function,
3581 'escape_function' => sub{ return() },
3585 $self->cust_bill_pkg;
3586 my $header = $details[0];
3587 ( $header, grep { $_ ne $header } @details );
3590 =item cust_pay_batch
3592 Returns all L<FS::cust_pay_batch> records linked to this invoice. Deprecated,
3597 sub cust_pay_batch {
3598 carp "FS::cust_bill->cust_pay_batch is deprecated";
3600 qsearch('cust_pay_batch', { 'invnum' => $self->invnum });
3609 =item process_reprint
3613 sub process_reprint {
3614 process_re_X('print', @_);
3617 =item process_reemail
3621 sub process_reemail {
3622 process_re_X('email', @_);
3630 process_re_X('fax', @_);
3638 process_re_X('ftp', @_);
3645 sub process_respool {
3646 process_re_X('spool', @_);
3651 my( $method, $job ) = ( shift, shift );
3652 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3655 warn Dumper($param) if $DEBUG;
3665 # this is called from search/cust_bill.html and given all its search
3666 # parameters, so it needs to perform the same search.
3669 # spool_invoice ftp_invoice fax_invoice print_invoice
3670 my($method, $job, %param ) = @_;
3672 warn "re_X $method for job $job with param:\n".
3673 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3676 #some false laziness w/search/cust_bill.html
3677 $param{'order_by'} = 'cust_bill._date';
3679 my $query = FS::cust_bill->search(\%param);
3680 delete $query->{'count_query'};
3681 delete $query->{'count_addl'};
3683 $query->{debug} = 1; # was in here before, is obviously useful
3685 my @cust_bill = qsearch( $query );
3687 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3689 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3692 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3693 foreach my $cust_bill ( @cust_bill ) {
3694 $cust_bill->$method();
3696 if ( $job ) { #progressbar foo
3698 if ( time - $min_sec > $last ) {
3699 my $error = $job->update_statustext(
3700 int( 100 * $num / scalar(@cust_bill) )
3702 die $error if $error;
3713 +{ ( map { $_=>$self->$_ } $self->fields ),
3714 'owed' => $self->owed,
3715 #XXX last payment applied date
3721 =head1 CLASS METHODS
3727 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3732 my ($class, $start, $end) = @_;
3734 $class->paid_sql($start, $end). ' - '.
3735 $class->credited_sql($start, $end);
3740 Returns an SQL fragment to retreive the net amount (charged minus credited).
3745 my ($class, $start, $end) = @_;
3746 'charged - '. $class->credited_sql($start, $end);
3751 Returns an SQL fragment to retreive the amount paid against this invoice.
3756 my ($class, $start, $end) = @_;
3757 $start &&= "AND cust_bill_pay._date <= $start";
3758 $end &&= "AND cust_bill_pay._date > $end";
3759 $start = '' unless defined($start);
3760 $end = '' unless defined($end);
3761 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3762 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3767 Returns an SQL fragment to retreive the amount credited against this invoice.
3772 my ($class, $start, $end) = @_;
3773 $start &&= "AND cust_credit_bill._date <= $start";
3774 $end &&= "AND cust_credit_bill._date > $end";
3775 $start = '' unless defined($start);
3776 $end = '' unless defined($end);
3777 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3778 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3783 Returns an SQL fragment to retrieve the due date of an invoice.
3784 Currently only supported on PostgreSQL.
3789 die "don't use: doesn't account for agent-specific invoice_default_terms";
3791 #we're passed a $conf but not a specific customer (that's in the query), so
3792 # to make this work we'd need an agentnum-aware "condition_sql_conf" like
3793 # "condition_sql_option" that retreives a conf value with SQL in an agent-
3796 my $conf = new FS::Conf;
3800 cust_bill.invoice_terms,
3801 cust_main.invoice_terms,
3802 \''.($conf->config('invoice_default_terms') || '').'\'
3803 ), E\'Net (\\\\d+)\'
3805 ) * 86400 + cust_bill._date'
3816 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3817 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base