2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $DEBUG $me $date_format );
7 use Fcntl qw(:flock); #for spool_csv
9 use List::Util qw(min max sum);
13 use Storable qw( freeze thaw );
15 use FS::UID qw( datasrc );
16 use FS::Misc qw( send_email send_fax do_print );
17 use FS::Record qw( qsearch qsearchs dbh );
19 use FS::cust_statement;
20 use FS::cust_bill_pkg;
21 use FS::cust_bill_pkg_display;
22 use FS::cust_bill_pkg_detail;
26 use FS::cust_credit_bill;
28 use FS::cust_pay_batch;
29 use FS::cust_bill_event;
32 use FS::cust_bill_pay;
33 use FS::cust_bill_pay_batch;
34 use FS::part_bill_event;
37 use FS::cust_bill_batch;
38 use FS::cust_bill_pay_pkg;
39 use FS::cust_credit_bill_pkg;
40 use FS::discount_plan;
41 use FS::cust_bill_void;
45 $me = '[FS::cust_bill]';
47 #ask FS::UID to run this stuff for us later
48 FS::UID->install_callback( sub {
49 my $conf = new FS::Conf; #global
50 $date_format = $conf->config('date_format') || '%x'; #/YY
55 FS::cust_bill - Object methods for cust_bill records
61 $record = new FS::cust_bill \%hash;
62 $record = new FS::cust_bill { 'column' => 'value' };
64 $error = $record->insert;
66 $error = $new_record->replace($old_record);
68 $error = $record->delete;
70 $error = $record->check;
72 ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
74 @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
76 ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
78 @cust_pay_objects = $cust_bill->cust_pay;
80 $tax_amount = $record->tax;
82 @lines = $cust_bill->print_text;
83 @lines = $cust_bill->print_text $time;
87 An FS::cust_bill object represents an invoice; a declaration that a customer
88 owes you money. The specific charges are itemized as B<cust_bill_pkg> records
89 (see L<FS::cust_bill_pkg>). FS::cust_bill inherits from FS::Record. The
90 following fields are currently supported:
96 =item invnum - primary key (assigned automatically for new invoices)
98 =item custnum - customer (see L<FS::cust_main>)
100 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
101 L<Time::Local> and L<Date::Parse> for conversion functions.
103 =item charged - amount of this invoice
105 =item invoice_terms - optional terms override for this specific invoice
109 Customer info at invoice generation time
113 =item previous_balance
115 =item billing_balance
123 =item printed - deprecated
131 =item closed - books closed flag, empty or `Y'
133 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
135 =item agent_invid - legacy invoice number
137 =item promised_date - customer promised payment date, for collection
147 Creates a new invoice. To add the invoice to the database, see L<"insert">.
148 Invoices are normally created by calling the bill method of a customer object
149 (see L<FS::cust_main>).
153 sub table { 'cust_bill'; }
154 sub notice_name { 'Invoice'; }
156 sub cust_linked { $_[0]->cust_main_custnum; }
157 sub cust_unlinked_msg {
159 "WARNING: can't find cust_main.custnum ". $self->custnum.
160 ' (cust_bill.invnum '. $self->invnum. ')';
165 Adds this invoice to the database ("Posts" the invoice). If there is an error,
166 returns the error, otherwise returns false.
172 warn "$me insert called\n" if $DEBUG;
174 local $SIG{HUP} = 'IGNORE';
175 local $SIG{INT} = 'IGNORE';
176 local $SIG{QUIT} = 'IGNORE';
177 local $SIG{TERM} = 'IGNORE';
178 local $SIG{TSTP} = 'IGNORE';
179 local $SIG{PIPE} = 'IGNORE';
181 my $oldAutoCommit = $FS::UID::AutoCommit;
182 local $FS::UID::AutoCommit = 0;
185 my $error = $self->SUPER::insert;
187 $dbh->rollback if $oldAutoCommit;
191 if ( $self->get('cust_bill_pkg') ) {
192 foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
193 $cust_bill_pkg->invnum($self->invnum);
194 my $error = $cust_bill_pkg->insert;
196 $dbh->rollback if $oldAutoCommit;
197 return "can't create invoice line item: $error";
202 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
209 Voids this invoice: deletes the invoice and adds a record of the voided invoice
210 to the FS::cust_bill_void table (and related tables starting from
211 FS::cust_bill_pkg_void).
217 my $reason = scalar(@_) ? shift : '';
219 local $SIG{HUP} = 'IGNORE';
220 local $SIG{INT} = 'IGNORE';
221 local $SIG{QUIT} = 'IGNORE';
222 local $SIG{TERM} = 'IGNORE';
223 local $SIG{TSTP} = 'IGNORE';
224 local $SIG{PIPE} = 'IGNORE';
226 my $oldAutoCommit = $FS::UID::AutoCommit;
227 local $FS::UID::AutoCommit = 0;
230 my $cust_bill_void = new FS::cust_bill_void ( {
231 map { $_ => $self->get($_) } $self->fields
233 $cust_bill_void->reason($reason);
234 my $error = $cust_bill_void->insert;
236 $dbh->rollback if $oldAutoCommit;
240 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
241 my $error = $cust_bill_pkg->void($reason);
243 $dbh->rollback if $oldAutoCommit;
248 $error = $self->delete;
250 $dbh->rollback if $oldAutoCommit;
254 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
262 This method now works but you probably shouldn't use it. Instead, apply a
263 credit against the invoice, or use the new void method.
265 Using this method to delete invoices outright is really, really bad. There
266 would be no record you ever posted this invoice, and there are no check to
267 make sure charged = 0 or that there are no associated cust_bill_pkg records.
269 Really, don't use it.
275 return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
277 local $SIG{HUP} = 'IGNORE';
278 local $SIG{INT} = 'IGNORE';
279 local $SIG{QUIT} = 'IGNORE';
280 local $SIG{TERM} = 'IGNORE';
281 local $SIG{TSTP} = 'IGNORE';
282 local $SIG{PIPE} = 'IGNORE';
284 my $oldAutoCommit = $FS::UID::AutoCommit;
285 local $FS::UID::AutoCommit = 0;
288 foreach my $table (qw(
299 foreach my $linked ( $self->$table() ) {
300 my $error = $linked->delete;
302 $dbh->rollback if $oldAutoCommit;
309 my $error = $self->SUPER::delete(@_);
311 $dbh->rollback if $oldAutoCommit;
315 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
321 =item replace [ OLD_RECORD ]
323 You can, but probably shouldn't modify invoices...
325 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
326 supplied, replaces this record. If there is an error, returns the error,
327 otherwise returns false.
331 #replace can be inherited from Record.pm
333 # replace_check is now the preferred way to #implement replace data checks
334 # (so $object->replace() works without an argument)
337 my( $new, $old ) = ( shift, shift );
338 return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
339 #return "Can't change _date!" unless $old->_date eq $new->_date;
340 return "Can't change _date" unless $old->_date == $new->_date;
341 return "Can't change charged" unless $old->charged == $new->charged
342 || $old->charged == 0
343 || $new->{'Hash'}{'cc_surcharge_replace_hack'};
349 =item add_cc_surcharge
355 sub add_cc_surcharge {
356 my ($self, $pkgnum, $amount) = (shift, shift, shift);
359 my $cust_bill_pkg = new FS::cust_bill_pkg({
360 'invnum' => $self->invnum,
364 $error = $cust_bill_pkg->insert;
365 return $error if $error;
367 $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
368 $self->charged($self->charged+$amount);
369 $error = $self->replace;
370 return $error if $error;
372 $self->apply_payments_and_credits;
378 Checks all fields to make sure this is a valid invoice. If there is an error,
379 returns the error, otherwise returns false. Called by the insert and replace
388 $self->ut_numbern('invnum')
389 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
390 || $self->ut_numbern('_date')
391 || $self->ut_money('charged')
392 || $self->ut_numbern('printed')
393 || $self->ut_enum('closed', [ '', 'Y' ])
394 || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
395 || $self->ut_numbern('agent_invid') #varchar?
397 return $error if $error;
399 $self->_date(time) unless $self->_date;
401 $self->printed(0) if $self->printed eq '';
408 Returns the displayed invoice number for this invoice: agent_invid if
409 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
415 my $conf = $self->conf;
416 if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
417 return $self->agent_invid;
419 return $self->invnum;
425 Returns a list consisting of the total previous balance for this customer,
426 followed by the previous outstanding invoices (as FS::cust_bill objects also).
433 my @cust_bill = sort { $a->_date <=> $b->_date }
434 grep { $_->owed != 0 }
435 qsearch( 'cust_bill', { 'custnum' => $self->custnum,
436 #'_date' => { op=>'<', value=>$self->_date },
437 'invnum' => { op=>'<', value=>$self->invnum },
440 foreach ( @cust_bill ) { $total += $_->owed; }
444 =item enable_previous
446 Whether to show the 'Previous Charges' section when printing this invoice.
447 The negation of the 'disable_previous_balance' config setting.
451 sub enable_previous {
453 my $agentnum = $self->cust_main->agentnum;
454 !$self->conf->exists('disable_previous_balance', $agentnum);
459 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
466 { 'table' => 'cust_bill_pkg',
467 'hashref' => { 'invnum' => $self->invnum },
468 'order_by' => 'ORDER BY billpkgnum',
473 =item cust_bill_pkg_pkgnum PKGNUM
475 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
480 sub cust_bill_pkg_pkgnum {
481 my( $self, $pkgnum ) = @_;
483 { 'table' => 'cust_bill_pkg',
484 'hashref' => { 'invnum' => $self->invnum,
487 'order_by' => 'ORDER BY billpkgnum',
494 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
501 my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
502 $self->cust_bill_pkg;
504 grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
509 Returns true if any of the packages (or their definitions) corresponding to the
510 line items for this invoice have the no_auto flag set.
516 grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
519 =item open_cust_bill_pkg
521 Returns the open line items for this invoice.
523 Note that cust_bill_pkg with both setup and recur fees are returned as two
524 separate line items, each with only one fee.
528 # modeled after cust_main::open_cust_bill
529 sub open_cust_bill_pkg {
532 # grep { $_->owed > 0 } $self->cust_bill_pkg
534 my %other = ( 'recur' => 'setup',
535 'setup' => 'recur', );
537 foreach my $field ( qw( recur setup )) {
538 push @open, map { $_->set( $other{$field}, 0 ); $_; }
539 grep { $_->owed($field) > 0 }
540 $self->cust_bill_pkg;
546 =item cust_bill_event
548 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
552 sub cust_bill_event {
554 qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
557 =item num_cust_bill_event
559 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
563 sub num_cust_bill_event {
566 "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
567 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
568 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
569 $sth->fetchrow_arrayref->[0];
574 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
578 #false laziness w/cust_pkg.pm
582 'table' => 'cust_event',
583 'addl_from' => 'JOIN part_event USING ( eventpart )',
584 'hashref' => { 'tablenum' => $self->invnum },
585 'extra_sql' => " AND eventtable = 'cust_bill' ",
591 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
595 #false laziness w/cust_pkg.pm
599 "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
600 " WHERE tablenum = ? AND eventtable = 'cust_bill'";
601 my $sth = dbh->prepare($sql) or die dbh->errstr. " preparing $sql";
602 $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
603 $sth->fetchrow_arrayref->[0];
608 Returns the customer (see L<FS::cust_main>) for this invoice.
614 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
617 =item cust_suspend_if_balance_over AMOUNT
619 Suspends the customer associated with this invoice if the total amount owed on
620 this invoice and all older invoices is greater than the specified amount.
622 Returns a list: an empty list on success or a list of errors.
626 sub cust_suspend_if_balance_over {
627 my( $self, $amount ) = ( shift, shift );
628 my $cust_main = $self->cust_main;
629 if ( $cust_main->total_owed_date($self->_date) < $amount ) {
632 $cust_main->suspend(@_);
638 Depreciated. See the cust_credited method.
640 #Returns a list consisting of the total previous credited (see
641 #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
642 #outstanding credits (FS::cust_credit objects).
648 croak "FS::cust_bill->cust_credit depreciated; see ".
649 "FS::cust_bill->cust_credit_bill";
652 #my @cust_credit = sort { $a->_date <=> $b->_date }
653 # grep { $_->credited != 0 && $_->_date < $self->_date }
654 # qsearch('cust_credit', { 'custnum' => $self->custnum } )
656 #foreach (@cust_credit) { $total += $_->credited; }
657 #$total, @cust_credit;
662 Depreciated. See the cust_bill_pay method.
664 #Returns all payments (see L<FS::cust_pay>) for this invoice.
670 croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
672 #sort { $a->_date <=> $b->_date }
673 # qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
679 qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
682 sub cust_bill_pay_batch {
684 qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
689 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
695 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
696 sort { $a->_date <=> $b->_date }
697 qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
702 =item cust_credit_bill
704 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
710 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
711 sort { $a->_date <=> $b->_date }
712 qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
716 sub cust_credit_bill {
717 shift->cust_credited(@_);
720 #=item cust_bill_pay_pkgnum PKGNUM
722 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
723 #with matching pkgnum.
727 #sub cust_bill_pay_pkgnum {
728 # my( $self, $pkgnum ) = @_;
729 # map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
730 # sort { $a->_date <=> $b->_date }
731 # qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
732 # 'pkgnum' => $pkgnum,
737 =item cust_bill_pay_pkg PKGNUM
739 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
740 applied against the matching pkgnum.
744 sub cust_bill_pay_pkg {
745 my( $self, $pkgnum ) = @_;
748 'select' => 'cust_bill_pay_pkg.*',
749 'table' => 'cust_bill_pay_pkg',
750 'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
751 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
752 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
753 " AND cust_bill_pkg.pkgnum = $pkgnum",
758 #=item cust_credited_pkgnum PKGNUM
760 #=item cust_credit_bill_pkgnum PKGNUM
762 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
763 #with matching pkgnum.
767 #sub cust_credited_pkgnum {
768 # my( $self, $pkgnum ) = @_;
769 # map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
770 # sort { $a->_date <=> $b->_date }
771 # qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
772 # 'pkgnum' => $pkgnum,
777 #sub cust_credit_bill_pkgnum {
778 # shift->cust_credited_pkgnum(@_);
781 =item cust_credit_bill_pkg PKGNUM
783 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
784 applied against the matching pkgnum.
788 sub cust_credit_bill_pkg {
789 my( $self, $pkgnum ) = @_;
792 'select' => 'cust_credit_bill_pkg.*',
793 'table' => 'cust_credit_bill_pkg',
794 'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
795 ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
796 'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
797 " AND cust_bill_pkg.pkgnum = $pkgnum",
802 =item cust_bill_batch
804 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
808 sub cust_bill_batch {
810 qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
815 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a
816 hash keyed by term length.
822 FS::discount_plan->all($self);
827 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
834 my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
836 foreach (@taxlines) { $total += $_->setup; }
842 Returns the amount owed (still outstanding) on this invoice, which is charged
843 minus all payment applications (see L<FS::cust_bill_pay>) and credit
844 applications (see L<FS::cust_credit_bill>).
850 my $balance = $self->charged;
851 $balance -= $_->amount foreach ( $self->cust_bill_pay );
852 $balance -= $_->amount foreach ( $self->cust_credited );
853 $balance = sprintf( "%.2f", $balance);
854 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
859 my( $self, $pkgnum ) = @_;
861 #my $balance = $self->charged;
863 $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
865 $balance -= $_->amount for $self->cust_bill_pay_pkg($pkgnum);
866 $balance -= $_->amount for $self->cust_credit_bill_pkg($pkgnum);
868 $balance = sprintf( "%.2f", $balance);
869 $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
875 Returns true if this invoice should be hidden. See the
876 selfservice-hide_invoices-taxclass configuraiton setting.
882 my $conf = $self->conf;
883 my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
885 my @cust_bill_pkg = $self->cust_bill_pkg;
886 my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
887 ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
890 =item apply_payments_and_credits [ OPTION => VALUE ... ]
892 Applies unapplied payments and credits to this invoice.
894 A hash of optional arguments may be passed. Currently "manual" is supported.
895 If true, a payment receipt is sent instead of a statement when
896 'payment_receipt_email' configuration option is set.
898 If there is an error, returns the error, otherwise returns false.
902 sub apply_payments_and_credits {
903 my( $self, %options ) = @_;
904 my $conf = $self->conf;
906 local $SIG{HUP} = 'IGNORE';
907 local $SIG{INT} = 'IGNORE';
908 local $SIG{QUIT} = 'IGNORE';
909 local $SIG{TERM} = 'IGNORE';
910 local $SIG{TSTP} = 'IGNORE';
911 local $SIG{PIPE} = 'IGNORE';
913 my $oldAutoCommit = $FS::UID::AutoCommit;
914 local $FS::UID::AutoCommit = 0;
917 $self->select_for_update; #mutex
919 my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
920 my @credits = grep { $_->credited > 0 } $self->cust_main->cust_credit;
922 if ( $conf->exists('pkg-balances') ) {
923 # limit @payments & @credits to those w/ a pkgnum grepped from $self
924 my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
925 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
926 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
929 while ( $self->owed > 0 and ( @payments || @credits ) ) {
932 if ( @payments && @credits ) {
934 #decide which goes first by weight of top (unapplied) line item
936 my @open_lineitems = $self->open_cust_bill_pkg;
939 max( map { $_->part_pkg->pay_weight || 0 }
944 my $max_credit_weight =
945 max( map { $_->part_pkg->credit_weight || 0 }
951 #if both are the same... payments first? it has to be something
952 if ( $max_pay_weight >= $max_credit_weight ) {
958 } elsif ( @payments ) {
960 } elsif ( @credits ) {
963 die "guru meditation #12 and 35";
967 if ( $app eq 'pay' ) {
969 my $payment = shift @payments;
970 $unapp_amount = $payment->unapplied;
971 $app = new FS::cust_bill_pay { 'paynum' => $payment->paynum };
972 $app->pkgnum( $payment->pkgnum )
973 if $conf->exists('pkg-balances') && $payment->pkgnum;
975 } elsif ( $app eq 'credit' ) {
977 my $credit = shift @credits;
978 $unapp_amount = $credit->credited;
979 $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
980 $app->pkgnum( $credit->pkgnum )
981 if $conf->exists('pkg-balances') && $credit->pkgnum;
984 die "guru meditation #12 and 35";
988 if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
989 warn "owed_pkgnum ". $app->pkgnum;
990 $owed = $self->owed_pkgnum($app->pkgnum);
994 next unless $owed > 0;
996 warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
997 $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
999 $app->invnum( $self->invnum );
1001 my $error = $app->insert(%options);
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Error inserting ". $app->table. " record: $error";
1006 die $error if $error;
1010 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1015 =item generate_email OPTION => VALUE ...
1023 sender address, required
1027 alternate template name, optional
1031 text attachment arrayref, optional
1035 email subject, optional
1039 notice name instead of "Invoice", optional
1043 Returns an argument list to be passed to L<FS::Misc::send_email>.
1049 sub generate_email {
1053 my $conf = $self->conf;
1055 my $me = '[FS::cust_bill::generate_email]';
1058 'from' => $args{'from'},
1059 'subject' => (($args{'subject'}) ? $args{'subject'} : 'Invoice'),
1063 'unsquelch_cdr' => $conf->exists('voip-cdr_email'),
1064 'template' => $args{'template'},
1065 'notice_name' => ( $args{'notice_name'} || 'Invoice' ),
1066 'no_coupon' => $args{'no_coupon'},
1069 my $cust_main = $self->cust_main;
1071 if (ref($args{'to'}) eq 'ARRAY') {
1072 $return{'to'} = $args{'to'};
1074 $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1075 $cust_main->invoicing_list
1079 if ( $conf->exists('invoice_html') ) {
1081 warn "$me creating HTML/text multipart message"
1084 $return{'nobody'} = 1;
1086 my $alternative = build MIME::Entity
1087 'Type' => 'multipart/alternative',
1088 #'Encoding' => '7bit',
1089 'Disposition' => 'inline'
1093 if ( $conf->exists('invoice_email_pdf')
1094 and scalar($conf->config('invoice_email_pdf_note')) ) {
1096 warn "$me using 'invoice_email_pdf_note' in multipart message"
1098 $data = [ map { $_ . "\n" }
1099 $conf->config('invoice_email_pdf_note')
1104 warn "$me not using 'invoice_email_pdf_note' in multipart message"
1106 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1107 $data = $args{'print_text'};
1109 $data = [ $self->print_text(\%opt) ];
1114 $alternative->attach(
1115 'Type' => 'text/plain',
1116 'Encoding' => 'quoted-printable',
1117 #'Encoding' => '7bit',
1119 'Disposition' => 'inline',
1126 if ( $conf->exists('invoice_email_pdf')
1127 and scalar($conf->config('invoice_email_pdf_note')) ) {
1129 $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1133 $args{'from'} =~ /\@([\w\.\-]+)/;
1134 my $from = $1 || 'example.com';
1135 my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1138 my $agentnum = $cust_main->agentnum;
1139 if ( defined($args{'template'}) && length($args{'template'})
1140 && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1143 $logo = 'logo_'. $args{'template'}. '.png';
1147 my $image_data = $conf->config_binary( $logo, $agentnum);
1149 $image = build MIME::Entity
1150 'Type' => 'image/png',
1151 'Encoding' => 'base64',
1152 'Data' => $image_data,
1153 'Filename' => 'logo.png',
1154 'Content-ID' => "<$content_id>",
1157 if ($conf->exists('invoice-barcode')) {
1158 my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1159 $barcode = build MIME::Entity
1160 'Type' => 'image/png',
1161 'Encoding' => 'base64',
1162 'Data' => $self->invoice_barcode(0),
1163 'Filename' => 'barcode.png',
1164 'Content-ID' => "<$barcode_content_id>",
1166 $opt{'barcode_cid'} = $barcode_content_id;
1169 $htmldata = $self->print_html({ 'cid'=>$content_id, %opt });
1172 $alternative->attach(
1173 'Type' => 'text/html',
1174 'Encoding' => 'quoted-printable',
1175 'Data' => [ '<html>',
1178 ' '. encode_entities($return{'subject'}),
1181 ' <body bgcolor="#e8e8e8">',
1186 'Disposition' => 'inline',
1187 #'Filename' => 'invoice.pdf',
1191 my @otherparts = ();
1192 if ( $cust_main->email_csv_cdr ) {
1194 push @otherparts, build MIME::Entity
1195 'Type' => 'text/csv',
1196 'Encoding' => '7bit',
1197 'Data' => [ map { "$_\n" }
1198 $self->call_details('prepend_billed_number' => 1)
1200 'Disposition' => 'attachment',
1201 'Filename' => 'usage-'. $self->invnum. '.csv',
1206 if ( $conf->exists('invoice_email_pdf') ) {
1211 # multipart/alternative
1217 my $related = build MIME::Entity 'Type' => 'multipart/related',
1218 'Encoding' => '7bit';
1220 #false laziness w/Misc::send_email
1221 $related->head->replace('Content-type',
1222 $related->mime_type.
1223 '; boundary="'. $related->head->multipart_boundary. '"'.
1224 '; type=multipart/alternative'
1227 $related->add_part($alternative);
1229 $related->add_part($image) if $image;
1231 my $pdf = build MIME::Entity $self->mimebuild_pdf(\%opt);
1233 $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1237 #no other attachment:
1239 # multipart/alternative
1244 $return{'content-type'} = 'multipart/related';
1245 if ($conf->exists('invoice-barcode') && $barcode) {
1246 $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1248 $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1250 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1251 #$return{'disposition'} = 'inline';
1257 if ( $conf->exists('invoice_email_pdf') ) {
1258 warn "$me creating PDF attachment"
1261 #mime parts arguments a la MIME::Entity->build().
1262 $return{'mimeparts'} = [
1263 { $self->mimebuild_pdf(\%opt) }
1267 if ( $conf->exists('invoice_email_pdf')
1268 and scalar($conf->config('invoice_email_pdf_note')) ) {
1270 warn "$me using 'invoice_email_pdf_note'"
1272 $return{'body'} = [ map { $_ . "\n" }
1273 $conf->config('invoice_email_pdf_note')
1278 warn "$me not using 'invoice_email_pdf_note'"
1280 if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1281 $return{'body'} = $args{'print_text'};
1283 $return{'body'} = [ $self->print_text(\%opt) ];
1296 Returns a list suitable for passing to MIME::Entity->build(), representing
1297 this invoice as PDF attachment.
1304 'Type' => 'application/pdf',
1305 'Encoding' => 'base64',
1306 'Data' => [ $self->print_pdf(@_) ],
1307 'Disposition' => 'attachment',
1308 'Filename' => 'invoice-'. $self->invnum. '.pdf',
1312 =item send HASHREF | [ TEMPLATE [ , AGENTNUM [ , INVOICE_FROM [ , AMOUNT ] ] ] ]
1314 Sends this invoice to the destinations configured for this customer: sends
1315 email, prints and/or faxes. See L<FS::cust_main_invoice>.
1317 Options can be passed as a hashref (recommended) or as a list of up to
1318 four values for templatename, agentnum, invoice_from and amount.
1320 I<template>, if specified, is the name of a suffix for alternate invoices.
1322 I<agentnum>, if specified, means that this invoice will only be sent for customers
1323 of the specified agent or agent(s). AGENTNUM can be a scalar agentnum (for a
1324 single agent) or an arrayref of agentnums.
1326 I<invoice_from>, if specified, overrides the default email invoice From: address.
1328 I<amount>, if specified, only sends the invoice if the total amount owed on this
1329 invoice and all older invoices is greater than the specified amount.
1331 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1333 I<lpr>, if specified, is passed to
1337 sub queueable_send {
1340 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1341 or die "invalid invoice number: " . $opt{invnum};
1343 my @args = ( $opt{template}, $opt{agentnum} );
1344 push @args, $opt{invoice_from}
1345 if exists($opt{invoice_from}) && $opt{invoice_from};
1347 my $error = $self->send( @args );
1348 die $error if $error;
1354 my $conf = $self->conf;
1356 my( $template, $invoice_from, $notice_name );
1358 my $balance_over = 0;
1363 $template = $opt->{'template'} || '';
1364 if ( $agentnums = $opt->{'agentnum'} ) {
1365 $agentnums = [ $agentnums ] unless ref($agentnums);
1367 $invoice_from = $opt->{'invoice_from'};
1368 $balance_over = $opt->{'balance_over'} if $opt->{'balance_over'};
1369 $notice_name = $opt->{'notice_name'};
1370 $lpr = $opt->{'lpr'}
1372 $template = scalar(@_) ? shift : '';
1373 if ( scalar(@_) && $_[0] ) {
1374 $agentnums = ref($_[0]) ? shift : [ shift ];
1376 $invoice_from = shift if scalar(@_);
1377 $balance_over = shift if scalar(@_) && $_[0] !~ /^\s*$/;
1380 my $cust_main = $self->cust_main;
1382 return 'N/A' unless ! $agentnums
1383 or grep { $_ == $cust_main->agentnum } @$agentnums;
1386 unless $cust_main->total_owed_date($self->_date) > $balance_over;
1388 $invoice_from ||= $self->_agent_invoice_from || #XXX should go away
1389 $conf->config('invoice_from', $cust_main->agentnum );
1392 'template' => $template,
1393 'invoice_from' => $invoice_from,
1394 'notice_name' => ( $notice_name || 'Invoice' ),
1397 my @invoicing_list = $cust_main->invoicing_list;
1399 #$self->email_invoice(\%opt)
1401 if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1402 && ! $self->invoice_noemail;
1405 #$self->print_invoice(\%opt)
1407 if grep { $_ eq 'POST' } @invoicing_list; #postal
1409 #this has never been used post-$ORIGINAL_ISP afaik
1410 $self->fax_invoice(\%opt)
1411 if grep { $_ eq 'FAX' } @invoicing_list; #fax
1417 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ]
1419 Emails this invoice.
1421 Options can be passed as a hashref (recommended) or as a list of up to
1422 two values for templatename and invoice_from.
1424 I<template>, if specified, is the name of a suffix for alternate invoices.
1426 I<invoice_from>, if specified, overrides the default email invoice From: address.
1428 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1432 sub queueable_email {
1435 my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1436 or die "invalid invoice number: " . $opt{invnum};
1438 my %args = ( 'template' => $opt{template} );
1439 $args{$_} = $opt{$_}
1440 foreach grep { exists($opt{$_}) && $opt{$_} }
1441 qw( invoice_from notice_name no_coupon );
1443 my $error = $self->email( \%args );
1444 die $error if $error;
1448 #sub email_invoice {
1451 return if $self->hide;
1452 my $conf = $self->conf;
1454 my( $template, $invoice_from, $notice_name, $no_coupon );
1457 $template = $opt->{'template'} || '';
1458 $invoice_from = $opt->{'invoice_from'};
1459 $notice_name = $opt->{'notice_name'} || 'Invoice';
1460 $no_coupon = $opt->{'no_coupon'} || 0;
1462 $template = scalar(@_) ? shift : '';
1463 $invoice_from = shift if scalar(@_);
1464 $notice_name = 'Invoice';
1468 $invoice_from ||= $self->_agent_invoice_from || #XXX should go away
1469 $conf->config('invoice_from', $self->cust_main->agentnum );
1471 my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ }
1472 $self->cust_main->invoicing_list;
1474 if ( ! @invoicing_list ) { #no recipients
1475 if ( $conf->exists('cust_bill-no_recipients-error') ) {
1476 die 'No recipients for customer #'. $self->custnum;
1478 #default: better to notify this person than silence
1479 @invoicing_list = ($invoice_from);
1483 my $subject = $self->email_subject($template);
1485 my $error = send_email(
1486 $self->generate_email(
1487 'from' => $invoice_from,
1488 'to' => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1489 'subject' => $subject,
1490 'template' => $template,
1491 'notice_name' => $notice_name,
1492 'no_coupon' => $no_coupon,
1495 die "can't email invoice: $error\n" if $error;
1496 #die "$error\n" if $error;
1502 my $conf = $self->conf;
1504 #my $template = scalar(@_) ? shift : '';
1507 my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1510 my $cust_main = $self->cust_main;
1511 my $name = $cust_main->name;
1512 my $name_short = $cust_main->name_short;
1513 my $invoice_number = $self->invnum;
1514 my $invoice_date = $self->_date_pretty;
1516 eval qq("$subject");
1519 =item lpr_data HASHREF | [ TEMPLATE ]
1521 Returns the postscript or plaintext for this invoice as an arrayref.
1523 Options can be passed as a hashref (recommended) or as a single optional value
1526 I<template>, if specified, is the name of a suffix for alternate invoices.
1528 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1534 my $conf = $self->conf;
1535 my( $template, $notice_name );
1538 $template = $opt->{'template'} || '';
1539 $notice_name = $opt->{'notice_name'} || 'Invoice';
1541 $template = scalar(@_) ? shift : '';
1542 $notice_name = 'Invoice';
1546 'template' => $template,
1547 'notice_name' => $notice_name,
1550 my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1551 [ $self->$method( \%opt ) ];
1554 =item print HASHREF | [ TEMPLATE ]
1556 Prints this invoice.
1558 Options can be passed as a hashref (recommended) or as a single optional
1561 I<template>, if specified, is the name of a suffix for alternate invoices.
1563 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1567 #sub print_invoice {
1570 return if $self->hide;
1571 my $conf = $self->conf;
1573 my( $template, $notice_name, $lpr );
1576 $template = $opt->{'template'} || '';
1577 $notice_name = $opt->{'notice_name'} || 'Invoice';
1578 $lpr = $opt->{'lpr'}
1580 $template = scalar(@_) ? shift : '';
1581 $notice_name = 'Invoice';
1586 'template' => $template,
1587 'notice_name' => $notice_name,
1590 if($conf->exists('invoice_print_pdf')) {
1591 # Add the invoice to the current batch.
1592 $self->batch_invoice(\%opt);
1596 $self->lpr_data(\%opt),
1597 'agentnum' => $self->cust_main->agentnum,
1603 =item fax_invoice HASHREF | [ TEMPLATE ]
1607 Options can be passed as a hashref (recommended) or as a single optional
1610 I<template>, if specified, is the name of a suffix for alternate invoices.
1612 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1618 return if $self->hide;
1619 my $conf = $self->conf;
1621 my( $template, $notice_name );
1624 $template = $opt->{'template'} || '';
1625 $notice_name = $opt->{'notice_name'} || 'Invoice';
1627 $template = scalar(@_) ? shift : '';
1628 $notice_name = 'Invoice';
1631 die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1632 unless $conf->exists('invoice_latex');
1634 my $dialstring = $self->cust_main->getfield('fax');
1638 'template' => $template,
1639 'notice_name' => $notice_name,
1642 my $error = send_fax( 'docdata' => $self->lpr_data(\%opt),
1643 'dialstring' => $dialstring,
1645 die $error if $error;
1649 =item batch_invoice [ HASHREF ]
1651 Place this invoice into the open batch (see C<FS::bill_batch>). If there
1652 isn't an open batch, one will be created.
1657 my ($self, $opt) = @_;
1658 my $bill_batch = $self->get_open_bill_batch;
1659 my $cust_bill_batch = FS::cust_bill_batch->new({
1660 batchnum => $bill_batch->batchnum,
1661 invnum => $self->invnum,
1663 return $cust_bill_batch->insert($opt);
1666 =item get_open_batch
1668 Returns the currently open batch as an FS::bill_batch object, creating a new
1669 one if necessary. (A per-agent batch if invoice_print_pdf-spoolagent is
1674 sub get_open_bill_batch {
1676 my $conf = $self->conf;
1677 my $hashref = { status => 'O' };
1678 $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1679 ? $self->cust_main->agentnum
1681 my $batch = qsearchs('bill_batch', $hashref);
1682 return $batch if $batch;
1683 $batch = FS::bill_batch->new($hashref);
1684 my $error = $batch->insert;
1685 die $error if $error;
1689 =item ftp_invoice [ TEMPLATENAME ]
1691 Sends this invoice data via FTP.
1693 TEMPLATENAME is unused?
1699 my $conf = $self->conf;
1700 my $template = scalar(@_) ? shift : '';
1703 'protocol' => 'ftp',
1704 'server' => $conf->config('cust_bill-ftpserver'),
1705 'username' => $conf->config('cust_bill-ftpusername'),
1706 'password' => $conf->config('cust_bill-ftppassword'),
1707 'dir' => $conf->config('cust_bill-ftpdir'),
1708 'format' => $conf->config('cust_bill-ftpformat'),
1712 =item spool_invoice [ TEMPLATENAME ]
1714 Spools this invoice data (see L<FS::spool_csv>)
1716 TEMPLATENAME is unused?
1722 my $conf = $self->conf;
1723 my $template = scalar(@_) ? shift : '';
1726 'format' => $conf->config('cust_bill-spoolformat'),
1727 'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1731 =item send_if_newest [ TEMPLATENAME [ , AGENTNUM [ , INVOICE_FROM ] ] ]
1733 Like B<send>, but only sends the invoice if it is the newest open invoice for
1738 sub send_if_newest {
1743 grep { $_->owed > 0 }
1744 qsearch('cust_bill', {
1745 'custnum' => $self->custnum,
1746 #'_date' => { op=>'>', value=>$self->_date },
1747 'invnum' => { op=>'>', value=>$self->invnum },
1754 =item send_csv OPTION => VALUE, ...
1756 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1760 protocol - currently only "ftp"
1766 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1767 and YYMMDDHHMMSS is a timestamp.
1769 See L</print_csv> for a description of the output format.
1774 my($self, %opt) = @_;
1778 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1779 mkdir $spooldir, 0700 unless -d $spooldir;
1781 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1782 my $file = "$spooldir/$tracctnum.csv";
1784 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1786 open(CSV, ">$file") or die "can't open $file: $!";
1794 if ( $opt{protocol} eq 'ftp' ) {
1795 eval "use Net::FTP;";
1797 $net = Net::FTP->new($opt{server}) or die @$;
1799 die "unknown protocol: $opt{protocol}";
1802 $net->login( $opt{username}, $opt{password} )
1803 or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1805 $net->binary or die "can't set binary mode";
1807 $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1809 $net->put($file) or die "can't put $file: $!";
1819 Spools CSV invoice data.
1825 =item format - any of FS::Misc::::Invoicing::spool_formats
1827 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1828 customer has the corresponding invoice destinations set (see
1829 L<FS::cust_main_invoice>).
1831 =item agent_spools - if set to a true value, will spool to per-agent files
1832 rather than a single global file
1834 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1835 append to that spool. L<FS::Cron::upload> will then send the spool file to
1838 =item balanceover - if set, only spools the invoice if the total amount owed on
1839 this invoice and all older invoices is greater than the specified amount.
1841 =item time - the "current time". Controls the printing of past due messages
1849 my($self, %opt) = @_;
1851 my $time = $opt{'time'} || time;
1852 my $cust_main = $self->cust_main;
1854 if ( $opt{'dest'} ) {
1855 my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1856 $cust_main->invoicing_list;
1857 return 'N/A' unless $invoicing_list{$opt{'dest'}}
1858 || ! keys %invoicing_list;
1861 if ( $opt{'balanceover'} ) {
1863 if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1866 my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1867 mkdir $spooldir, 0700 unless -d $spooldir;
1869 my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1872 if ( $opt{'agent_spools'} ) {
1873 $file = 'agentnum'.$cust_main->agentnum;
1878 if ( $opt{'upload_targetnum'} ) {
1879 $spooldir .= '/target'.$opt{'upload_targetnum'};
1880 mkdir $spooldir, 0700 unless -d $spooldir;
1881 } # otherwise it just goes into export.xxx/cust_bill
1883 if ( lc($opt{'format'}) eq 'billco' ) {
1887 $file = "$spooldir/$file.csv";
1889 my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1891 open(CSV, ">>$file") or die "can't open $file: $!";
1892 flock(CSV, LOCK_EX);
1897 if ( lc($opt{'format'}) eq 'billco' ) {
1899 flock(CSV, LOCK_UN);
1902 $file =~ s/-header.csv$/-detail.csv/;
1904 open(CSV,">>$file") or die "can't open $file: $!";
1905 flock(CSV, LOCK_EX);
1909 print CSV $detail if defined($detail);
1911 flock(CSV, LOCK_UN);
1918 =item print_csv OPTION => VALUE, ...
1920 Returns CSV data for this invoice.
1924 format - 'default', 'billco', 'oneline', 'bridgestone'
1926 Returns a list consisting of two scalars. The first is a single line of CSV
1927 header information for this invoice. The second is one or more lines of CSV
1928 detail information for this invoice.
1930 If I<format> is not specified or "default", the fields of the CSV file are as
1933 record_type, invnum, custnum, _date, charged, first, last, company, address1,
1934 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1938 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1940 B<record_type> is C<cust_bill> for the initial header line only. The
1941 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1942 fields are filled in.
1944 B<record_type> is C<cust_bill_pkg> for detail lines. Only the first two fields
1945 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1948 =item invnum - invoice number
1950 =item custnum - customer number
1952 =item _date - invoice date
1954 =item charged - total invoice amount
1956 =item first - customer first name
1958 =item last - customer first name
1960 =item company - company name
1962 =item address1 - address line 1
1964 =item address2 - address line 1
1974 =item pkg - line item description
1976 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1978 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1980 =item sdate - start date for recurring fee
1982 =item edate - end date for recurring fee
1986 If I<format> is "billco", the fields of the header CSV file are as follows:
1988 +-------------------------------------------------------------------+
1989 | FORMAT HEADER FILE |
1990 |-------------------------------------------------------------------|
1991 | Field | Description | Name | Type | Width |
1992 | 1 | N/A-Leave Empty | RC | CHAR | 2 |
1993 | 2 | N/A-Leave Empty | CUSTID | CHAR | 15 |
1994 | 3 | Transaction Account No | TRACCTNUM | CHAR | 15 |
1995 | 4 | Transaction Invoice No | TRINVOICE | CHAR | 15 |
1996 | 5 | Transaction Zip Code | TRZIP | CHAR | 5 |
1997 | 6 | Transaction Company Bill To | TRCOMPANY | CHAR | 30 |
1998 | 7 | Transaction Contact Bill To | TRNAME | CHAR | 30 |
1999 | 8 | Additional Address Unit Info | TRADDR1 | CHAR | 30 |
2000 | 9 | Bill To Street Address | TRADDR2 | CHAR | 30 |
2001 | 10 | Ancillary Billing Information | TRADDR3 | CHAR | 30 |
2002 | 11 | Transaction City Bill To | TRCITY | CHAR | 20 |
2003 | 12 | Transaction State Bill To | TRSTATE | CHAR | 2 |
2004 | 13 | Bill Cycle Close Date | CLOSEDATE | CHAR | 10 |
2005 | 14 | Bill Due Date | DUEDATE | CHAR | 10 |
2006 | 15 | Previous Balance | BALFWD | NUM* | 9 |
2007 | 16 | Pmt/CR Applied | CREDAPPLY | NUM* | 9 |
2008 | 17 | Total Current Charges | CURRENTCHG | NUM* | 9 |
2009 | 18 | Total Amt Due | TOTALDUE | NUM* | 9 |
2010 | 19 | Total Amt Due | AMTDUE | NUM* | 9 |
2011 | 20 | 30 Day Aging | AMT30 | NUM* | 9 |
2012 | 21 | 60 Day Aging | AMT60 | NUM* | 9 |
2013 | 22 | 90 Day Aging | AMT90 | NUM* | 9 |
2014 | 23 | Y/N | AGESWITCH | CHAR | 1 |
2015 | 24 | Remittance automation | SCANLINE | CHAR | 100 |
2016 | 25 | Total Taxes & Fees | TAXTOT | NUM* | 9 |
2017 | 26 | Customer Reference Number | CUSTREF | CHAR | 15 |
2018 | 27 | Federal Tax*** | FEDTAX | NUM* | 9 |
2019 | 28 | State Tax*** | STATETAX | NUM* | 9 |
2020 | 29 | Other Taxes & Fees*** | OTHERTAX | NUM* | 9 |
2021 +-------+-------------------------------+------------+------+-------+
2023 If I<format> is "billco", the fields of the detail CSV file are as follows:
2025 FORMAT FOR DETAIL FILE
2027 Field | Description | Name | Type | Width
2028 1 | N/A-Leave Empty | RC | CHAR | 2
2029 2 | N/A-Leave Empty | CUSTID | CHAR | 15
2030 3 | Account Number | TRACCTNUM | CHAR | 15
2031 4 | Invoice Number | TRINVOICE | CHAR | 15
2032 5 | Line Sequence (sort order) | LINESEQ | NUM | 6
2033 6 | Transaction Detail | DETAILS | CHAR | 100
2034 7 | Amount | AMT | NUM* | 9
2035 8 | Line Format Control** | LNCTRL | CHAR | 2
2036 9 | Grouping Code | GROUP | CHAR | 2
2037 10 | User Defined | ACCT CODE | CHAR | 15
2039 If format is 'oneline', there is no detail file. Each invoice has a
2040 header line only, with the fields:
2042 Agent number, agent name, customer number, first name, last name, address
2043 line 1, address line 2, city, state, zip, invoice date, invoice number,
2044 amount charged, amount due, previous balance, due date.
2046 and then, for each line item, three columns containing the package number,
2047 description, and amount.
2049 If format is 'bridgestone', there is no detail file. Each invoice has a
2050 header line with the following fields in a fixed-width format:
2052 Customer number (in display format), date, name (first last), company,
2053 address 1, address 2, city, state, zip.
2055 This is a mailing list format, and has no per-invoice fields. To avoid
2056 sending redundant notices, the spooling event should have a "once" or
2057 "once_percust_every" condition.
2062 my($self, %opt) = @_;
2064 eval "use Text::CSV_XS";
2067 my $cust_main = $self->cust_main;
2069 my $csv = Text::CSV_XS->new({'always_quote'=>1});
2070 my $format = lc($opt{'format'});
2072 my $time = $opt{'time'} || time;
2074 if ( $format eq 'billco' ) {
2077 $taxtotal += $_->{'amount'} foreach $self->_items_tax;
2079 my $duedate = $self->due_date2str('%m/%d/%Y'); #date_format?
2081 my( $previous_balance, @unused ) = $self->previous; #previous balance
2083 my $pmt_cr_applied = 0;
2084 $pmt_cr_applied += $_->{'amount'}
2085 foreach ( $self->_items_payments, $self->_items_credits ) ;
2087 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2090 '', # 1 | N/A-Leave Empty CHAR 2
2091 '', # 2 | N/A-Leave Empty CHAR 15
2092 $opt{'tracctnum'}, # 3 | Transaction Account No CHAR 15
2093 $self->invnum, # 4 | Transaction Invoice No CHAR 15
2094 $cust_main->zip, # 5 | Transaction Zip Code CHAR 5
2095 $cust_main->company, # 6 | Transaction Company Bill To CHAR 30
2096 #$cust_main->payname, # 7 | Transaction Contact Bill To CHAR 30
2097 $cust_main->contact, # 7 | Transaction Contact Bill To CHAR 30
2098 $cust_main->address2, # 8 | Additional Address Unit Info CHAR 30
2099 $cust_main->address1, # 9 | Bill To Street Address CHAR 30
2100 '', # 10 | Ancillary Billing Information CHAR 30
2101 $cust_main->city, # 11 | Transaction City Bill To CHAR 20
2102 $cust_main->state, # 12 | Transaction State Bill To CHAR 2
2105 time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR 10
2108 $duedate, # 14 | Bill Due Date CHAR 10
2110 $previous_balance, # 15 | Previous Balance NUM* 9
2111 $pmt_cr_applied, # 16 | Pmt/CR Applied NUM* 9
2112 sprintf("%.2f", $self->charged), # 17 | Total Current Charges NUM* 9
2113 $totaldue, # 18 | Total Amt Due NUM* 9
2114 $totaldue, # 19 | Total Amt Due NUM* 9
2115 '', # 20 | 30 Day Aging NUM* 9
2116 '', # 21 | 60 Day Aging NUM* 9
2117 '', # 22 | 90 Day Aging NUM* 9
2118 'N', # 23 | Y/N CHAR 1
2119 '', # 24 | Remittance automation CHAR 100
2120 $taxtotal, # 25 | Total Taxes & Fees NUM* 9
2121 $self->custnum, # 26 | Customer Reference Number CHAR 15
2122 '0', # 27 | Federal Tax*** NUM* 9
2123 sprintf("%.2f", $taxtotal), # 28 | State Tax*** NUM* 9
2124 '0', # 29 | Other Taxes & Fees*** NUM* 9
2127 } elsif ( $format eq 'oneline' ) { #name
2129 my ($previous_balance) = $self->previous;
2130 $previous_balance = sprintf('%.2f', $previous_balance);
2131 my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2137 $self->_items_pkg, #_items_nontax? no sections or anything
2142 $cust_main->agentnum,
2143 $cust_main->agent->agent,
2147 $cust_main->company,
2148 $cust_main->address1,
2149 $cust_main->address2,
2155 time2str("%x", $self->_date),
2160 $self->due_date2str("%x"),
2165 } elsif ( $format eq 'bridgestone' ) {
2167 # bypass the CSV stuff and just return this
2168 my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2169 my $zip = $cust_main->zip;
2171 my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2175 "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2177 $cust_main->display_custnum,
2179 uc(substr($cust_main->contact_firstlast,0,30)),
2180 uc(substr($cust_main->company ,0,30)),
2181 uc(substr($cust_main->address1 ,0,30)),
2182 uc(substr($cust_main->address2 ,0,30)),
2183 uc(substr($cust_main->city ,0,20)),
2184 uc($cust_main->state),
2190 } elsif ( $format eq 'ics' ) {
2192 my $bill = $cust_main->bill_location;
2193 my $zip = $bill->zip;
2197 if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2202 # minor false laziness with print_generic
2203 my ($previous_balance) = $self->previous;
2204 my $balance_due = $self->owed + $previous_balance;
2205 my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2206 my $credit_total = sum(0, map { $_->{'amount'} } $self->_items_credits);
2209 if ( $self->due_date and $time >= $self->due_date ) {
2210 $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2214 my $header = sprintf(
2215 '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2216 $cust_main->display_custnum, #BID
2217 uc($cust_main->first), #FNAME
2218 uc($cust_main->last), #LNAME
2219 '00', #BATCH, should this ever be anything else?
2220 uc($cust_main->company), #COMP
2221 uc($bill->address1), #STREET1
2222 uc($bill->address2), #STREET2
2223 uc($bill->city), #CITY
2224 uc($bill->state), #STATE
2227 time2str('%Y%m%d', $self->_date), #BILL_DATE
2228 $self->due_date2str('%Y%m%d'), #DUE_DATE,
2229 ( map {sprintf('%0.2f', $_)}
2230 $balance_due, #AMNT_DUE
2231 $previous_balance, #PREV_BAL
2232 $payment_total, #PYMT_RCVD
2233 $credit_total, #CREDITS
2234 $previous_balance, #BEG_BAL--is this correct?
2235 $self->charged, #NEW_CHRG
2238 $past_due, #PAST_MSG
2242 my %svc_class = ('' => ''); # maybe cache this more persistently?
2244 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2246 my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2247 my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2251 my @dates = ( $self->_date, undef );
2252 if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2253 $dates[1] = $prev->sdate; #questionable
2256 # generate an 01 detail for each service
2257 my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2258 foreach my $cust_svc ( @svcs ) {
2259 $show_pkgnum = ''; # hide it if we're showing svcnums
2261 my $svcpart = $cust_svc->svcpart;
2262 if (!exists($svc_class{$svcpart})) {
2263 my $classnum = $cust_svc->part_svc->classnum;
2264 my $part_svc_class = FS::part_svc_class->by_key($classnum)
2266 $svc_class{$svcpart} = $part_svc_class ?
2267 $part_svc_class->classname :
2271 my @h_label = $cust_svc->label(@dates, 'I');
2272 push @details, sprintf('01%-9s%-20s%-47s',
2274 $svc_class{$svcpart},
2277 } #foreach $cust_svc
2280 my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2281 if ($cust_bill_pkg->recur > 0) {
2282 $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2283 time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2285 push @details, sprintf('02%-6s%-60s%-10s',
2288 sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2290 } #foreach $cust_bill_pkg
2292 # Tag this row so that we know whether this is one page (1), two pages
2293 # (2), # or "big" (B). The tag will be stripped off before uploading.
2294 if ( scalar(@details) < 12 ) {
2296 } elsif ( scalar(@details) < 58 ) {
2302 return join('', $header, @details, "\n");
2310 time2str("%x", $self->_date),
2311 sprintf("%.2f", $self->charged),
2312 ( map { $cust_main->getfield($_) }
2313 qw( first last company address1 address2 city state zip country ) ),
2315 ) or die "can't create csv";
2318 my $header = $csv->string. "\n";
2321 if ( lc($opt{'format'}) eq 'billco' ) {
2324 foreach my $item ( $self->_items_pkg ) {
2327 '', # 1 | N/A-Leave Empty CHAR 2
2328 '', # 2 | N/A-Leave Empty CHAR 15
2329 $opt{'tracctnum'}, # 3 | Account Number CHAR 15
2330 $self->invnum, # 4 | Invoice Number CHAR 15
2331 $lineseq++, # 5 | Line Sequence (sort order) NUM 6
2332 $item->{'description'}, # 6 | Transaction Detail CHAR 100
2333 $item->{'amount'}, # 7 | Amount NUM* 9
2334 '', # 8 | Line Format Control** CHAR 2
2335 '', # 9 | Grouping Code CHAR 2
2336 '', # 10 | User Defined CHAR 15
2339 $detail .= $csv->string. "\n";
2343 } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2349 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2351 my($pkg, $setup, $recur, $sdate, $edate);
2352 if ( $cust_bill_pkg->pkgnum ) {
2354 ($pkg, $setup, $recur, $sdate, $edate) = (
2355 $cust_bill_pkg->part_pkg->pkg,
2356 ( $cust_bill_pkg->setup != 0
2357 ? sprintf("%.2f", $cust_bill_pkg->setup )
2359 ( $cust_bill_pkg->recur != 0
2360 ? sprintf("%.2f", $cust_bill_pkg->recur )
2362 ( $cust_bill_pkg->sdate
2363 ? time2str("%x", $cust_bill_pkg->sdate)
2365 ($cust_bill_pkg->edate
2366 ?time2str("%x", $cust_bill_pkg->edate)
2370 } else { #pkgnum tax
2371 next unless $cust_bill_pkg->setup != 0;
2372 $pkg = $cust_bill_pkg->desc;
2373 $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2374 ( $sdate, $edate ) = ( '', '' );
2380 ( map { '' } (1..11) ),
2381 ($pkg, $setup, $recur, $sdate, $edate)
2382 ) or die "can't create csv";
2384 $detail .= $csv->string. "\n";
2390 ( $header, $detail );
2396 Pays this invoice with a compliemntary payment. If there is an error,
2397 returns the error, otherwise returns false.
2403 my $cust_pay = new FS::cust_pay ( {
2404 'invnum' => $self->invnum,
2405 'paid' => $self->owed,
2408 'payinfo' => $self->cust_main->payinfo,
2416 Attempts to pay this invoice with a credit card payment via a
2417 Business::OnlinePayment realtime gateway. See
2418 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2419 for supported processors.
2425 $self->realtime_bop( 'CC', @_ );
2430 Attempts to pay this invoice with an electronic check (ACH) payment via a
2431 Business::OnlinePayment realtime gateway. See
2432 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2433 for supported processors.
2439 $self->realtime_bop( 'ECHECK', @_ );
2444 Attempts to pay this invoice with phone bill (LEC) payment via a
2445 Business::OnlinePayment realtime gateway. See
2446 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2447 for supported processors.
2453 $self->realtime_bop( 'LEC', @_ );
2457 my( $self, $method ) = (shift,shift);
2458 my $conf = $self->conf;
2461 my $cust_main = $self->cust_main;
2462 my $balance = $cust_main->balance;
2463 my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2464 $amount = sprintf("%.2f", $amount);
2465 return "not run (balance $balance)" unless $amount > 0;
2467 my $description = 'Internet Services';
2468 if ( $conf->exists('business-onlinepayment-description') ) {
2469 my $dtempl = $conf->config('business-onlinepayment-description');
2471 my $agent_obj = $cust_main->agent
2472 or die "can't retreive agent for $cust_main (agentnum ".
2473 $cust_main->agentnum. ")";
2474 my $agent = $agent_obj->agent;
2475 my $pkgs = join(', ',
2476 map { $_->part_pkg->pkg }
2477 grep { $_->pkgnum } $self->cust_bill_pkg
2479 $description = eval qq("$dtempl");
2482 $cust_main->realtime_bop($method, $amount,
2483 'description' => $description,
2484 'invnum' => $self->invnum,
2485 #this didn't do what we want, it just calls apply_payments_and_credits
2487 'apply_to_invoice' => 1,
2490 #this changes application behavior: auto payments
2491 #triggered against a specific invoice are now applied
2492 #to that invoice instead of oldest open.
2498 =item batch_card OPTION => VALUE...
2500 Adds a payment for this invoice to the pending credit card batch (see
2501 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2502 runs the payment using a realtime gateway.
2507 my ($self, %options) = @_;
2508 my $cust_main = $self->cust_main;
2510 $options{invnum} = $self->invnum;
2512 $cust_main->batch_card(%options);
2515 sub _agent_template {
2517 $self->cust_main->agent_template;
2520 sub _agent_invoice_from {
2522 $self->cust_main->agent_invoice_from;
2525 =item invoice_barcode DIR_OR_FALSE
2527 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2528 it is taken as the temp directory where the PNG file will be generated and the
2529 PNG file name is returned. Otherwise, the PNG image itself is returned.
2533 sub invoice_barcode {
2534 my ($self, $dir) = (shift,shift);
2536 my $gdbar = new GD::Barcode('Code39',$self->invnum);
2537 die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2538 my $gd = $gdbar->plot(Height => 30);
2541 my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2545 ) or die "can't open temp file: $!\n";
2546 print $bh $gd->png or die "cannot write barcode to file: $!\n";
2547 my $png_file = $bh->filename;
2554 =item invnum_date_pretty
2556 Returns a string with the invoice number and date, for example:
2557 "Invoice #54 (3/20/2008)"
2561 sub invnum_date_pretty {
2563 $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2566 #sub _items_extra_usage_sections {
2568 # my $escape = shift;
2570 # my %sections = ();
2572 # my %usage_class = map{ $_->classname, $_ } qsearch('usage_class', {});
2573 # foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2575 # next unless $cust_bill_pkg->pkgnum > 0;
2577 # foreach my $section ( keys %usage_class ) {
2579 # my $usage = $cust_bill_pkg->usage($section);
2581 # next unless $usage && $usage > 0;
2583 # $sections{$section} ||= 0;
2584 # $sections{$section} += $usage;
2590 # map { { 'description' => &{$escape}($_),
2591 # 'subtotal' => $sections{$_},
2592 # 'summarized' => '',
2593 # 'tax_section' => '',
2596 # sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2600 sub _items_extra_usage_sections {
2602 my $conf = $self->conf;
2610 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2612 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2613 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2614 next unless $cust_bill_pkg->pkgnum > 0;
2616 foreach my $classnum ( keys %usage_class ) {
2617 my $section = $usage_class{$classnum}->classname;
2618 $classnums{$section} = $classnum;
2620 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2621 my $amount = $detail->amount;
2622 next unless $amount && $amount > 0;
2624 $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2625 $sections{$section}{amount} += $amount; #subtotal
2626 $sections{$section}{calls}++;
2627 $sections{$section}{duration} += $detail->duration;
2629 my $desc = $detail->regionname;
2630 my $description = $desc;
2631 $description = substr($desc, 0, $maxlength). '...'
2632 if $format eq 'latex' && length($desc) > $maxlength;
2634 $lines{$section}{$desc} ||= {
2635 description => &{$escape}($description),
2636 #pkgpart => $part_pkg->pkgpart,
2637 pkgnum => $cust_bill_pkg->pkgnum,
2642 #unit_amount => $cust_bill_pkg->unitrecur,
2643 quantity => $cust_bill_pkg->quantity,
2644 product_code => 'N/A',
2645 ext_description => [],
2648 $lines{$section}{$desc}{amount} += $amount;
2649 $lines{$section}{$desc}{calls}++;
2650 $lines{$section}{$desc}{duration} += $detail->duration;
2656 my %sectionmap = ();
2657 foreach (keys %sections) {
2658 my $usage_class = $usage_class{$classnums{$_}};
2659 $sectionmap{$_} = { 'description' => &{$escape}($_),
2660 'amount' => $sections{$_}{amount}, #subtotal
2661 'calls' => $sections{$_}{calls},
2662 'duration' => $sections{$_}{duration},
2664 'tax_section' => '',
2665 'sort_weight' => $usage_class->weight,
2666 ( $usage_class->format
2667 ? ( map { $_ => $usage_class->$_($format) }
2668 qw( description_generator header_generator total_generator total_line_generator )
2675 my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2679 foreach my $section ( keys %lines ) {
2680 foreach my $line ( keys %{$lines{$section}} ) {
2681 my $l = $lines{$section}{$line};
2682 $l->{section} = $sectionmap{$section};
2683 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2684 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2689 return(\@sections, \@lines);
2695 my $end = $self->_date;
2697 # start at date of previous invoice + 1 second or 0 if no previous invoice
2698 my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2699 $start = 0 if !$start;
2702 my $cust_main = $self->cust_main;
2703 my @pkgs = $cust_main->all_pkgs;
2704 my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2707 foreach my $pkg ( @pkgs ) {
2708 my @h_cust_svc = $pkg->h_cust_svc($end);
2709 foreach my $h_cust_svc ( @h_cust_svc ) {
2710 next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2711 next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2713 my $inserted = $h_cust_svc->date_inserted;
2714 my $deleted = $h_cust_svc->date_deleted;
2715 my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2717 $phone_deleted = $h_cust_svc->h_svc_x($deleted) if $deleted;
2719 # DID either activated or ported in; cannot be both for same DID simultaneously
2720 if ($inserted >= $start && $inserted <= $end && $phone_inserted
2721 && (!$phone_inserted->lnp_status
2722 || $phone_inserted->lnp_status eq ''
2723 || $phone_inserted->lnp_status eq 'native')) {
2726 else { # this one not so clean, should probably move to (h_)svc_phone
2727 my $phone_portedin = qsearchs( 'h_svc_phone',
2728 { 'svcnum' => $h_cust_svc->svcnum,
2729 'lnp_status' => 'portedin' },
2730 FS::h_svc_phone->sql_h_searchs($end),
2732 $num_portedin++ if $phone_portedin;
2735 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2736 if($deleted >= $start && $deleted <= $end && $phone_deleted
2737 && (!$phone_deleted->lnp_status
2738 || $phone_deleted->lnp_status ne 'portingout')) {
2741 elsif($deleted >= $start && $deleted <= $end && $phone_deleted
2742 && $phone_deleted->lnp_status
2743 && $phone_deleted->lnp_status eq 'portingout') {
2747 # increment usage minutes
2748 if ( $phone_inserted ) {
2749 my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2750 $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2753 warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2756 # don't look at this service again
2757 push @seen, $h_cust_svc->svcnum;
2761 $minutes = sprintf("%d", $minutes);
2762 ("Activated: $num_activated Ported-In: $num_portedin Deactivated: "
2763 . "$num_deactivated Ported-Out: $num_portedout ",
2764 "Total Minutes: $minutes");
2767 sub _items_accountcode_cdr {
2772 my $section = { 'amount' => 0,
2775 'sort_weight' => '',
2777 'description' => 'Usage by Account Code',
2783 my %accountcodes = ();
2785 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2786 next unless $cust_bill_pkg->pkgnum > 0;
2788 my @header = $cust_bill_pkg->details_header;
2789 next unless scalar(@header);
2790 $section->{'header'} = join(',',@header);
2792 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2794 $section->{'header'} = $detail->formatted('format' => $format)
2795 if($detail->detail eq $section->{'header'});
2797 my $accountcode = $detail->accountcode;
2798 next unless $accountcode;
2800 my $amount = $detail->amount;
2801 next unless $amount && $amount > 0;
2803 $accountcodes{$accountcode} ||= {
2804 description => $accountcode,
2811 product_code => 'N/A',
2812 section => $section,
2813 ext_description => [ $section->{'header'} ],
2817 $section->{'amount'} += $amount;
2818 $accountcodes{$accountcode}{'amount'} += $amount;
2819 $accountcodes{$accountcode}{calls}++;
2820 $accountcodes{$accountcode}{duration} += $detail->duration;
2821 push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2825 foreach my $l ( values %accountcodes ) {
2826 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2827 my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2828 foreach my $sorted_detail ( @sorted_detail ) {
2829 push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2831 delete $l->{detail_temp};
2835 my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2837 return ($section,\@sorted_lines);
2840 sub _items_svc_phone_sections {
2842 my $conf = $self->conf;
2850 my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2852 my %usage_class = map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2853 $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2855 foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2856 next unless $cust_bill_pkg->pkgnum > 0;
2858 my @header = $cust_bill_pkg->details_header;
2859 next unless scalar(@header);
2861 foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2863 my $phonenum = $detail->phonenum;
2864 next unless $phonenum;
2866 my $amount = $detail->amount;
2867 next unless $amount && $amount > 0;
2869 $sections{$phonenum} ||= { 'amount' => 0,
2872 'sort_weight' => -1,
2873 'phonenum' => $phonenum,
2875 $sections{$phonenum}{amount} += $amount; #subtotal
2876 $sections{$phonenum}{calls}++;
2877 $sections{$phonenum}{duration} += $detail->duration;
2879 my $desc = $detail->regionname;
2880 my $description = $desc;
2881 $description = substr($desc, 0, $maxlength). '...'
2882 if $format eq 'latex' && length($desc) > $maxlength;
2884 $lines{$phonenum}{$desc} ||= {
2885 description => &{$escape}($description),
2886 #pkgpart => $part_pkg->pkgpart,
2894 product_code => 'N/A',
2895 ext_description => [],
2898 $lines{$phonenum}{$desc}{amount} += $amount;
2899 $lines{$phonenum}{$desc}{calls}++;
2900 $lines{$phonenum}{$desc}{duration} += $detail->duration;
2902 my $line = $usage_class{$detail->classnum}->classname;
2903 $sections{"$phonenum $line"} ||=
2907 'sort_weight' => $usage_class{$detail->classnum}->weight,
2908 'phonenum' => $phonenum,
2909 'header' => [ @header ],
2911 $sections{"$phonenum $line"}{amount} += $amount; #subtotal
2912 $sections{"$phonenum $line"}{calls}++;
2913 $sections{"$phonenum $line"}{duration} += $detail->duration;
2915 $lines{"$phonenum $line"}{$desc} ||= {
2916 description => &{$escape}($description),
2917 #pkgpart => $part_pkg->pkgpart,
2925 product_code => 'N/A',
2926 ext_description => [],
2929 $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2930 $lines{"$phonenum $line"}{$desc}{calls}++;
2931 $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2932 push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2933 $detail->formatted('format' => $format);
2938 my %sectionmap = ();
2939 my $simple = new FS::usage_class { format => 'simple' }; #bleh
2940 foreach ( keys %sections ) {
2941 my @header = @{ $sections{$_}{header} || [] };
2943 new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2944 my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2945 my $usage_class = $summary ? $simple : $usage_simple;
2946 my $ending = $summary ? ' usage charges' : '';
2949 $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2951 $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2952 'amount' => $sections{$_}{amount}, #subtotal
2953 'calls' => $sections{$_}{calls},
2954 'duration' => $sections{$_}{duration},
2956 'tax_section' => '',
2957 'phonenum' => $sections{$_}{phonenum},
2958 'sort_weight' => $sections{$_}{sort_weight},
2959 'post_total' => $summary, #inspire pagebreak
2961 ( map { $_ => $usage_class->$_($format, %gen_opt) }
2962 qw( description_generator
2965 total_line_generator
2972 my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2973 $a->{sort_weight} <=> $b->{sort_weight}
2978 foreach my $section ( keys %lines ) {
2979 foreach my $line ( keys %{$lines{$section}} ) {
2980 my $l = $lines{$section}{$line};
2981 $l->{section} = $sectionmap{$section};
2982 $l->{amount} = sprintf( "%.2f", $l->{amount} );
2983 #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2988 if($conf->exists('phone_usage_class_summary')) {
2989 # this only works with Latex
2993 # after this, we'll have only two sections per DID:
2994 # Calls Summary and Calls Detail
2995 foreach my $section ( @sections ) {
2996 if($section->{'post_total'}) {
2997 $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2998 $section->{'total_line_generator'} = sub { '' };
2999 $section->{'total_generator'} = sub { '' };
3000 $section->{'header_generator'} = sub { '' };
3001 $section->{'description_generator'} = '';
3002 push @newsections, $section;
3003 my %calls_detail = %$section;
3004 $calls_detail{'post_total'} = '';
3005 $calls_detail{'sort_weight'} = '';
3006 $calls_detail{'description_generator'} = sub { '' };
3007 $calls_detail{'header_generator'} = sub {
3008 return ' & Date/Time & Called Number & Duration & Price'
3009 if $format eq 'latex';
3012 $calls_detail{'description'} = 'Calls Detail: '
3013 . $section->{'phonenum'};
3014 push @newsections, \%calls_detail;
3018 # after this, each usage class is collapsed/summarized into a single
3019 # line under the Calls Summary section
3020 foreach my $newsection ( @newsections ) {
3021 if($newsection->{'post_total'}) { # this means Calls Summary
3022 foreach my $section ( @sections ) {
3023 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'}
3024 && !$section->{'post_total'});
3025 my $newdesc = $section->{'description'};
3026 my $tn = $section->{'phonenum'};
3027 $newdesc =~ s/$tn//g;
3028 my $line = { ext_description => [],
3032 calls => $section->{'calls'},
3033 section => $newsection,
3034 duration => $section->{'duration'},
3035 description => $newdesc,
3036 amount => sprintf("%.2f",$section->{'amount'}),
3037 product_code => 'N/A',
3039 push @newlines, $line;
3044 # after this, Calls Details is populated with all CDRs
3045 foreach my $newsection ( @newsections ) {
3046 if(!$newsection->{'post_total'}) { # this means Calls Details
3047 foreach my $line ( @lines ) {
3048 next unless (scalar(@{$line->{'ext_description'}}) &&
3049 $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
3051 my @extdesc = @{$line->{'ext_description'}};
3053 foreach my $extdesc ( @extdesc ) {
3054 $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
3055 push @newextdesc, $extdesc;
3057 $line->{'ext_description'} = \@newextdesc;
3058 $line->{'section'} = $newsection;
3059 push @newlines, $line;
3064 return(\@newsections, \@newlines);
3067 return(\@sections, \@lines);
3071 sub _items_previous {
3073 my $conf = $self->conf;
3074 my $cust_main = $self->cust_main;
3075 my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
3077 foreach ( @pr_cust_bill ) {
3078 my $date = $conf->exists('invoice_show_prior_due_date')
3079 ? 'due '. $_->due_date2str($date_format)
3080 : time2str($date_format, $_->_date);
3082 'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
3083 #'pkgpart' => 'N/A',
3085 'amount' => sprintf("%.2f", $_->owed),
3091 # 'description' => 'Previous Balance',
3092 # #'pkgpart' => 'N/A',
3093 # 'pkgnum' => 'N/A',
3094 # 'amount' => sprintf("%10.2f", $pr_total ),
3095 # 'ext_description' => [ map {
3096 # "Invoice ". $_->invnum.
3097 # " (". time2str("%x",$_->_date). ") ".
3098 # sprintf("%10.2f", $_->owed)
3099 # } @pr_cust_bill ],
3104 sub _items_credits {
3105 my( $self, %opt ) = @_;
3106 my $trim_len = $opt{'trim_len'} || 60;
3110 foreach ( $self->cust_credited ) {
3112 #something more elaborate if $_->amount ne $_->cust_credit->credited ?
3114 my $reason = substr($_->cust_credit->reason, 0, $trim_len);
3115 $reason .= '...' if length($reason) < length($_->cust_credit->reason);
3116 $reason = " ($reason) " if $reason;
3119 #'description' => 'Credit ref\#'. $_->crednum.
3120 # " (". time2str("%x",$_->cust_credit->_date) .")".
3122 'description' => $self->mt('Credit applied').' '.
3123 time2str($date_format,$_->cust_credit->_date). $reason,
3124 'amount' => sprintf("%.2f",$_->amount),
3132 sub _items_payments {
3136 #get & print payments
3137 foreach ( $self->cust_bill_pay ) {
3139 #something more elaborate if $_->amount ne ->cust_pay->paid ?
3141 my $desc = $self->mt('Payment received').' '.
3142 time2str($date_format,$_->cust_pay->_date );
3143 $desc .= $self->mt(' via ' . $_->cust_pay->payby_payinfo_pretty)
3144 if ( $self->conf->exists('invoice_payment_details') );
3147 'description' => $desc,
3148 'amount' => sprintf("%.2f", $_->amount )
3157 =item call_details [ OPTION => VALUE ... ]
3159 Returns an array of CSV strings representing the call details for this invoice
3160 The only option available is the boolean prepend_billed_number
3165 my ($self, %opt) = @_;
3167 my $format_function = sub { shift };
3169 if ($opt{prepend_billed_number}) {
3170 $format_function = sub {
3174 $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3179 my @details = map { $_->details( 'format_function' => $format_function,
3180 'escape_function' => sub{ return() },
3184 $self->cust_bill_pkg;
3185 my $header = $details[0];
3186 ( $header, grep { $_ ne $header } @details );
3196 =item process_reprint
3200 sub process_reprint {
3201 process_re_X('print', @_);
3204 =item process_reemail
3208 sub process_reemail {
3209 process_re_X('email', @_);
3217 process_re_X('fax', @_);
3225 process_re_X('ftp', @_);
3232 sub process_respool {
3233 process_re_X('spool', @_);
3236 use Storable qw(thaw);
3240 my( $method, $job ) = ( shift, shift );
3241 warn "$me process_re_X $method for job $job\n" if $DEBUG;
3243 my $param = thaw(decode_base64(shift));
3244 warn Dumper($param) if $DEBUG;
3255 # spool_invoice ftp_invoice fax_invoice print_invoice
3256 my($method, $job, %param ) = @_;
3258 warn "re_X $method for job $job with param:\n".
3259 join( '', map { " $_ => ". $param{$_}. "\n" } keys %param );
3262 #some false laziness w/search/cust_bill.html
3264 my $orderby = 'ORDER BY cust_bill._date';
3266 my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3268 my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3270 my @cust_bill = qsearch( {
3271 #'select' => "cust_bill.*",
3272 'table' => 'cust_bill',
3273 'addl_from' => $addl_from,
3275 'extra_sql' => $extra_sql,
3276 'order_by' => $orderby,
3280 $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3282 warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3285 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3286 foreach my $cust_bill ( @cust_bill ) {
3287 $cust_bill->$method();
3289 if ( $job ) { #progressbar foo
3291 if ( time - $min_sec > $last ) {
3292 my $error = $job->update_statustext(
3293 int( 100 * $num / scalar(@cust_bill) )
3295 die $error if $error;
3306 =head1 CLASS METHODS
3312 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3317 my ($class, $start, $end) = @_;
3319 $class->paid_sql($start, $end). ' - '.
3320 $class->credited_sql($start, $end);
3325 Returns an SQL fragment to retreive the net amount (charged minus credited).
3330 my ($class, $start, $end) = @_;
3331 'charged - '. $class->credited_sql($start, $end);
3336 Returns an SQL fragment to retreive the amount paid against this invoice.
3341 my ($class, $start, $end) = @_;
3342 $start &&= "AND cust_bill_pay._date <= $start";
3343 $end &&= "AND cust_bill_pay._date > $end";
3344 $start = '' unless defined($start);
3345 $end = '' unless defined($end);
3346 "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3347 WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end )";
3352 Returns an SQL fragment to retreive the amount credited against this invoice.
3357 my ($class, $start, $end) = @_;
3358 $start &&= "AND cust_credit_bill._date <= $start";
3359 $end &&= "AND cust_credit_bill._date > $end";
3360 $start = '' unless defined($start);
3361 $end = '' unless defined($end);
3362 "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3363 WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end )";
3368 Returns an SQL fragment to retrieve the due date of an invoice.
3369 Currently only supported on PostgreSQL.
3374 my $conf = new FS::Conf;
3378 cust_bill.invoice_terms,
3379 cust_main.invoice_terms,
3380 \''.($conf->config('invoice_default_terms') || '').'\'
3381 ), E\'Net (\\\\d+)\'
3383 ) * 86400 + cust_bill._date'
3386 =item search_sql_where HASHREF
3388 Class method which returns an SQL WHERE fragment to search for parameters
3389 specified in HASHREF. Valid parameters are
3395 List reference of start date, end date, as UNIX timestamps.
3405 List reference of charged limits (exclusive).
3409 List reference of charged limits (exclusive).
3413 flag, return open invoices only
3417 flag, return net invoices only
3421 =item newest_percust
3425 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3429 sub search_sql_where {
3430 my($class, $param) = @_;
3432 warn "$me search_sql_where called with params: \n".
3433 join("\n", map { " $_: ". $param->{$_} } keys %$param ). "\n";
3439 if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3440 push @search, "cust_main.agentnum = $1";
3444 if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3445 push @search, "cust_main.refnum = $1";
3449 if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3450 push @search, "cust_bill.custnum = $1";
3454 if ( $param->{'cust_classnum'} ) {
3455 my $classnums = $param->{'cust_classnum'};
3456 $classnums = [ $classnums ] if !ref($classnums);
3457 $classnums = [ grep /^\d+$/, @$classnums ];
3458 push @search, 'cust_main.classnum in ('.join(',',@$classnums).')'
3463 if ( $param->{_date} ) {
3464 my($beginning, $ending) = @{$param->{_date}};
3466 push @search, "cust_bill._date >= $beginning",
3467 "cust_bill._date < $ending";
3471 if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3472 push @search, "cust_bill.invnum >= $1";
3474 if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3475 push @search, "cust_bill.invnum <= $1";
3479 if ( $param->{charged} ) {
3480 my @charged = ref($param->{charged})
3481 ? @{ $param->{charged} }
3482 : ($param->{charged});
3484 push @search, map { s/^charged/cust_bill.charged/; $_; }
3488 my $owed_sql = FS::cust_bill->owed_sql;
3491 if ( $param->{owed} ) {
3492 my @owed = ref($param->{owed})
3493 ? @{ $param->{owed} }
3495 push @search, map { s/^owed/$owed_sql/; $_; }
3500 push @search, "0 != $owed_sql"
3501 if $param->{'open'};
3502 push @search, '0 != '. FS::cust_bill->net_sql
3506 push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3507 if $param->{'days'};
3510 if ( $param->{'newest_percust'} ) {
3512 #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3513 #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3515 my @newest_where = map { my $x = $_;
3516 $x =~ s/\bcust_bill\./newest_cust_bill./g;
3519 grep ! /^cust_main./, @search;
3520 my $newest_where = scalar(@newest_where)
3521 ? ' AND '. join(' AND ', @newest_where)
3525 push @search, "cust_bill._date = (
3526 SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3527 WHERE newest_cust_bill.custnum = cust_bill.custnum
3533 #promised_date - also has an option to accept nulls
3534 if ( $param->{promised_date} ) {
3535 my($beginning, $ending, $null) = @{$param->{promised_date}};
3537 push @search, "(( cust_bill.promised_date >= $beginning AND ".
3538 "cust_bill.promised_date < $ending )" .
3539 ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3542 #agent virtualization
3543 my $curuser = $FS::CurrentUser::CurrentUser;
3544 if ( $curuser->username eq 'fs_queue'
3545 && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3547 my $newuser = qsearchs('access_user', {
3548 'username' => $username,
3552 $curuser = $newuser;
3554 warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3557 push @search, $curuser->agentnums_sql;
3559 join(' AND ', @search );
3571 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3572 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base