5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6 $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
11 use Scalar::Util qw( blessed );
12 use Time::Local qw(timelocal_nocheck);
15 use Digest::MD5 qw(md5_base64);
19 use File::Slurp qw( slurp );
20 use File::Temp qw( tempfile );
21 use String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
24 use FS::UID qw( getotaker dbh driver_name );
25 use FS::Record qw( qsearchs qsearch dbdef );
26 use FS::Misc qw( generate_email send_email generate_ps do_print );
27 use FS::Msgcat qw(gettext);
31 use FS::cust_bill_pkg;
32 use FS::cust_bill_pkg_display;
34 use FS::cust_pay_pending;
35 use FS::cust_pay_void;
36 use FS::cust_pay_batch;
39 use FS::part_referral;
40 use FS::cust_main_county;
41 use FS::cust_tax_location;
43 use FS::cust_main_invoice;
44 use FS::cust_credit_bill;
45 use FS::cust_bill_pay;
46 use FS::prepay_credit;
50 use FS::part_event_condition;
53 use FS::payment_gateway;
54 use FS::agent_payment_gateway;
56 use FS::payinfo_Mixin;
59 @ISA = qw( FS::payinfo_Mixin FS::Record );
61 @EXPORT_OK = qw( smart_search );
63 $realtime_bop_decline_quiet = 0;
65 # 1 is mostly method/subroutine entry and options
66 # 2 traces progress of some operations
67 # 3 is even more information including possibly sensitive data
69 $me = '[FS::cust_main]';
73 $ignore_expired_card = 0;
75 @encrypted_fields = ('payinfo', 'paycvv');
76 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
78 #ask FS::UID to run this stuff for us later
79 #$FS::UID::callback{'FS::cust_main'} = sub {
80 install_callback FS::UID sub {
82 #yes, need it for stuff below (prolly should be cached)
87 my ( $hashref, $cache ) = @_;
88 if ( exists $hashref->{'pkgnum'} ) {
89 #@{ $self->{'_pkgnum'} } = ();
90 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
91 $self->{'_pkgnum'} = $subcache;
92 #push @{ $self->{'_pkgnum'} },
93 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
99 FS::cust_main - Object methods for cust_main records
105 $record = new FS::cust_main \%hash;
106 $record = new FS::cust_main { 'column' => 'value' };
108 $error = $record->insert;
110 $error = $new_record->replace($old_record);
112 $error = $record->delete;
114 $error = $record->check;
116 @cust_pkg = $record->all_pkgs;
118 @cust_pkg = $record->ncancelled_pkgs;
120 @cust_pkg = $record->suspended_pkgs;
122 $error = $record->bill;
123 $error = $record->bill %options;
124 $error = $record->bill 'time' => $time;
126 $error = $record->collect;
127 $error = $record->collect %options;
128 $error = $record->collect 'invoice_time' => $time,
133 An FS::cust_main object represents a customer. FS::cust_main inherits from
134 FS::Record. The following fields are currently supported:
138 =item custnum - primary key (assigned automatically for new customers)
140 =item agentnum - agent (see L<FS::agent>)
142 =item refnum - Advertising source (see L<FS::part_referral>)
148 =item ss - social security number (optional)
150 =item company - (optional)
154 =item address2 - (optional)
158 =item county - (optional, see L<FS::cust_main_county>)
160 =item state - (see L<FS::cust_main_county>)
164 =item country - (see L<FS::cust_main_county>)
166 =item daytime - phone (optional)
168 =item night - phone (optional)
170 =item fax - phone (optional)
172 =item ship_first - name
174 =item ship_last - name
176 =item ship_company - (optional)
180 =item ship_address2 - (optional)
184 =item ship_county - (optional, see L<FS::cust_main_county>)
186 =item ship_state - (see L<FS::cust_main_county>)
190 =item ship_country - (see L<FS::cust_main_county>)
192 =item ship_daytime - phone (optional)
194 =item ship_night - phone (optional)
196 =item ship_fax - phone (optional)
198 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
200 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
202 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
206 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
208 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
210 =item paystart_month - start date month (maestro/solo cards only)
212 =item paystart_year - start date year (maestro/solo cards only)
214 =item payissue - issue number (maestro/solo cards only)
216 =item payname - name on card or billing name
218 =item payip - IP address from which payment information was received
220 =item tax - tax exempt, empty or `Y'
222 =item otaker - order taker (assigned automatically, see L<FS::UID>)
224 =item comments - comments (optional)
226 =item referral_custnum - referring customer number
228 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
230 =item squelch_cdr - Discourage individual CDR printing, empty or `Y'
240 Creates a new customer. To add the customer to the database, see L<"insert">.
242 Note that this stores the hash reference, not a distinct copy of the hash it
243 points to. You can ask the object for a copy with the I<hash> method.
247 sub table { 'cust_main'; }
249 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
251 Adds this customer to the database. If there is an error, returns the error,
252 otherwise returns false.
254 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
255 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
256 are inserted atomicly, or the transaction is rolled back. Passing an empty
257 hash reference is equivalent to not supplying this parameter. There should be
258 a better explanation of this, but until then, here's an example:
261 tie %hash, 'Tie::RefHash'; #this part is important
263 $cust_pkg => [ $svc_acct ],
266 $cust_main->insert( \%hash );
268 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
269 be set as the invoicing list (see L<"invoicing_list">). Errors return as
270 expected and rollback the entire transaction; it is not necessary to call
271 check_invoicing_list first. The invoicing_list is set after the records in the
272 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
273 invoicing_list destination to the newly-created svc_acct. Here's an example:
275 $cust_main->insert( {}, [ $email, 'POST' ] );
277 Currently available options are: I<depend_jobnum> and I<noexport>.
279 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
280 on the supplied jobnum (they will not run until the specific job completes).
281 This can be used to defer provisioning until some action completes (such
282 as running the customer's credit card successfully).
284 The I<noexport> option is deprecated. If I<noexport> is set true, no
285 provisioning jobs (exports) are scheduled. (You can schedule them later with
286 the B<reexport> method.)
292 my $cust_pkgs = @_ ? shift : {};
293 my $invoicing_list = @_ ? shift : '';
295 warn "$me insert called with options ".
296 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
299 local $SIG{HUP} = 'IGNORE';
300 local $SIG{INT} = 'IGNORE';
301 local $SIG{QUIT} = 'IGNORE';
302 local $SIG{TERM} = 'IGNORE';
303 local $SIG{TSTP} = 'IGNORE';
304 local $SIG{PIPE} = 'IGNORE';
306 my $oldAutoCommit = $FS::UID::AutoCommit;
307 local $FS::UID::AutoCommit = 0;
310 my $prepay_identifier = '';
311 my( $amount, $seconds ) = ( 0, 0 );
313 if ( $self->payby eq 'PREPAY' ) {
315 $self->payby('BILL');
316 $prepay_identifier = $self->payinfo;
319 warn " looking up prepaid card $prepay_identifier\n"
322 my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
324 $dbh->rollback if $oldAutoCommit;
325 #return "error applying prepaid card (transaction rolled back): $error";
329 $payby = 'PREP' if $amount;
331 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
334 $self->payby('BILL');
335 $amount = $self->paid;
339 warn " inserting $self\n"
342 $self->signupdate(time) unless $self->signupdate;
344 my $error = $self->SUPER::insert;
346 $dbh->rollback if $oldAutoCommit;
347 #return "inserting cust_main record (transaction rolled back): $error";
351 warn " setting invoicing list\n"
354 if ( $invoicing_list ) {
355 $error = $self->check_invoicing_list( $invoicing_list );
357 $dbh->rollback if $oldAutoCommit;
358 #return "checking invoicing_list (transaction rolled back): $error";
361 $self->invoicing_list( $invoicing_list );
364 if ( $conf->config('cust_main-skeleton_tables')
365 && $conf->config('cust_main-skeleton_custnum') ) {
367 warn " inserting skeleton records\n"
370 my $error = $self->start_copy_skel;
372 $dbh->rollback if $oldAutoCommit;
378 warn " ordering packages\n"
381 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
383 $dbh->rollback if $oldAutoCommit;
388 $dbh->rollback if $oldAutoCommit;
389 return "No svc_acct record to apply pre-paid time";
393 warn " inserting initial $payby payment of $amount\n"
395 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
397 $dbh->rollback if $oldAutoCommit;
398 return "inserting payment (transaction rolled back): $error";
402 unless ( $import || $skip_fuzzyfiles ) {
403 warn " queueing fuzzyfiles update\n"
405 $error = $self->queue_fuzzyfiles_update;
407 $dbh->rollback if $oldAutoCommit;
408 return "updating fuzzy search cache: $error";
412 warn " insert complete; committing transaction\n"
415 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
420 sub start_copy_skel {
423 #'mg_user_preference' => {},
424 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
425 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
426 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
427 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
428 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
431 _copy_skel( 'cust_main', #tablename
432 $conf->config('cust_main-skeleton_custnum'), #sourceid
433 $self->custnum, #destid
434 @tables, #child tables
438 #recursive subroutine, not a method
440 my( $table, $sourceid, $destid, %child_tables ) = @_;
443 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
444 ( $table, $primary_key ) = ( $1, $2 );
446 my $dbdef_table = dbdef->table($table);
447 $primary_key = $dbdef_table->primary_key
448 or return "$table has no primary key".
449 " (or do you need to run dbdef-create?)";
452 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
453 join (', ', keys %child_tables). "\n"
456 foreach my $child_table_def ( keys %child_tables ) {
460 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
461 ( $child_table, $child_pkey ) = ( $1, $2 );
463 $child_table = $child_table_def;
465 $child_pkey = dbdef->table($child_table)->primary_key;
466 # or return "$table has no primary key".
467 # " (or do you need to run dbdef-create?)\n";
471 if ( keys %{ $child_tables{$child_table_def} } ) {
473 return "$child_table has no primary key".
474 " (run dbdef-create or try specifying it?)\n"
477 #false laziness w/Record::insert and only works on Pg
478 #refactor the proper last-inserted-id stuff out of Record::insert if this
479 # ever gets use for anything besides a quick kludge for one customer
480 my $default = dbdef->table($child_table)->column($child_pkey)->default;
481 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
482 or return "can't parse $child_table.$child_pkey default value ".
483 " for sequence name: $default";
488 my @sel_columns = grep { $_ ne $primary_key }
489 dbdef->table($child_table)->columns;
490 my $sel_columns = join(', ', @sel_columns );
492 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
493 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
494 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
496 my $sel_st = "SELECT $sel_columns FROM $child_table".
497 " WHERE $primary_key = $sourceid";
500 my $sel_sth = dbh->prepare( $sel_st )
501 or return dbh->errstr;
503 $sel_sth->execute or return $sel_sth->errstr;
505 while ( my $row = $sel_sth->fetchrow_hashref ) {
507 warn " selected row: ".
508 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
512 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
513 my $ins_sth =dbh->prepare($statement)
514 or return dbh->errstr;
515 my @param = ( $destid, map $row->{$_}, @ins_columns );
516 warn " $statement: [ ". join(', ', @param). " ]\n"
518 $ins_sth->execute( @param )
519 or return $ins_sth->errstr;
521 #next unless keys %{ $child_tables{$child_table} };
522 next unless $sequence;
524 #another section of that laziness
525 my $seq_sql = "SELECT currval('$sequence')";
526 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
527 $seq_sth->execute or return $seq_sth->errstr;
528 my $insertid = $seq_sth->fetchrow_arrayref->[0];
530 # don't drink soap! recurse! recurse! okay!
532 _copy_skel( $child_table_def,
533 $row->{$child_pkey}, #sourceid
535 %{ $child_tables{$child_table_def} },
537 return $error if $error;
547 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
549 Like the insert method on an existing record, this method orders a package
550 and included services atomicaly. Pass a Tie::RefHash data structure to this
551 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
552 be a better explanation of this, but until then, here's an example:
555 tie %hash, 'Tie::RefHash'; #this part is important
557 $cust_pkg => [ $svc_acct ],
560 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
562 Services can be new, in which case they are inserted, or existing unaudited
563 services, in which case they are linked to the newly-created package.
565 Currently available options are: I<depend_jobnum> and I<noexport>.
567 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
568 on the supplied jobnum (they will not run until the specific job completes).
569 This can be used to defer provisioning until some action completes (such
570 as running the customer's credit card successfully).
572 The I<noexport> option is deprecated. If I<noexport> is set true, no
573 provisioning jobs (exports) are scheduled. (You can schedule them later with
574 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
575 on the cust_main object is not recommended, as existing services will also be
582 my $cust_pkgs = shift;
585 my %svc_options = ();
586 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
587 if exists $options{'depend_jobnum'};
588 warn "$me order_pkgs called with options ".
589 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
592 local $SIG{HUP} = 'IGNORE';
593 local $SIG{INT} = 'IGNORE';
594 local $SIG{QUIT} = 'IGNORE';
595 local $SIG{TERM} = 'IGNORE';
596 local $SIG{TSTP} = 'IGNORE';
597 local $SIG{PIPE} = 'IGNORE';
599 my $oldAutoCommit = $FS::UID::AutoCommit;
600 local $FS::UID::AutoCommit = 0;
603 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
605 foreach my $cust_pkg ( keys %$cust_pkgs ) {
606 $cust_pkg->custnum( $self->custnum );
607 my $error = $cust_pkg->insert;
609 $dbh->rollback if $oldAutoCommit;
610 return "inserting cust_pkg (transaction rolled back): $error";
612 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
613 if ( $svc_something->svcnum ) {
614 my $old_cust_svc = $svc_something->cust_svc;
615 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
616 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
617 $error = $new_cust_svc->replace($old_cust_svc);
619 $svc_something->pkgnum( $cust_pkg->pkgnum );
620 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
621 $svc_something->seconds( $svc_something->seconds + $$seconds );
624 $error = $svc_something->insert(%svc_options);
627 $dbh->rollback if $oldAutoCommit;
628 #return "inserting svc_ (transaction rolled back): $error";
634 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
638 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
640 Recharges this (existing) customer with the specified prepaid card (see
641 L<FS::prepay_credit>), specified either by I<identifier> or as an
642 FS::prepay_credit object. If there is an error, returns the error, otherwise
645 Optionally, four scalar references can be passed as well. They will have their
646 values filled in with the amount, number of seconds, and number of upload and
647 download bytes applied by this prepaid
652 sub recharge_prepay {
653 my( $self, $prepay_credit, $amountref, $secondsref,
654 $upbytesref, $downbytesref, $totalbytesref ) = @_;
656 local $SIG{HUP} = 'IGNORE';
657 local $SIG{INT} = 'IGNORE';
658 local $SIG{QUIT} = 'IGNORE';
659 local $SIG{TERM} = 'IGNORE';
660 local $SIG{TSTP} = 'IGNORE';
661 local $SIG{PIPE} = 'IGNORE';
663 my $oldAutoCommit = $FS::UID::AutoCommit;
664 local $FS::UID::AutoCommit = 0;
667 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
669 my $error = $self->get_prepay($prepay_credit, \$amount,
670 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
671 || $self->increment_seconds($seconds)
672 || $self->increment_upbytes($upbytes)
673 || $self->increment_downbytes($downbytes)
674 || $self->increment_totalbytes($totalbytes)
675 || $self->insert_cust_pay_prepay( $amount,
677 ? $prepay_credit->identifier
682 $dbh->rollback if $oldAutoCommit;
686 if ( defined($amountref) ) { $$amountref = $amount; }
687 if ( defined($secondsref) ) { $$secondsref = $seconds; }
688 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
689 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
690 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
692 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
697 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
699 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
700 specified either by I<identifier> or as an FS::prepay_credit object.
702 References to I<amount> and I<seconds> scalars should be passed as arguments
703 and will be incremented by the values of the prepaid card.
705 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
706 check or set this customer's I<agentnum>.
708 If there is an error, returns the error, otherwise returns false.
714 my( $self, $prepay_credit, $amountref, $secondsref,
715 $upref, $downref, $totalref) = @_;
717 local $SIG{HUP} = 'IGNORE';
718 local $SIG{INT} = 'IGNORE';
719 local $SIG{QUIT} = 'IGNORE';
720 local $SIG{TERM} = 'IGNORE';
721 local $SIG{TSTP} = 'IGNORE';
722 local $SIG{PIPE} = 'IGNORE';
724 my $oldAutoCommit = $FS::UID::AutoCommit;
725 local $FS::UID::AutoCommit = 0;
728 unless ( ref($prepay_credit) ) {
730 my $identifier = $prepay_credit;
732 $prepay_credit = qsearchs(
734 { 'identifier' => $prepay_credit },
739 unless ( $prepay_credit ) {
740 $dbh->rollback if $oldAutoCommit;
741 return "Invalid prepaid card: ". $identifier;
746 if ( $prepay_credit->agentnum ) {
747 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
748 $dbh->rollback if $oldAutoCommit;
749 return "prepaid card not valid for agent ". $self->agentnum;
751 $self->agentnum($prepay_credit->agentnum);
754 my $error = $prepay_credit->delete;
756 $dbh->rollback if $oldAutoCommit;
757 return "removing prepay_credit (transaction rolled back): $error";
760 $$amountref += $prepay_credit->amount;
761 $$secondsref += $prepay_credit->seconds;
762 $$upref += $prepay_credit->upbytes;
763 $$downref += $prepay_credit->downbytes;
764 $$totalref += $prepay_credit->totalbytes;
766 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
771 =item increment_upbytes SECONDS
773 Updates this customer's single or primary account (see L<FS::svc_acct>) by
774 the specified number of upbytes. If there is an error, returns the error,
775 otherwise returns false.
779 sub increment_upbytes {
780 _increment_column( shift, 'upbytes', @_);
783 =item increment_downbytes SECONDS
785 Updates this customer's single or primary account (see L<FS::svc_acct>) by
786 the specified number of downbytes. If there is an error, returns the error,
787 otherwise returns false.
791 sub increment_downbytes {
792 _increment_column( shift, 'downbytes', @_);
795 =item increment_totalbytes SECONDS
797 Updates this customer's single or primary account (see L<FS::svc_acct>) by
798 the specified number of totalbytes. If there is an error, returns the error,
799 otherwise returns false.
803 sub increment_totalbytes {
804 _increment_column( shift, 'totalbytes', @_);
807 =item increment_seconds SECONDS
809 Updates this customer's single or primary account (see L<FS::svc_acct>) by
810 the specified number of seconds. If there is an error, returns the error,
811 otherwise returns false.
815 sub increment_seconds {
816 _increment_column( shift, 'seconds', @_);
819 =item _increment_column AMOUNT
821 Updates this customer's single or primary account (see L<FS::svc_acct>) by
822 the specified number of seconds or bytes. If there is an error, returns
823 the error, otherwise returns false.
827 sub _increment_column {
828 my( $self, $column, $amount ) = @_;
829 warn "$me increment_column called: $column, $amount\n"
832 return '' unless $amount;
834 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
835 $self->ncancelled_pkgs;
838 return 'No packages with primary or single services found'.
839 ' to apply pre-paid time';
840 } elsif ( scalar(@cust_pkg) > 1 ) {
841 #maybe have a way to specify the package/account?
842 return 'Multiple packages found to apply pre-paid time';
845 my $cust_pkg = $cust_pkg[0];
846 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
850 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
853 return 'No account found to apply pre-paid time';
854 } elsif ( scalar(@cust_svc) > 1 ) {
855 return 'Multiple accounts found to apply pre-paid time';
858 my $svc_acct = $cust_svc[0]->svc_x;
859 warn " found service svcnum ". $svc_acct->pkgnum.
860 ' ('. $svc_acct->email. ")\n"
863 $column = "increment_$column";
864 $svc_acct->$column($amount);
868 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
870 Inserts a prepayment in the specified amount for this customer. An optional
871 second argument can specify the prepayment identifier for tracking purposes.
872 If there is an error, returns the error, otherwise returns false.
876 sub insert_cust_pay_prepay {
877 shift->insert_cust_pay('PREP', @_);
880 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
882 Inserts a cash payment in the specified amount for this customer. An optional
883 second argument can specify the payment identifier for tracking purposes.
884 If there is an error, returns the error, otherwise returns false.
888 sub insert_cust_pay_cash {
889 shift->insert_cust_pay('CASH', @_);
892 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
894 Inserts a Western Union payment in the specified amount for this customer. An
895 optional second argument can specify the prepayment identifier for tracking
896 purposes. If there is an error, returns the error, otherwise returns false.
900 sub insert_cust_pay_west {
901 shift->insert_cust_pay('WEST', @_);
904 sub insert_cust_pay {
905 my( $self, $payby, $amount ) = splice(@_, 0, 3);
906 my $payinfo = scalar(@_) ? shift : '';
908 my $cust_pay = new FS::cust_pay {
909 'custnum' => $self->custnum,
910 'paid' => sprintf('%.2f', $amount),
911 #'_date' => #date the prepaid card was purchased???
913 'payinfo' => $payinfo,
921 This method is deprecated. See the I<depend_jobnum> option to the insert and
922 order_pkgs methods for a better way to defer provisioning.
924 Re-schedules all exports by calling the B<reexport> method of all associated
925 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
926 otherwise returns false.
933 carp "WARNING: FS::cust_main::reexport is deprectated; ".
934 "use the depend_jobnum option to insert or order_pkgs to delay export";
936 local $SIG{HUP} = 'IGNORE';
937 local $SIG{INT} = 'IGNORE';
938 local $SIG{QUIT} = 'IGNORE';
939 local $SIG{TERM} = 'IGNORE';
940 local $SIG{TSTP} = 'IGNORE';
941 local $SIG{PIPE} = 'IGNORE';
943 my $oldAutoCommit = $FS::UID::AutoCommit;
944 local $FS::UID::AutoCommit = 0;
947 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
948 my $error = $cust_pkg->reexport;
950 $dbh->rollback if $oldAutoCommit;
955 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
960 =item delete NEW_CUSTNUM
962 This deletes the customer. If there is an error, returns the error, otherwise
965 This will completely remove all traces of the customer record. This is not
966 what you want when a customer cancels service; for that, cancel all of the
967 customer's packages (see L</cancel>).
969 If the customer has any uncancelled packages, you need to pass a new (valid)
970 customer number for those packages to be transferred to. Cancelled packages
971 will be deleted. Did I mention that this is NOT what you want when a customer
972 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
974 You can't delete a customer with invoices (see L<FS::cust_bill>),
975 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
976 refunds (see L<FS::cust_refund>).
983 local $SIG{HUP} = 'IGNORE';
984 local $SIG{INT} = 'IGNORE';
985 local $SIG{QUIT} = 'IGNORE';
986 local $SIG{TERM} = 'IGNORE';
987 local $SIG{TSTP} = 'IGNORE';
988 local $SIG{PIPE} = 'IGNORE';
990 my $oldAutoCommit = $FS::UID::AutoCommit;
991 local $FS::UID::AutoCommit = 0;
994 if ( $self->cust_bill ) {
995 $dbh->rollback if $oldAutoCommit;
996 return "Can't delete a customer with invoices";
998 if ( $self->cust_credit ) {
999 $dbh->rollback if $oldAutoCommit;
1000 return "Can't delete a customer with credits";
1002 if ( $self->cust_pay ) {
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Can't delete a customer with payments";
1006 if ( $self->cust_refund ) {
1007 $dbh->rollback if $oldAutoCommit;
1008 return "Can't delete a customer with refunds";
1011 my @cust_pkg = $self->ncancelled_pkgs;
1013 my $new_custnum = shift;
1014 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1015 $dbh->rollback if $oldAutoCommit;
1016 return "Invalid new customer number: $new_custnum";
1018 foreach my $cust_pkg ( @cust_pkg ) {
1019 my %hash = $cust_pkg->hash;
1020 $hash{'custnum'} = $new_custnum;
1021 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1022 my $error = $new_cust_pkg->replace($cust_pkg,
1023 options => { $cust_pkg->options },
1026 $dbh->rollback if $oldAutoCommit;
1031 my @cancelled_cust_pkg = $self->all_pkgs;
1032 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1033 my $error = $cust_pkg->delete;
1035 $dbh->rollback if $oldAutoCommit;
1040 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1041 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1043 my $error = $cust_main_invoice->delete;
1045 $dbh->rollback if $oldAutoCommit;
1050 my $error = $self->SUPER::delete;
1052 $dbh->rollback if $oldAutoCommit;
1056 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1061 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ]
1063 Replaces the OLD_RECORD with this one in the database. If there is an error,
1064 returns the error, otherwise returns false.
1066 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1067 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1068 expected and rollback the entire transaction; it is not necessary to call
1069 check_invoicing_list first. Here's an example:
1071 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1078 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1080 : $self->replace_old;
1084 warn "$me replace called\n"
1087 my $curuser = $FS::CurrentUser::CurrentUser;
1088 if ( $self->payby eq 'COMP'
1089 && $self->payby ne $old->payby
1090 && ! $curuser->access_right('Complimentary customer')
1093 return "You are not permitted to create complimentary accounts.";
1096 local($ignore_expired_card) = 1
1097 if $old->payby =~ /^(CARD|DCRD)$/
1098 && $self->payby =~ /^(CARD|DCRD)$/
1099 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1101 local $SIG{HUP} = 'IGNORE';
1102 local $SIG{INT} = 'IGNORE';
1103 local $SIG{QUIT} = 'IGNORE';
1104 local $SIG{TERM} = 'IGNORE';
1105 local $SIG{TSTP} = 'IGNORE';
1106 local $SIG{PIPE} = 'IGNORE';
1108 my $oldAutoCommit = $FS::UID::AutoCommit;
1109 local $FS::UID::AutoCommit = 0;
1112 my $error = $self->SUPER::replace($old);
1115 $dbh->rollback if $oldAutoCommit;
1119 if ( @param ) { # INVOICING_LIST_ARYREF
1120 my $invoicing_list = shift @param;
1121 $error = $self->check_invoicing_list( $invoicing_list );
1123 $dbh->rollback if $oldAutoCommit;
1126 $self->invoicing_list( $invoicing_list );
1129 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1130 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1131 # card/check/lec info has changed, want to retry realtime_ invoice events
1132 my $error = $self->retry_realtime;
1134 $dbh->rollback if $oldAutoCommit;
1139 unless ( $import || $skip_fuzzyfiles ) {
1140 $error = $self->queue_fuzzyfiles_update;
1142 $dbh->rollback if $oldAutoCommit;
1143 return "updating fuzzy search cache: $error";
1147 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1152 =item queue_fuzzyfiles_update
1154 Used by insert & replace to update the fuzzy search cache
1158 sub queue_fuzzyfiles_update {
1161 local $SIG{HUP} = 'IGNORE';
1162 local $SIG{INT} = 'IGNORE';
1163 local $SIG{QUIT} = 'IGNORE';
1164 local $SIG{TERM} = 'IGNORE';
1165 local $SIG{TSTP} = 'IGNORE';
1166 local $SIG{PIPE} = 'IGNORE';
1168 my $oldAutoCommit = $FS::UID::AutoCommit;
1169 local $FS::UID::AutoCommit = 0;
1172 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1173 my $error = $queue->insert( map $self->getfield($_),
1174 qw(first last company)
1177 $dbh->rollback if $oldAutoCommit;
1178 return "queueing job (transaction rolled back): $error";
1181 if ( $self->ship_last ) {
1182 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1183 $error = $queue->insert( map $self->getfield("ship_$_"),
1184 qw(first last company)
1187 $dbh->rollback if $oldAutoCommit;
1188 return "queueing job (transaction rolled back): $error";
1192 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1199 Checks all fields to make sure this is a valid customer record. If there is
1200 an error, returns the error, otherwise returns false. Called by the insert
1201 and replace methods.
1208 warn "$me check BEFORE: \n". $self->_dump
1212 $self->ut_numbern('custnum')
1213 || $self->ut_number('agentnum')
1214 || $self->ut_textn('agent_custid')
1215 || $self->ut_number('refnum')
1216 || $self->ut_textn('custbatch')
1217 || $self->ut_name('last')
1218 || $self->ut_name('first')
1219 || $self->ut_snumbern('birthdate')
1220 || $self->ut_snumbern('signupdate')
1221 || $self->ut_textn('company')
1222 || $self->ut_text('address1')
1223 || $self->ut_textn('address2')
1224 || $self->ut_text('city')
1225 || $self->ut_textn('county')
1226 || $self->ut_textn('state')
1227 || $self->ut_country('country')
1228 || $self->ut_anything('comments')
1229 || $self->ut_numbern('referral_custnum')
1230 || $self->ut_textn('stateid')
1231 || $self->ut_textn('stateid_state')
1232 || $self->ut_textn('invoice_terms')
1234 #barf. need message catalogs. i18n. etc.
1235 $error .= "Please select an advertising source."
1236 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1237 return $error if $error;
1239 return "Unknown agent"
1240 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1242 return "Unknown refnum"
1243 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1245 return "Unknown referring custnum: ". $self->referral_custnum
1246 unless ! $self->referral_custnum
1247 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1249 if ( $self->ss eq '' ) {
1254 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1255 or return "Illegal social security number: ". $self->ss;
1256 $self->ss("$1-$2-$3");
1260 # bad idea to disable, causes billing to fail because of no tax rates later
1261 # unless ( $import ) {
1262 unless ( qsearch('cust_main_county', {
1263 'country' => $self->country,
1266 return "Unknown state/county/country: ".
1267 $self->state. "/". $self->county. "/". $self->country
1268 unless qsearch('cust_main_county',{
1269 'state' => $self->state,
1270 'county' => $self->county,
1271 'country' => $self->country,
1277 $self->ut_phonen('daytime', $self->country)
1278 || $self->ut_phonen('night', $self->country)
1279 || $self->ut_phonen('fax', $self->country)
1280 || $self->ut_zip('zip', $self->country)
1282 return $error if $error;
1284 if ( $conf->exists('cust_main-require_phone')
1285 && ! length($self->daytime) && ! length($self->night)
1288 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1290 : FS::Msgcat::_gettext('daytime');
1291 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1293 : FS::Msgcat::_gettext('night');
1295 return "$daytime_label or $night_label is required"
1299 if ( $self->has_ship_address
1300 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1301 $self->addr_fields )
1305 $self->ut_name('ship_last')
1306 || $self->ut_name('ship_first')
1307 || $self->ut_textn('ship_company')
1308 || $self->ut_text('ship_address1')
1309 || $self->ut_textn('ship_address2')
1310 || $self->ut_text('ship_city')
1311 || $self->ut_textn('ship_county')
1312 || $self->ut_textn('ship_state')
1313 || $self->ut_country('ship_country')
1315 return $error if $error;
1317 #false laziness with above
1318 unless ( qsearchs('cust_main_county', {
1319 'country' => $self->ship_country,
1322 return "Unknown ship_state/ship_county/ship_country: ".
1323 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1324 unless qsearch('cust_main_county',{
1325 'state' => $self->ship_state,
1326 'county' => $self->ship_county,
1327 'country' => $self->ship_country,
1333 $self->ut_phonen('ship_daytime', $self->ship_country)
1334 || $self->ut_phonen('ship_night', $self->ship_country)
1335 || $self->ut_phonen('ship_fax', $self->ship_country)
1336 || $self->ut_zip('ship_zip', $self->ship_country)
1338 return $error if $error;
1340 return "Unit # is required."
1341 if $self->ship_address2 =~ /^\s*$/
1342 && $conf->exists('cust_main-require_address2');
1344 } else { # ship_ info eq billing info, so don't store dup info in database
1346 $self->setfield("ship_$_", '')
1347 foreach $self->addr_fields;
1349 return "Unit # is required."
1350 if $self->address2 =~ /^\s*$/
1351 && $conf->exists('cust_main-require_address2');
1355 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1356 # or return "Illegal payby: ". $self->payby;
1358 FS::payby->can_payby($self->table, $self->payby)
1359 or return "Illegal payby: ". $self->payby;
1361 $error = $self->ut_numbern('paystart_month')
1362 || $self->ut_numbern('paystart_year')
1363 || $self->ut_numbern('payissue')
1364 || $self->ut_textn('paytype')
1366 return $error if $error;
1368 if ( $self->payip eq '' ) {
1371 $error = $self->ut_ip('payip');
1372 return $error if $error;
1375 # If it is encrypted and the private key is not availaible then we can't
1376 # check the credit card.
1378 my $check_payinfo = 1;
1380 if ($self->is_encrypted($self->payinfo)) {
1384 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1386 my $payinfo = $self->payinfo;
1387 $payinfo =~ s/\D//g;
1388 $payinfo =~ /^(\d{13,16})$/
1389 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1391 $self->payinfo($payinfo);
1393 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1395 return gettext('unknown_card_type')
1396 if cardtype($self->payinfo) eq "Unknown";
1398 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1400 return 'Banned credit card: banned on '.
1401 time2str('%a %h %o at %r', $ban->_date).
1402 ' by '. $ban->otaker.
1403 ' (ban# '. $ban->bannum. ')';
1406 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1407 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1408 $self->paycvv =~ /^(\d{4})$/
1409 or return "CVV2 (CID) for American Express cards is four digits.";
1412 $self->paycvv =~ /^(\d{3})$/
1413 or return "CVV2 (CVC2/CID) is three digits.";
1420 my $cardtype = cardtype($payinfo);
1421 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1423 return "Start date or issue number is required for $cardtype cards"
1424 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1426 return "Start month must be between 1 and 12"
1427 if $self->paystart_month
1428 and $self->paystart_month < 1 || $self->paystart_month > 12;
1430 return "Start year must be 1990 or later"
1431 if $self->paystart_year
1432 and $self->paystart_year < 1990;
1434 return "Issue number must be beween 1 and 99"
1436 and $self->payissue < 1 || $self->payissue > 99;
1439 $self->paystart_month('');
1440 $self->paystart_year('');
1441 $self->payissue('');
1444 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1446 my $payinfo = $self->payinfo;
1447 $payinfo =~ s/[^\d\@]//g;
1448 if ( $conf->exists('echeck-nonus') ) {
1449 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1450 $payinfo = "$1\@$2";
1452 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1453 $payinfo = "$1\@$2";
1455 $self->payinfo($payinfo);
1458 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1460 return 'Banned ACH account: banned on '.
1461 time2str('%a %h %o at %r', $ban->_date).
1462 ' by '. $ban->otaker.
1463 ' (ban# '. $ban->bannum. ')';
1466 } elsif ( $self->payby eq 'LECB' ) {
1468 my $payinfo = $self->payinfo;
1469 $payinfo =~ s/\D//g;
1470 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1472 $self->payinfo($payinfo);
1475 } elsif ( $self->payby eq 'BILL' ) {
1477 $error = $self->ut_textn('payinfo');
1478 return "Illegal P.O. number: ". $self->payinfo if $error;
1481 } elsif ( $self->payby eq 'COMP' ) {
1483 my $curuser = $FS::CurrentUser::CurrentUser;
1484 if ( ! $self->custnum
1485 && ! $curuser->access_right('Complimentary customer')
1488 return "You are not permitted to create complimentary accounts."
1491 $error = $self->ut_textn('payinfo');
1492 return "Illegal comp account issuer: ". $self->payinfo if $error;
1495 } elsif ( $self->payby eq 'PREPAY' ) {
1497 my $payinfo = $self->payinfo;
1498 $payinfo =~ s/\W//g; #anything else would just confuse things
1499 $self->payinfo($payinfo);
1500 $error = $self->ut_alpha('payinfo');
1501 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1502 return "Unknown prepayment identifier"
1503 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1508 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1509 return "Expiration date required"
1510 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1514 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1515 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1516 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1517 ( $m, $y ) = ( $3, "20$2" );
1519 return "Illegal expiration date: ". $self->paydate;
1521 $self->paydate("$y-$m-01");
1522 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1523 return gettext('expired_card')
1525 && !$ignore_expired_card
1526 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1529 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1530 ( ! $conf->exists('require_cardname')
1531 || $self->payby !~ /^(CARD|DCRD)$/ )
1533 $self->payname( $self->first. " ". $self->getfield('last') );
1535 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1536 or return gettext('illegal_name'). " payname: ". $self->payname;
1540 foreach my $flag (qw( tax spool_cdr squelch_cdr )) {
1541 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1545 $self->otaker(getotaker) unless $self->otaker;
1547 warn "$me check AFTER: \n". $self->_dump
1550 $self->SUPER::check;
1555 Returns a list of fields which have ship_ duplicates.
1560 qw( last first company
1561 address1 address2 city county state zip country
1566 =item has_ship_address
1568 Returns true if this customer record has a separate shipping address.
1572 sub has_ship_address {
1574 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1579 Returns all packages (see L<FS::cust_pkg>) for this customer.
1586 return $self->num_pkgs unless wantarray;
1589 if ( $self->{'_pkgnum'} ) {
1590 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1592 @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1595 sort sort_packages @cust_pkg;
1600 Synonym for B<all_pkgs>.
1605 shift->all_pkgs(@_);
1608 =item ncancelled_pkgs
1610 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1614 sub ncancelled_pkgs {
1617 return $self->num_ncancelled_pkgs unless wantarray;
1620 if ( $self->{'_pkgnum'} ) {
1622 warn "$me ncancelled_pkgs: returning cached objects"
1625 @cust_pkg = grep { ! $_->getfield('cancel') }
1626 values %{ $self->{'_pkgnum'}->cache };
1630 warn "$me ncancelled_pkgs: searching for packages with custnum ".
1631 $self->custnum. "\n"
1635 qsearch( 'cust_pkg', {
1636 'custnum' => $self->custnum,
1640 qsearch( 'cust_pkg', {
1641 'custnum' => $self->custnum,
1646 sort sort_packages @cust_pkg;
1650 # This should be generalized to use config options to determine order.
1652 if ( $a->get('cancel') and $b->get('cancel') ) {
1653 $a->pkgnum <=> $b->pkgnum;
1654 } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1655 return -1 if $b->get('cancel');
1656 return 1 if $a->get('cancel');
1659 $a->pkgnum <=> $b->pkgnum;
1663 =item suspended_pkgs
1665 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1669 sub suspended_pkgs {
1671 grep { $_->susp } $self->ncancelled_pkgs;
1674 =item unflagged_suspended_pkgs
1676 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1677 customer (thouse packages without the `manual_flag' set).
1681 sub unflagged_suspended_pkgs {
1683 return $self->suspended_pkgs
1684 unless dbdef->table('cust_pkg')->column('manual_flag');
1685 grep { ! $_->manual_flag } $self->suspended_pkgs;
1688 =item unsuspended_pkgs
1690 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1695 sub unsuspended_pkgs {
1697 grep { ! $_->susp } $self->ncancelled_pkgs;
1700 =item num_cancelled_pkgs
1702 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1707 sub num_cancelled_pkgs {
1708 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1711 sub num_ncancelled_pkgs {
1712 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1716 my( $self ) = shift;
1717 my $sql = scalar(@_) ? shift : '';
1718 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1719 my $sth = dbh->prepare(
1720 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1721 ) or die dbh->errstr;
1722 $sth->execute($self->custnum) or die $sth->errstr;
1723 $sth->fetchrow_arrayref->[0];
1728 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1729 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1730 on success or a list of errors.
1736 grep { $_->unsuspend } $self->suspended_pkgs;
1741 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1743 Returns a list: an empty list on success or a list of errors.
1749 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1752 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1754 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1755 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
1756 of a list of pkgparts; the hashref has the following keys:
1760 =item pkgparts - listref of pkgparts
1762 =item (other options are passed to the suspend method)
1767 Returns a list: an empty list on success or a list of errors.
1771 sub suspend_if_pkgpart {
1773 my (@pkgparts, %opt);
1774 if (ref($_[0]) eq 'HASH'){
1775 @pkgparts = @{$_[0]{pkgparts}};
1780 grep { $_->suspend(%opt) }
1781 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1782 $self->unsuspended_pkgs;
1785 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1787 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1788 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
1789 instead of a list of pkgparts; the hashref has the following keys:
1793 =item pkgparts - listref of pkgparts
1795 =item (other options are passed to the suspend method)
1799 Returns a list: an empty list on success or a list of errors.
1803 sub suspend_unless_pkgpart {
1805 my (@pkgparts, %opt);
1806 if (ref($_[0]) eq 'HASH'){
1807 @pkgparts = @{$_[0]{pkgparts}};
1812 grep { $_->suspend(%opt) }
1813 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1814 $self->unsuspended_pkgs;
1817 =item cancel [ OPTION => VALUE ... ]
1819 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1821 Available options are:
1825 =item quiet - can be set true to supress email cancellation notices.
1827 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
1829 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1833 Always returns a list: an empty list on success or a list of errors.
1838 my( $self, %opt ) = @_;
1840 warn "$me cancel called on customer ". $self->custnum. " with options ".
1841 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1844 return ( 'access denied' )
1845 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1847 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1849 #should try decryption (we might have the private key)
1850 # and if not maybe queue a job for the server that does?
1851 return ( "Can't (yet) ban encrypted credit cards" )
1852 if $self->is_encrypted($self->payinfo);
1854 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1855 my $error = $ban->insert;
1856 return ( $error ) if $error;
1860 my @pkgs = $self->ncancelled_pkgs;
1862 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1863 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1866 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1869 sub _banned_pay_hashref {
1880 'payby' => $payby2ban{$self->payby},
1881 'payinfo' => md5_base64($self->payinfo),
1882 #don't ever *search* on reason! #'reason' =>
1888 Returns all notes (see L<FS::cust_main_note>) for this customer.
1895 qsearch( 'cust_main_note',
1896 { 'custnum' => $self->custnum },
1898 'ORDER BY _DATE DESC'
1904 Returns the agent (see L<FS::agent>) for this customer.
1910 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1913 =item bill_and_collect
1915 Cancels and suspends any packages due, generates bills, applies payments and
1918 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1920 Options are passed as name-value pairs. Currently available options are:
1926 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
1930 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1934 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
1938 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1942 If set true, re-charges setup fees.
1946 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1952 sub bill_and_collect {
1953 my( $self, %options ) = @_;
1959 #$options{actual_time} not $options{time} because freeside-daily -d is for
1960 #pre-printing invoices
1961 my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
1962 $self->ncancelled_pkgs;
1964 foreach my $cust_pkg ( @cancel_pkgs ) {
1965 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
1966 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
1967 'reason_otaker' => $cpr->otaker
1971 warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1972 " for custnum ". $self->custnum. ": $error"
1980 #$options{actual_time} not $options{time} because freeside-daily -d is for
1981 #pre-printing invoices
1984 && ( ( $_->part_pkg->is_prepaid
1986 && $_->bill < $options{actual_time}
1989 && $_->adjourn <= $options{actual_time}
1993 $self->ncancelled_pkgs;
1995 foreach my $cust_pkg ( @susp_pkgs ) {
1996 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
1997 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
1998 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
1999 'reason_otaker' => $cpr->otaker
2004 warn "Error suspending package ". $cust_pkg->pkgnum.
2005 " for custnum ". $self->custnum. ": $error"
2013 my $error = $self->bill( %options );
2014 warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
2016 $self->apply_payments_and_credits;
2018 $error = $self->collect( %options );
2019 warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2025 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
2026 conjunction with the collect method by calling B<bill_and_collect>.
2028 If there is an error, returns the error, otherwise returns false.
2030 Options are passed as name-value pairs. Currently available options are:
2036 If set true, re-charges setup fees.
2040 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
2044 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2048 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2050 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2054 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
2061 my( $self, %options ) = @_;
2062 return '' if $self->payby eq 'COMP';
2063 warn "$me bill customer ". $self->custnum. "\n"
2066 my $time = $options{'time'} || time;
2069 local $SIG{HUP} = 'IGNORE';
2070 local $SIG{INT} = 'IGNORE';
2071 local $SIG{QUIT} = 'IGNORE';
2072 local $SIG{TERM} = 'IGNORE';
2073 local $SIG{TSTP} = 'IGNORE';
2074 local $SIG{PIPE} = 'IGNORE';
2076 my $oldAutoCommit = $FS::UID::AutoCommit;
2077 local $FS::UID::AutoCommit = 0;
2080 $self->select_for_update; #mutex
2082 my @cust_bill_pkg = ();
2085 # find the packages which are due for billing, find out how much they are
2086 # & generate invoice database.
2089 my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2093 my @precommit_hooks = ();
2095 my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2096 foreach my $cust_pkg (@cust_pkgs) {
2098 #NO!! next if $cust_pkg->cancel;
2099 next if $cust_pkg->getfield('cancel');
2101 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2103 #? to avoid use of uninitialized value errors... ?
2104 $cust_pkg->setfield('bill', '')
2105 unless defined($cust_pkg->bill);
2107 #my $part_pkg = $cust_pkg->part_pkg;
2109 my $real_pkgpart = $cust_pkg->pkgpart;
2110 my %hash = $cust_pkg->hash;
2112 foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2114 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2117 $self->_make_lines( 'part_pkg' => $part_pkg,
2118 'cust_pkg' => $cust_pkg,
2119 'precommit_hooks' => \@precommit_hooks,
2120 'line_items' => \@cust_bill_pkg,
2121 'setup' => \$total_setup,
2122 'recur' => \$total_recur,
2123 'tax_matrix' => \%taxlisthash,
2125 'options' => \%options,
2128 $dbh->rollback if $oldAutoCommit;
2132 } #foreach my $part_pkg
2134 } #foreach my $cust_pkg
2136 unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2137 #but do commit any package date cycling that happened
2138 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2142 my $postal_pkg = $self->charge_postal_fee();
2143 if ( $postal_pkg && !ref( $postal_pkg ) ) {
2144 $dbh->rollback if $oldAutoCommit;
2145 return "can't charge postal invoice fee for customer ".
2146 $self->custnum. ": $postal_pkg";
2148 if ( $postal_pkg ) {
2149 foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2151 $self->_make_lines( 'part_pkg' => $part_pkg,
2152 'cust_pkg' => $postal_pkg,
2153 'precommit_hooks' => \@precommit_hooks,
2154 'line_items' => \@cust_bill_pkg,
2155 'setup' => \$total_setup,
2156 'recur' => \$total_recur,
2157 'tax_matrix' => \%taxlisthash,
2159 'options' => \%options,
2162 $dbh->rollback if $oldAutoCommit;
2168 warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2169 foreach my $tax ( keys %taxlisthash ) {
2170 my $tax_object = shift @{ $taxlisthash{$tax} };
2171 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2172 my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2173 unless (ref($listref_or_error)) {
2174 $dbh->rollback if $oldAutoCommit;
2175 return $listref_or_error;
2177 unshift @{ $taxlisthash{$tax} }, $tax_object;
2179 warn "adding ". $listref_or_error->[1].
2180 " as ". $listref_or_error->[0]. "\n"
2182 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2183 if ( $taxname{ $listref_or_error->[0] } ) {
2184 push @{ $taxname{ $listref_or_error->[0] } }, $tax_object->taxname;
2186 $taxname{ $listref_or_error->[0] } = [ $tax_object->taxname ];
2191 #some taxes are taxed
2194 warn "finding taxed taxes...\n" if $DEBUG > 2;
2195 foreach my $tax ( keys %taxlisthash ) {
2196 my $tax_object = shift @{ $taxlisthash{$tax} };
2197 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2199 next unless $tax_object->can('tax_on_tax');
2201 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2202 my $totname = ref( $tot ). ' '. $tot->taxnum;
2204 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2206 next unless exists( $taxlisthash{ $totname } ); # only increase
2208 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2209 if ( exists( $totlisthash{ $totname } ) ) {
2210 push @{ $totlisthash{ $totname } }, $tax{ $tax_object->taxname };
2212 $totlisthash{ $totname } = [ $tot, $tax{ $tax_object->taxname } ];
2217 warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2218 foreach my $tax ( keys %totlisthash ) {
2219 my $tax_object = shift @{ $totlisthash{$tax} };
2220 warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2222 my $listref_or_error = $tax_object->taxline( @{ $totlisthash{$tax} } );
2223 unless (ref($listref_or_error)) {
2224 $dbh->rollback if $oldAutoCommit;
2225 return $listref_or_error;
2228 warn "adding taxed tax amount ". $listref_or_error->[1].
2229 " as ". $tax_object->taxname. "\n"
2231 $tax{ $tax_object->taxname } += $listref_or_error->[1];
2234 #consolidate and create tax line items
2235 warn "consolidating and generating...\n" if $DEBUG > 2;
2236 foreach my $taxname ( keys %taxname ) {
2239 warn "adding $taxname\n" if $DEBUG > 1;
2240 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2241 $tax += $tax{$taxitem} unless $seen{$taxitem};
2242 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2246 $tax = sprintf('%.2f', $tax );
2247 $total_setup = sprintf('%.2f', $total_setup+$tax );
2249 push @cust_bill_pkg, new FS::cust_bill_pkg {
2255 'itemdesc' => $taxname,
2260 my $charged = sprintf('%.2f', $total_setup + $total_recur );
2262 #create the new invoice
2263 my $cust_bill = new FS::cust_bill ( {
2264 'custnum' => $self->custnum,
2265 '_date' => ( $options{'invoice_time'} || $time ),
2266 'charged' => $charged,
2268 my $error = $cust_bill->insert;
2270 $dbh->rollback if $oldAutoCommit;
2271 return "can't create invoice for customer #". $self->custnum. ": $error";
2274 foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2275 $cust_bill_pkg->invnum($cust_bill->invnum);
2276 my $error = $cust_bill_pkg->insert;
2278 $dbh->rollback if $oldAutoCommit;
2279 return "can't create invoice line item: $error";
2284 foreach my $hook ( @precommit_hooks ) {
2286 &{$hook}; #($self) ?
2289 $dbh->rollback if $oldAutoCommit;
2290 return "$@ running precommit hook $hook\n";
2294 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2300 my ($self, %params) = @_;
2302 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2303 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2304 my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2305 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2306 my $total_setup = $params{setup} or die "no setup accumulator specified";
2307 my $total_recur = $params{recur} or die "no recur accumulator specified";
2308 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2309 my $time = $params{'time'} or die "no time specified";
2310 my (%options) = %{$params{options}}; #hmmm only for 'resetup'
2313 my $real_pkgpart = $cust_pkg->pkgpart;
2314 my %hash = $cust_pkg->hash;
2315 my $old_cust_pkg = new FS::cust_pkg \%hash;
2321 $cust_pkg->pkgpart($part_pkg->pkgpart);
2329 if ( ! $cust_pkg->setup &&
2331 ( $conf->exists('disable_setup_suspended_pkgs') &&
2332 ! $cust_pkg->getfield('susp')
2333 ) || ! $conf->exists('disable_setup_suspended_pkgs')
2335 || $options{'resetup'}
2338 warn " bill setup\n" if $DEBUG > 1;
2341 $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2342 return "$@ running calc_setup for $cust_pkg\n"
2345 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2347 $cust_pkg->setfield('setup', $time)
2348 unless $cust_pkg->setup;
2349 #do need it, but it won't get written to the db
2350 #|| $cust_pkg->pkgpart != $real_pkgpart;
2355 # bill recurring fee
2358 #XXX unit stuff here too
2362 if ( $part_pkg->getfield('freq') ne '0' &&
2363 ! $cust_pkg->getfield('susp') &&
2364 ( $cust_pkg->getfield('bill') || 0 ) <= $time
2367 # XXX should this be a package event? probably. events are called
2368 # at collection time at the moment, though...
2369 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2370 if $part_pkg->can('reset_usage');
2371 #don't want to reset usage just cause we want a line item??
2372 #&& $part_pkg->pkgpart == $real_pkgpart;
2374 warn " bill recur\n" if $DEBUG > 1;
2377 # XXX shared with $recur_prog
2378 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2380 #over two params! lets at least switch to a hashref for the rest...
2381 my %param = ( 'precommit_hooks' => $precommit_hooks, );
2383 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2384 return "$@ running calc_recur for $cust_pkg\n"
2388 #change this bit to use Date::Manip? CAREFUL with timezones (see
2389 # mailing list archive)
2390 my ($sec,$min,$hour,$mday,$mon,$year) =
2391 (localtime($sdate) )[0,1,2,3,4,5];
2393 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2394 # only for figuring next bill date, nothing else, so, reset $sdate again
2396 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2397 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
2398 $cust_pkg->last_bill($sdate);
2400 if ( $part_pkg->freq =~ /^\d+$/ ) {
2401 $mon += $part_pkg->freq;
2402 until ( $mon < 12 ) { $mon -= 12; $year++; }
2403 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2405 $mday += $weeks * 7;
2406 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2409 } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2413 return "unparsable frequency: ". $part_pkg->freq;
2415 $cust_pkg->setfield('bill',
2416 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2420 warn "\$setup is undefined" unless defined($setup);
2421 warn "\$recur is undefined" unless defined($recur);
2422 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2425 # If there's line items, create em cust_bill_pkg records
2426 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2431 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2432 # hmm.. and if just the options are modified in some weird price plan?
2434 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
2437 my $error = $cust_pkg->replace( $old_cust_pkg,
2438 'options' => { $cust_pkg->options },
2440 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2441 if $error; #just in case
2444 $setup = sprintf( "%.2f", $setup );
2445 $recur = sprintf( "%.2f", $recur );
2446 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2447 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2449 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2450 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2453 if ( $setup != 0 || $recur != 0 ) {
2455 warn " charges (setup=$setup, recur=$recur); adding line items\n"
2458 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
2460 warn " adding customer package invoice detail: $_\n"
2461 foreach @cust_pkg_detail;
2463 push @details, @cust_pkg_detail;
2465 my $cust_bill_pkg = new FS::cust_bill_pkg {
2466 'pkgnum' => $cust_pkg->pkgnum,
2468 'unitsetup' => $unitsetup,
2470 'unitrecur' => $unitrecur,
2471 'quantity' => $cust_pkg->quantity,
2472 'details' => \@details,
2475 if ( $part_pkg->option('recur_temporality', 1) eq 'preceding' ) {
2476 $cust_bill_pkg->sdate( $hash{last_bill} );
2477 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
2478 } else { #if ( $part_pkg->option('recur_temporality', 1) eq 'upcoming' ) {
2479 $cust_bill_pkg->sdate( $sdate );
2480 $cust_bill_pkg->edate( $cust_pkg->bill );
2483 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2484 unless $part_pkg->pkgpart == $real_pkgpart;
2486 $$total_setup += $setup;
2487 $$total_recur += $recur;
2494 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg);
2495 return $error if $error;
2497 push @$cust_bill_pkgs, $cust_bill_pkg;
2499 } #if $setup != 0 || $recur != 0
2509 my $part_pkg = shift;
2510 my $taxlisthash = shift;
2511 my $cust_bill_pkg = shift;
2512 my $cust_pkg = shift;
2514 my %cust_bill_pkg = ();
2518 ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2523 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
2524 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
2525 push @classes, 'setup' if $cust_bill_pkg->setup;
2526 push @classes, 'recur' if $cust_bill_pkg->recur;
2528 if ( $conf->exists('enable_taxproducts')
2529 && (scalar($part_pkg->part_pkg_taxoverride) || $part_pkg->has_taxproduct)
2530 && ( $self->tax !~ /Y/i && $self->payby ne 'COMP' )
2534 foreach my $class (@classes) {
2535 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $prefix );
2536 return $err_or_ref unless ref($err_or_ref);
2537 $taxes{$class} = $err_or_ref;
2540 unless (exists $taxes{''}) {
2541 my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $prefix );
2542 return $err_or_ref unless ref($err_or_ref);
2543 $taxes{''} = $err_or_ref;
2546 } elsif ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
2548 my %taxhash = map { $_ => $self->get("$prefix$_") }
2549 qw( state county country );
2551 $taxhash{'taxclass'} = $part_pkg->taxclass;
2553 my @taxes = qsearch( 'cust_main_county', \%taxhash );
2556 $taxhash{'taxclass'} = '';
2557 @taxes = qsearch( 'cust_main_county', \%taxhash );
2560 #one more try at a whole-country tax rate
2562 $taxhash{$_} = '' foreach qw( state county );
2563 @taxes = qsearch( 'cust_main_county', \%taxhash );
2566 $taxes{''} = [ @taxes ];
2567 $taxes{'setup'} = [ @taxes ];
2568 $taxes{'recur'} = [ @taxes ];
2569 $taxes{$_} = [ @taxes ] foreach (@classes);
2571 # maybe eliminate this entirely, along with all the 0% records
2574 "fatal: can't find tax rate for state/county/country/taxclass ".
2575 join('/', ( map $self->get("$prefix$_"),
2576 qw(state county country)
2578 $part_pkg->taxclass ). "\n";
2581 } #if $conf->exists('enable_taxproducts') ...
2584 if ( $conf->exists('separate_usage') ) {
2585 my $section = $cust_pkg->part_pkg->option('usage_section', 'Hush!');
2586 my $summary = $cust_pkg->part_pkg->option('summarize_usage', 'Hush!');
2587 push @display, new FS::cust_bill_pkg_display { type => 'S' };
2588 push @display, new FS::cust_bill_pkg_display { type => 'R' };
2589 push @display, new FS::cust_bill_pkg_display { type => 'U',
2592 if ($section && $summary) {
2593 $display[2]->post_total('Y');
2594 push @display, new FS::cust_bill_pkg_display { type => 'U',
2599 $cust_bill_pkg->set('display', \@display);
2601 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
2602 foreach my $key (keys %tax_cust_bill_pkg) {
2603 my @taxes = @{ $taxes{$key} };
2604 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
2606 foreach my $tax ( @taxes ) {
2607 my $taxname = ref( $tax ). ' '. $tax->taxnum;
2608 if ( exists( $taxlisthash->{ $taxname } ) ) {
2609 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
2611 $taxlisthash->{ $taxname } = [ $tax, $tax_cust_bill_pkg ];
2621 my $part_pkg = shift;
2626 my $geocode = $self->geocode('cch');
2628 my @taxclassnums = map { $_->taxclassnum }
2629 $part_pkg->part_pkg_taxoverride($class);
2631 unless (@taxclassnums) {
2632 @taxclassnums = map { $_->taxclassnum }
2633 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
2635 warn "Found taxclassnum values of ". join(',', @taxclassnums)
2640 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2642 @taxes = qsearch({ 'table' => 'tax_rate',
2643 'hashref' => { 'geocode' => $geocode, },
2644 'extra_sql' => $extra_sql,
2646 if scalar(@taxclassnums);
2648 # maybe eliminate this entirely, along with all the 0% records
2651 "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2652 join('/', ( map $self->get("$prefix$_"),
2655 $part_pkg->taxproduct_description,
2656 $part_pkg->pkgpart ). "\n";
2659 warn "Found taxes ".
2660 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
2667 =item collect OPTIONS
2669 (Attempt to) collect money for this customer's outstanding invoices (see
2670 L<FS::cust_bill>). Usually used after the bill method.
2672 Actions are now triggered by billing events; see L<FS::part_event> and the
2673 billing events web interface. Old-style invoice events (see
2674 L<FS::part_bill_event>) have been deprecated.
2676 If there is an error, returns the error, otherwise returns false.
2678 Options are passed as name-value pairs.
2680 Currently available options are:
2686 Use this time when deciding when to print invoices and late notices on those invoices. The default is now. It is specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions.
2690 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2694 set true to surpress email card/ACH decline notices.
2698 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2702 allows for one time override of normal customer billing method
2706 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2714 my( $self, %options ) = @_;
2715 my $invoice_time = $options{'invoice_time'} || time;
2718 local $SIG{HUP} = 'IGNORE';
2719 local $SIG{INT} = 'IGNORE';
2720 local $SIG{QUIT} = 'IGNORE';
2721 local $SIG{TERM} = 'IGNORE';
2722 local $SIG{TSTP} = 'IGNORE';
2723 local $SIG{PIPE} = 'IGNORE';
2725 my $oldAutoCommit = $FS::UID::AutoCommit;
2726 local $FS::UID::AutoCommit = 0;
2729 $self->select_for_update; #mutex
2732 my $balance = $self->balance;
2733 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2736 if ( exists($options{'retry_card'}) ) {
2737 carp 'retry_card option passed to collect is deprecated; use retry';
2738 $options{'retry'} ||= $options{'retry_card'};
2740 if ( exists($options{'retry'}) && $options{'retry'} ) {
2741 my $error = $self->retry_realtime;
2743 $dbh->rollback if $oldAutoCommit;
2748 # false laziness w/pay_batch::import_results
2750 my $due_cust_event = $self->due_cust_event(
2751 'debug' => ( $options{'debug'} || 0 ),
2752 'time' => $invoice_time,
2753 'check_freq' => $options{'check_freq'},
2755 unless( ref($due_cust_event) ) {
2756 $dbh->rollback if $oldAutoCommit;
2757 return $due_cust_event;
2760 foreach my $cust_event ( @$due_cust_event ) {
2764 #re-eval event conditions (a previous event could have changed things)
2765 unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2766 #don't leave stray "new/locked" records around
2767 my $error = $cust_event->delete;
2769 #gah, even with transactions
2770 $dbh->commit if $oldAutoCommit; #well.
2777 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2778 warn " running cust_event ". $cust_event->eventnum. "\n"
2782 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2783 if ( my $error = $cust_event->do_event() ) {
2784 #XXX wtf is this? figure out a proper dealio with return value
2786 # gah, even with transactions.
2787 $dbh->commit if $oldAutoCommit; #well.
2794 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2799 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2801 Inserts database records for and returns an ordered listref of new events due
2802 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2803 events are due, an empty listref is returned. If there is an error, returns a
2804 scalar error message.
2806 To actually run the events, call each event's test_condition method, and if
2807 still true, call the event's do_event method.
2809 Options are passed as a hashref or as a list of name-value pairs. Available
2816 Search only for events of this check frequency (how often events of this type are checked); currently "1d" (daily, the default) and "1m" (monthly) are recognized.
2820 "Current time" for the events.
2824 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2828 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2832 Explicitly pass the objects to be tested (typically used with eventtable).
2838 sub due_cust_event {
2840 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2843 #my $DEBUG = $opt{'debug'}
2844 local($DEBUG) = $opt{'debug'}
2845 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2847 warn "$me due_cust_event called with options ".
2848 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2851 $opt{'time'} ||= time;
2853 local $SIG{HUP} = 'IGNORE';
2854 local $SIG{INT} = 'IGNORE';
2855 local $SIG{QUIT} = 'IGNORE';
2856 local $SIG{TERM} = 'IGNORE';
2857 local $SIG{TSTP} = 'IGNORE';
2858 local $SIG{PIPE} = 'IGNORE';
2860 my $oldAutoCommit = $FS::UID::AutoCommit;
2861 local $FS::UID::AutoCommit = 0;
2864 $self->select_for_update; #mutex
2867 # 1: find possible events (initial search)
2870 my @cust_event = ();
2872 my @eventtable = $opt{'eventtable'}
2873 ? ( $opt{'eventtable'} )
2874 : FS::part_event->eventtables_runorder;
2876 foreach my $eventtable ( @eventtable ) {
2879 if ( $opt{'objects'} ) {
2881 @objects = @{ $opt{'objects'} };
2885 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2886 @objects = ( $eventtable eq 'cust_main' )
2888 : ( $self->$eventtable() );
2892 my @e_cust_event = ();
2894 my $cross = "CROSS JOIN $eventtable";
2895 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2896 unless $eventtable eq 'cust_main';
2898 foreach my $object ( @objects ) {
2900 #this first search uses the condition_sql magic for optimization.
2901 #the more possible events we can eliminate in this step the better
2903 my $cross_where = '';
2904 my $pkey = $object->primary_key;
2905 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2907 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2909 FS::part_event_condition->where_conditions_sql( $eventtable,
2910 'time'=>$opt{'time'}
2912 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2914 $extra_sql = "AND $extra_sql" if $extra_sql;
2916 #here is the agent virtualization
2917 $extra_sql .= " AND ( part_event.agentnum IS NULL
2918 OR part_event.agentnum = ". $self->agentnum. ' )';
2920 $extra_sql .= " $order";
2922 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2923 if $opt{'debug'} > 2;
2924 my @part_event = qsearch( {
2925 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2926 'select' => 'part_event.*',
2927 'table' => 'part_event',
2928 'addl_from' => "$cross $join",
2929 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2930 'eventtable' => $eventtable,
2933 'extra_sql' => "AND $cross_where $extra_sql",
2937 my $pkey = $object->primary_key;
2938 warn " ". scalar(@part_event).
2939 " possible events found for $eventtable ". $object->$pkey(). "\n";
2942 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2946 warn " ". scalar(@e_cust_event).
2947 " subtotal possible cust events found for $eventtable\n"
2950 push @cust_event, @e_cust_event;
2954 warn " ". scalar(@cust_event).
2955 " total possible cust events found in initial search\n"
2959 # 2: test conditions
2964 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
2965 'stats_hashref' => \%unsat ),
2968 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
2971 warn " invalid conditions not eliminated with condition_sql:\n".
2972 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
2979 foreach my $cust_event ( @cust_event ) {
2981 my $error = $cust_event->insert();
2983 $dbh->rollback if $oldAutoCommit;
2989 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2995 warn " returning events: ". Dumper(@cust_event). "\n"
3002 =item retry_realtime
3004 Schedules realtime / batch credit card / electronic check / LEC billing
3005 events for for retry. Useful if card information has changed or manual
3006 retry is desired. The 'collect' method must be called to actually retry
3009 Implementation details: For either this customer, or for each of this
3010 customer's open invoices, changes the status of the first "done" (with
3011 statustext error) realtime processing event to "failed".
3015 sub retry_realtime {
3018 local $SIG{HUP} = 'IGNORE';
3019 local $SIG{INT} = 'IGNORE';
3020 local $SIG{QUIT} = 'IGNORE';
3021 local $SIG{TERM} = 'IGNORE';
3022 local $SIG{TSTP} = 'IGNORE';
3023 local $SIG{PIPE} = 'IGNORE';
3025 my $oldAutoCommit = $FS::UID::AutoCommit;
3026 local $FS::UID::AutoCommit = 0;
3029 #a little false laziness w/due_cust_event (not too bad, really)
3031 my $join = FS::part_event_condition->join_conditions_sql;
3032 my $order = FS::part_event_condition->order_conditions_sql;
3035 . join ( ' OR ' , map {
3036 "( part_event.eventtable = " . dbh->quote($_)
3037 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3038 } FS::part_event->eventtables)
3041 #here is the agent virtualization
3042 my $agent_virt = " ( part_event.agentnum IS NULL
3043 OR part_event.agentnum = ". $self->agentnum. ' )';
3045 #XXX this shouldn't be hardcoded, actions should declare it...
3046 my @realtime_events = qw(
3047 cust_bill_realtime_card
3048 cust_bill_realtime_check
3049 cust_bill_realtime_lec
3053 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3058 my @cust_event = qsearchs({
3059 'table' => 'cust_event',
3060 'select' => 'cust_event.*',
3061 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3062 'hashref' => { 'status' => 'done' },
3063 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3064 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3067 my %seen_invnum = ();
3068 foreach my $cust_event (@cust_event) {
3070 #max one for the customer, one for each open invoice
3071 my $cust_X = $cust_event->cust_X;
3072 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3076 or $cust_event->part_event->eventtable eq 'cust_bill'
3079 my $error = $cust_event->retry;
3081 $dbh->rollback if $oldAutoCommit;
3082 return "error scheduling event for retry: $error";
3087 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3092 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3094 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3095 via a Business::OnlinePayment realtime gateway. See
3096 L<http://420.am/business-onlinepayment> for supported gateways.
3098 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3100 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3102 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3103 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3104 if set, will override the value from the customer record.
3106 I<description> is a free-text field passed to the gateway. It defaults to
3107 "Internet services".
3109 If an I<invnum> is specified, this payment (if successful) is applied to the
3110 specified invoice. If you don't specify an I<invnum> you might want to
3111 call the B<apply_payments> method.
3113 I<quiet> can be set true to surpress email decline notices.
3115 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
3116 resulting paynum, if any.
3118 I<payunique> is a unique identifier for this payment.
3120 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3125 my( $self, $method, $amount, %options ) = @_;
3127 warn "$me realtime_bop: $method $amount\n";
3128 warn " $_ => $options{$_}\n" foreach keys %options;
3131 $options{'description'} ||= 'Internet services';
3133 return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3135 eval "use Business::OnlinePayment";
3138 my $payinfo = exists($options{'payinfo'})
3139 ? $options{'payinfo'}
3142 my %method2payby = (
3149 # check for banned credit card/ACH
3152 my $ban = qsearchs('banned_pay', {
3153 'payby' => $method2payby{$method},
3154 'payinfo' => md5_base64($payinfo),
3156 return "Banned credit card" if $ban;
3163 if ( $options{'invnum'} ) {
3164 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3165 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3167 map { $_->part_pkg->taxclass }
3169 map { $_->cust_pkg }
3170 $cust_bill->cust_bill_pkg;
3171 unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3172 #different taxclasses
3173 $taxclass = $taxclasses[0];
3177 #look for an agent gateway override first
3179 if ( $method eq 'CC' ) {
3180 $cardtype = cardtype($payinfo);
3181 } elsif ( $method eq 'ECHECK' ) {
3184 $cardtype = $method;
3188 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3189 cardtype => $cardtype,
3190 taxclass => $taxclass, } )
3191 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3193 taxclass => $taxclass, } )
3194 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3195 cardtype => $cardtype,
3197 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3199 taxclass => '', } );
3201 my $payment_gateway = '';
3202 my( $processor, $login, $password, $action, @bop_options );
3203 if ( $override ) { #use a payment gateway override
3205 $payment_gateway = $override->payment_gateway;
3207 $processor = $payment_gateway->gateway_module;
3208 $login = $payment_gateway->gateway_username;
3209 $password = $payment_gateway->gateway_password;
3210 $action = $payment_gateway->gateway_action;
3211 @bop_options = $payment_gateway->options;
3213 } else { #use the standard settings from the config
3215 ( $processor, $login, $password, $action, @bop_options ) =
3216 $self->default_payment_gateway($method);
3224 my $address = exists($options{'address1'})
3225 ? $options{'address1'}
3227 my $address2 = exists($options{'address2'})
3228 ? $options{'address2'}
3230 $address .= ", ". $address2 if length($address2);
3232 my $o_payname = exists($options{'payname'})
3233 ? $options{'payname'}
3235 my($payname, $payfirst, $paylast);
3236 if ( $o_payname && $method ne 'ECHECK' ) {
3237 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3238 or return "Illegal payname $payname";
3239 ($payfirst, $paylast) = ($1, $2);
3241 $payfirst = $self->getfield('first');
3242 $paylast = $self->getfield('last');
3243 $payname = "$payfirst $paylast";
3246 my @invoicing_list = $self->invoicing_list_emailonly;
3247 if ( $conf->exists('emailinvoiceautoalways')
3248 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3249 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3250 push @invoicing_list, $self->all_emails;
3253 my $email = ($conf->exists('business-onlinepayment-email-override'))
3254 ? $conf->config('business-onlinepayment-email-override')
3255 : $invoicing_list[0];
3259 my $payip = exists($options{'payip'})
3262 $content{customer_ip} = $payip
3265 $content{invoice_number} = $options{'invnum'}
3266 if exists($options{'invnum'}) && length($options{'invnum'});
3268 $content{email_customer} =
3269 ( $conf->exists('business-onlinepayment-email_customer')
3270 || $conf->exists('business-onlinepayment-email-override') );
3273 if ( $method eq 'CC' ) {
3275 $content{card_number} = $payinfo;
3276 $paydate = exists($options{'paydate'})
3277 ? $options{'paydate'}
3279 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3280 $content{expiration} = "$2/$1";
3282 my $paycvv = exists($options{'paycvv'})
3283 ? $options{'paycvv'}
3285 $content{cvv2} = $paycvv
3288 my $paystart_month = exists($options{'paystart_month'})
3289 ? $options{'paystart_month'}
3290 : $self->paystart_month;
3292 my $paystart_year = exists($options{'paystart_year'})
3293 ? $options{'paystart_year'}
3294 : $self->paystart_year;
3296 $content{card_start} = "$paystart_month/$paystart_year"
3297 if $paystart_month && $paystart_year;
3299 my $payissue = exists($options{'payissue'})
3300 ? $options{'payissue'}
3302 $content{issue_number} = $payissue if $payissue;
3304 $content{recurring_billing} = 'YES'
3305 if qsearch('cust_pay', { 'custnum' => $self->custnum,
3307 'payinfo' => $payinfo,
3309 || qsearch('cust_pay', { 'custnum' => $self->custnum,
3311 'paymask' => $self->mask_payinfo('CARD', $payinfo),
3315 } elsif ( $method eq 'ECHECK' ) {
3316 ( $content{account_number}, $content{routing_code} ) =
3317 split('@', $payinfo);
3318 $content{bank_name} = $o_payname;
3319 $content{bank_state} = exists($options{'paystate'})
3320 ? $options{'paystate'}
3321 : $self->getfield('paystate');
3322 $content{account_type} = exists($options{'paytype'})
3323 ? uc($options{'paytype'}) || 'CHECKING'
3324 : uc($self->getfield('paytype')) || 'CHECKING';
3325 $content{account_name} = $payname;
3326 $content{customer_org} = $self->company ? 'B' : 'I';
3327 $content{state_id} = exists($options{'stateid'})
3328 ? $options{'stateid'}
3329 : $self->getfield('stateid');
3330 $content{state_id_state} = exists($options{'stateid_state'})
3331 ? $options{'stateid_state'}
3332 : $self->getfield('stateid_state');
3333 $content{customer_ssn} = exists($options{'ss'})
3336 } elsif ( $method eq 'LEC' ) {
3337 $content{phone} = $payinfo;
3341 # run transaction(s)
3344 my $balance = exists( $options{'balance'} )
3345 ? $options{'balance'}
3348 $self->select_for_update; #mutex ... just until we get our pending record in
3350 #the checks here are intended to catch concurrent payments
3351 #double-form-submission prevention is taken care of in cust_pay_pending::check
3354 return "The customer's balance has changed; $method transaction aborted."
3355 if $self->balance < $balance;
3356 #&& $self->balance < $amount; #might as well anyway?
3358 #also check and make sure there aren't *other* pending payments for this cust
3360 my @pending = qsearch('cust_pay_pending', {
3361 'custnum' => $self->custnum,
3362 'status' => { op=>'!=', value=>'done' }
3364 return "A payment is already being processed for this customer (".
3365 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3366 "); $method transaction aborted."
3367 if scalar(@pending);
3369 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3371 my $cust_pay_pending = new FS::cust_pay_pending {
3372 'custnum' => $self->custnum,
3373 #'invnum' => $options{'invnum'},
3376 'payby' => $method2payby{$method},
3377 'payinfo' => $payinfo,
3378 'paydate' => $paydate,
3380 'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3382 $cust_pay_pending->payunique( $options{payunique} )
3383 if defined($options{payunique}) && length($options{payunique});
3384 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3385 return $cpp_new_err if $cpp_new_err;
3387 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3389 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3390 $transaction->content(
3393 'password' => $password,
3394 'action' => $action1,
3395 'description' => $options{'description'},
3396 'amount' => $amount,
3397 #'invoice_number' => $options{'invnum'},
3398 'customer_id' => $self->custnum,
3399 'last_name' => $paylast,
3400 'first_name' => $payfirst,
3402 'address' => $address,
3403 'city' => ( exists($options{'city'})
3406 'state' => ( exists($options{'state'})
3409 'zip' => ( exists($options{'zip'})
3412 'country' => ( exists($options{'country'})
3413 ? $options{'country'}
3415 'referer' => 'http://cleanwhisker.420.am/',
3417 'phone' => $self->daytime || $self->night,
3421 $cust_pay_pending->status('pending');
3422 my $cpp_pending_err = $cust_pay_pending->replace;
3423 return $cpp_pending_err if $cpp_pending_err;
3426 my $BOP_TESTING = 0;
3427 my $BOP_TESTING_SUCCESS = 1;
3429 unless ( $BOP_TESTING ) {
3430 $transaction->submit();
3432 if ( $BOP_TESTING_SUCCESS ) {
3433 $transaction->is_success(1);
3434 $transaction->authorization('fake auth');
3436 $transaction->is_success(0);
3437 $transaction->error_message('fake failure');
3441 if ( $transaction->is_success() && $action2 ) {
3443 $cust_pay_pending->status('authorized');
3444 my $cpp_authorized_err = $cust_pay_pending->replace;
3445 return $cpp_authorized_err if $cpp_authorized_err;
3447 my $auth = $transaction->authorization;
3448 my $ordernum = $transaction->can('order_number')
3449 ? $transaction->order_number
3453 new Business::OnlinePayment( $processor, @bop_options );
3460 password => $password,
3461 order_number => $ordernum,
3463 authorization => $auth,
3464 description => $options{'description'},
3467 foreach my $field (qw( authorization_source_code returned_ACI
3468 transaction_identifier validation_code
3469 transaction_sequence_num local_transaction_date
3470 local_transaction_time AVS_result_code )) {
3471 $capture{$field} = $transaction->$field() if $transaction->can($field);
3474 $capture->content( %capture );
3478 unless ( $capture->is_success ) {
3479 my $e = "Authorization successful but capture failed, custnum #".
3480 $self->custnum. ': '. $capture->result_code.
3481 ": ". $capture->error_message;
3488 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3489 my $cpp_captured_err = $cust_pay_pending->replace;
3490 return $cpp_captured_err if $cpp_captured_err;
3493 # remove paycvv after initial transaction
3496 #false laziness w/misc/process/payment.cgi - check both to make sure working
3498 if ( defined $self->dbdef_table->column('paycvv')
3499 && length($self->paycvv)
3500 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3502 my $error = $self->remove_cvv;
3504 warn "WARNING: error removing cvv: $error\n";
3512 if ( $transaction->is_success() ) {
3515 if ( $payment_gateway ) { # agent override
3516 $paybatch = $payment_gateway->gatewaynum. '-';
3519 $paybatch .= "$processor:". $transaction->authorization;
3521 $paybatch .= ':'. $transaction->order_number
3522 if $transaction->can('order_number')
3523 && length($transaction->order_number);
3525 my $cust_pay = new FS::cust_pay ( {
3526 'custnum' => $self->custnum,
3527 'invnum' => $options{'invnum'},
3530 'payby' => $method2payby{$method},
3531 'payinfo' => $payinfo,
3532 'paybatch' => $paybatch,
3533 'paydate' => $paydate,
3535 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3536 $cust_pay->payunique( $options{payunique} )
3537 if defined($options{payunique}) && length($options{payunique});
3539 my $oldAutoCommit = $FS::UID::AutoCommit;
3540 local $FS::UID::AutoCommit = 0;
3543 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3545 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3548 $cust_pay->invnum(''); #try again with no specific invnum
3549 my $error2 = $cust_pay->insert( $options{'manual'} ?
3550 ( 'manual' => 1 ) : ()
3553 # gah. but at least we have a record of the state we had to abort in
3554 # from cust_pay_pending now.
3555 my $e = "WARNING: $method captured but payment not recorded - ".
3556 "error inserting payment ($processor): $error2".
3557 " (previously tried insert with invnum #$options{'invnum'}" .
3558 ": $error ) - pending payment saved as paypendingnum ".
3559 $cust_pay_pending->paypendingnum. "\n";
3565 if ( $options{'paynum_ref'} ) {
3566 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3569 $cust_pay_pending->status('done');
3570 $cust_pay_pending->statustext('captured');
3571 my $cpp_done_err = $cust_pay_pending->replace;
3573 if ( $cpp_done_err ) {
3575 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3576 my $e = "WARNING: $method captured but payment not recorded - ".
3577 "error updating status for paypendingnum ".
3578 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3584 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3585 return ''; #no error
3591 my $perror = "$processor error: ". $transaction->error_message;
3593 unless ( $transaction->error_message ) {
3596 if ( $transaction->can('response_page') ) {
3598 'page' => ( $transaction->can('response_page')
3599 ? $transaction->response_page
3602 'code' => ( $transaction->can('response_code')
3603 ? $transaction->response_code
3606 'headers' => ( $transaction->can('response_headers')
3607 ? $transaction->response_headers
3613 "No additional debugging information available for $processor";
3616 $perror .= "No error_message returned from $processor -- ".
3617 ( ref($t_response) ? Dumper($t_response) : $t_response );
3621 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3622 && $conf->exists('emaildecline')
3623 && grep { $_ ne 'POST' } $self->invoicing_list
3624 && ! grep { $transaction->error_message =~ /$_/ }
3625 $conf->config('emaildecline-exclude')
3627 my @templ = $conf->config('declinetemplate');
3628 my $template = new Text::Template (
3630 SOURCE => [ map "$_\n", @templ ],
3631 ) or return "($perror) can't create template: $Text::Template::ERROR";
3632 $template->compile()
3633 or return "($perror) can't compile template: $Text::Template::ERROR";
3635 my $templ_hash = { error => $transaction->error_message };
3637 my $error = send_email(
3638 'from' => $conf->config('invoice_from'),
3639 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3640 'subject' => 'Your payment could not be processed',
3641 'body' => [ $template->fill_in(HASH => $templ_hash) ],
3644 $perror .= " (also received error sending decline notification: $error)"
3649 $cust_pay_pending->status('done');
3650 $cust_pay_pending->statustext("declined: $perror");
3651 my $cpp_done_err = $cust_pay_pending->replace;
3652 if ( $cpp_done_err ) {
3653 my $e = "WARNING: $method declined but pending payment not resolved - ".
3654 "error updating status for paypendingnum ".
3655 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3657 $perror = "$e ($perror)";
3670 my( $self, $method, $amount, %options ) = @_;
3672 if ( $options{'fake_failure'} ) {
3673 return "Error: No error; test failure requested with fake_failure";
3676 my %method2payby = (
3683 #if ( $payment_gateway ) { # agent override
3684 # $paybatch = $payment_gateway->gatewaynum. '-';
3687 #$paybatch .= "$processor:". $transaction->authorization;
3689 #$paybatch .= ':'. $transaction->order_number
3690 # if $transaction->can('order_number')
3691 # && length($transaction->order_number);
3693 my $paybatch = 'FakeProcessor:54:32';
3695 my $cust_pay = new FS::cust_pay ( {
3696 'custnum' => $self->custnum,
3697 'invnum' => $options{'invnum'},
3700 'payby' => $method2payby{$method},
3701 #'payinfo' => $payinfo,
3702 'payinfo' => '4111111111111111',
3703 'paybatch' => $paybatch,
3704 #'paydate' => $paydate,
3705 'paydate' => '2012-05-01',
3707 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3709 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3712 $cust_pay->invnum(''); #try again with no specific invnum
3713 my $error2 = $cust_pay->insert( $options{'manual'} ?
3714 ( 'manual' => 1 ) : ()
3717 # gah, even with transactions.
3718 my $e = 'WARNING: Card/ACH debited but database not updated - '.
3719 "error inserting (fake!) payment: $error2".
3720 " (previously tried insert with invnum #$options{'invnum'}" .
3727 if ( $options{'paynum_ref'} ) {
3728 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3731 return ''; #no error
3735 =item default_payment_gateway
3739 sub default_payment_gateway {
3740 my( $self, $method ) = @_;
3742 die "Real-time processing not enabled\n"
3743 unless $conf->exists('business-onlinepayment');
3746 my $bop_config = 'business-onlinepayment';
3747 $bop_config .= '-ach'
3748 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3749 my ( $processor, $login, $password, $action, @bop_options ) =
3750 $conf->config($bop_config);
3751 $action ||= 'normal authorization';
3752 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3753 die "No real-time processor is enabled - ".
3754 "did you set the business-onlinepayment configuration value?\n"
3757 ( $processor, $login, $password, $action, @bop_options )
3762 Removes the I<paycvv> field from the database directly.
3764 If there is an error, returns the error, otherwise returns false.
3770 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3771 or return dbh->errstr;
3772 $sth->execute($self->custnum)
3773 or return $sth->errstr;
3778 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3780 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3781 via a Business::OnlinePayment realtime gateway. See
3782 L<http://420.am/business-onlinepayment> for supported gateways.
3784 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3786 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3788 Most gateways require a reference to an original payment transaction to refund,
3789 so you probably need to specify a I<paynum>.
3791 I<amount> defaults to the original amount of the payment if not specified.
3793 I<reason> specifies a reason for the refund.
3795 I<paydate> specifies the expiration date for a credit card overriding the
3796 value from the customer record or the payment record. Specified as yyyy-mm-dd
3798 Implementation note: If I<amount> is unspecified or equal to the amount of the
3799 orignal payment, first an attempt is made to "void" the transaction via
3800 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3801 the normal attempt is made to "refund" ("credit") the transaction via the
3802 gateway is attempted.
3804 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3805 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
3806 #if set, will override the value from the customer record.
3808 #If an I<invnum> is specified, this payment (if successful) is applied to the
3809 #specified invoice. If you don't specify an I<invnum> you might want to
3810 #call the B<apply_payments> method.
3814 #some false laziness w/realtime_bop, not enough to make it worth merging
3815 #but some useful small subs should be pulled out
3816 sub realtime_refund_bop {
3817 my( $self, $method, %options ) = @_;
3819 warn "$me realtime_refund_bop: $method refund\n";
3820 warn " $_ => $options{$_}\n" foreach keys %options;
3823 eval "use Business::OnlinePayment";
3827 # look up the original payment and optionally a gateway for that payment
3831 my $amount = $options{'amount'};
3833 my( $processor, $login, $password, @bop_options ) ;
3834 my( $auth, $order_number ) = ( '', '', '' );
3836 if ( $options{'paynum'} ) {
3838 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
3839 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3840 or return "Unknown paynum $options{'paynum'}";
3841 $amount ||= $cust_pay->paid;
3843 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3844 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3845 $cust_pay->paybatch;
3846 my $gatewaynum = '';
3847 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3849 if ( $gatewaynum ) { #gateway for the payment to be refunded
3851 my $payment_gateway =
3852 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3853 die "payment gateway $gatewaynum not found"
3854 unless $payment_gateway;
3856 $processor = $payment_gateway->gateway_module;
3857 $login = $payment_gateway->gateway_username;
3858 $password = $payment_gateway->gateway_password;
3859 @bop_options = $payment_gateway->options;
3861 } else { #try the default gateway
3863 my( $conf_processor, $unused_action );
3864 ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3865 $self->default_payment_gateway($method);
3867 return "processor of payment $options{'paynum'} $processor does not".
3868 " match default processor $conf_processor"
3869 unless $processor eq $conf_processor;
3874 } else { # didn't specify a paynum, so look for agent gateway overrides
3875 # like a normal transaction
3878 if ( $method eq 'CC' ) {
3879 $cardtype = cardtype($self->payinfo);
3880 } elsif ( $method eq 'ECHECK' ) {
3883 $cardtype = $method;
3886 qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3887 cardtype => $cardtype,
3889 || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3891 taxclass => '', } );
3893 if ( $override ) { #use a payment gateway override
3895 my $payment_gateway = $override->payment_gateway;
3897 $processor = $payment_gateway->gateway_module;
3898 $login = $payment_gateway->gateway_username;
3899 $password = $payment_gateway->gateway_password;
3900 #$action = $payment_gateway->gateway_action;
3901 @bop_options = $payment_gateway->options;
3903 } else { #use the standard settings from the config
3906 ( $processor, $login, $password, $unused_action, @bop_options ) =
3907 $self->default_payment_gateway($method);
3912 return "neither amount nor paynum specified" unless $amount;
3917 'password' => $password,
3918 'order_number' => $order_number,
3919 'amount' => $amount,
3920 'referer' => 'http://cleanwhisker.420.am/',
3922 $content{authorization} = $auth
3923 if length($auth); #echeck/ACH transactions have an order # but no auth
3924 #(at least with authorize.net)
3926 my $disable_void_after;
3927 if ($conf->exists('disable_void_after')
3928 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3929 $disable_void_after = $1;
3932 #first try void if applicable
3933 if ( $cust_pay && $cust_pay->paid == $amount
3935 ( not defined($disable_void_after) )
3936 || ( time < ($cust_pay->_date + $disable_void_after ) )
3939 warn " attempting void\n" if $DEBUG > 1;
3940 my $void = new Business::OnlinePayment( $processor, @bop_options );
3941 $void->content( 'action' => 'void', %content );
3943 if ( $void->is_success ) {
3944 my $error = $cust_pay->void($options{'reason'});
3946 # gah, even with transactions.
3947 my $e = 'WARNING: Card/ACH voided but database not updated - '.
3948 "error voiding payment: $error";
3952 warn " void successful\n" if $DEBUG > 1;
3957 warn " void unsuccessful, trying refund\n"
3961 my $address = $self->address1;
3962 $address .= ", ". $self->address2 if $self->address2;
3964 my($payname, $payfirst, $paylast);
3965 if ( $self->payname && $method ne 'ECHECK' ) {
3966 $payname = $self->payname;
3967 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3968 or return "Illegal payname $payname";
3969 ($payfirst, $paylast) = ($1, $2);
3971 $payfirst = $self->getfield('first');
3972 $paylast = $self->getfield('last');
3973 $payname = "$payfirst $paylast";
3976 my @invoicing_list = $self->invoicing_list_emailonly;
3977 if ( $conf->exists('emailinvoiceautoalways')
3978 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3979 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3980 push @invoicing_list, $self->all_emails;
3983 my $email = ($conf->exists('business-onlinepayment-email-override'))
3984 ? $conf->config('business-onlinepayment-email-override')
3985 : $invoicing_list[0];
3987 my $payip = exists($options{'payip'})
3990 $content{customer_ip} = $payip
3994 if ( $method eq 'CC' ) {
3997 $content{card_number} = $payinfo = $cust_pay->payinfo;
3998 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3999 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
4000 ($content{expiration} = "$2/$1"); # where available
4002 $content{card_number} = $payinfo = $self->payinfo;
4003 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
4004 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
4005 $content{expiration} = "$2/$1";
4008 } elsif ( $method eq 'ECHECK' ) {
4011 $payinfo = $cust_pay->payinfo;
4013 $payinfo = $self->payinfo;
4015 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
4016 $content{bank_name} = $self->payname;
4017 $content{account_type} = 'CHECKING';
4018 $content{account_name} = $payname;
4019 $content{customer_org} = $self->company ? 'B' : 'I';
4020 $content{customer_ssn} = $self->ss;
4021 } elsif ( $method eq 'LEC' ) {
4022 $content{phone} = $payinfo = $self->payinfo;
4026 my $refund = new Business::OnlinePayment( $processor, @bop_options );
4027 my %sub_content = $refund->content(
4028 'action' => 'credit',
4029 'customer_id' => $self->custnum,
4030 'last_name' => $paylast,
4031 'first_name' => $payfirst,
4033 'address' => $address,
4034 'city' => $self->city,
4035 'state' => $self->state,
4036 'zip' => $self->zip,
4037 'country' => $self->country,
4039 'phone' => $self->daytime || $self->night,
4042 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
4046 return "$processor error: ". $refund->error_message
4047 unless $refund->is_success();
4049 my %method2payby = (
4055 my $paybatch = "$processor:". $refund->authorization;
4056 $paybatch .= ':'. $refund->order_number
4057 if $refund->can('order_number') && $refund->order_number;
4059 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4060 my @cust_bill_pay = $cust_pay->cust_bill_pay;
4061 last unless @cust_bill_pay;
4062 my $cust_bill_pay = pop @cust_bill_pay;
4063 my $error = $cust_bill_pay->delete;
4067 my $cust_refund = new FS::cust_refund ( {
4068 'custnum' => $self->custnum,
4069 'paynum' => $options{'paynum'},
4070 'refund' => $amount,
4072 'payby' => $method2payby{$method},
4073 'payinfo' => $payinfo,
4074 'paybatch' => $paybatch,
4075 'reason' => $options{'reason'} || 'card or ACH refund',
4077 my $error = $cust_refund->insert;
4079 $cust_refund->paynum(''); #try again with no specific paynum
4080 my $error2 = $cust_refund->insert;
4082 # gah, even with transactions.
4083 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4084 "error inserting refund ($processor): $error2".
4085 " (previously tried insert with paynum #$options{'paynum'}" .
4096 =item batch_card OPTION => VALUE...
4098 Adds a payment for this invoice to the pending credit card batch (see
4099 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4100 runs the payment using a realtime gateway.
4105 my ($self, %options) = @_;
4108 if (exists($options{amount})) {
4109 $amount = $options{amount};
4111 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4113 return '' unless $amount > 0;
4115 my $invnum = delete $options{invnum};
4116 my $payby = $options{invnum} || $self->payby; #dubious
4118 if ($options{'realtime'}) {
4119 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4125 my $oldAutoCommit = $FS::UID::AutoCommit;
4126 local $FS::UID::AutoCommit = 0;
4129 #this needs to handle mysql as well as Pg, like svc_acct.pm
4130 #(make it into a common function if folks need to do batching with mysql)
4131 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4132 or return "Cannot lock pay_batch: " . $dbh->errstr;
4136 'payby' => FS::payby->payby2payment($payby),
4139 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4141 unless ( $pay_batch ) {
4142 $pay_batch = new FS::pay_batch \%pay_batch;
4143 my $error = $pay_batch->insert;
4145 $dbh->rollback if $oldAutoCommit;
4146 die "error creating new batch: $error\n";
4150 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4151 'batchnum' => $pay_batch->batchnum,
4152 'custnum' => $self->custnum,
4155 foreach (qw( address1 address2 city state zip country payby payinfo paydate
4157 $options{$_} = '' unless exists($options{$_});
4160 my $cust_pay_batch = new FS::cust_pay_batch ( {
4161 'batchnum' => $pay_batch->batchnum,
4162 'invnum' => $invnum || 0, # is there a better value?
4163 # this field should be
4165 # cust_bill_pay_batch now
4166 'custnum' => $self->custnum,
4167 'last' => $self->getfield('last'),
4168 'first' => $self->getfield('first'),
4169 'address1' => $options{address1} || $self->address1,
4170 'address2' => $options{address2} || $self->address2,
4171 'city' => $options{city} || $self->city,
4172 'state' => $options{state} || $self->state,
4173 'zip' => $options{zip} || $self->zip,
4174 'country' => $options{country} || $self->country,
4175 'payby' => $options{payby} || $self->payby,
4176 'payinfo' => $options{payinfo} || $self->payinfo,
4177 'exp' => $options{paydate} || $self->paydate,
4178 'payname' => $options{payname} || $self->payname,
4179 'amount' => $amount, # consolidating
4182 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4183 if $old_cust_pay_batch;
4186 if ($old_cust_pay_batch) {
4187 $error = $cust_pay_batch->replace($old_cust_pay_batch)
4189 $error = $cust_pay_batch->insert;
4193 $dbh->rollback if $oldAutoCommit;
4197 my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
4198 foreach my $cust_bill ($self->open_cust_bill) {
4199 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4200 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4201 'invnum' => $cust_bill->invnum,
4202 'paybatchnum' => $cust_pay_batch->paybatchnum,
4203 'amount' => $cust_bill->owed,
4206 if ($unapplied >= $cust_bill_pay_batch->amount){
4207 $unapplied -= $cust_bill_pay_batch->amount;
4210 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
4211 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
4213 $error = $cust_bill_pay_batch->insert;
4215 $dbh->rollback if $oldAutoCommit;
4220 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4226 Returns the total owed for this customer on all invoices
4227 (see L<FS::cust_bill/owed>).
4233 $self->total_owed_date(2145859200); #12/31/2037
4236 =item total_owed_date TIME
4238 Returns the total owed for this customer on all invoices with date earlier than
4239 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
4240 see L<Time::Local> and L<Date::Parse> for conversion functions.
4244 sub total_owed_date {
4248 foreach my $cust_bill (
4249 grep { $_->_date <= $time }
4250 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4252 $total_bill += $cust_bill->owed;
4254 sprintf( "%.2f", $total_bill );
4257 =item apply_payments_and_credits
4259 Applies unapplied payments and credits.
4261 In most cases, this new method should be used in place of sequential
4262 apply_payments and apply_credits methods.
4264 If there is an error, returns the error, otherwise returns false.
4268 sub apply_payments_and_credits {
4271 local $SIG{HUP} = 'IGNORE';
4272 local $SIG{INT} = 'IGNORE';
4273 local $SIG{QUIT} = 'IGNORE';
4274 local $SIG{TERM} = 'IGNORE';
4275 local $SIG{TSTP} = 'IGNORE';
4276 local $SIG{PIPE} = 'IGNORE';
4278 my $oldAutoCommit = $FS::UID::AutoCommit;
4279 local $FS::UID::AutoCommit = 0;
4282 $self->select_for_update; #mutex
4284 foreach my $cust_bill ( $self->open_cust_bill ) {
4285 my $error = $cust_bill->apply_payments_and_credits;
4287 $dbh->rollback if $oldAutoCommit;
4288 return "Error applying: $error";
4292 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4297 =item apply_credits OPTION => VALUE ...
4299 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4300 to outstanding invoice balances in chronological order (or reverse
4301 chronological order if the I<order> option is set to B<newest>) and returns the
4302 value of any remaining unapplied credits available for refund (see
4303 L<FS::cust_refund>).
4305 Dies if there is an error.
4313 local $SIG{HUP} = 'IGNORE';
4314 local $SIG{INT} = 'IGNORE';
4315 local $SIG{QUIT} = 'IGNORE';
4316 local $SIG{TERM} = 'IGNORE';
4317 local $SIG{TSTP} = 'IGNORE';
4318 local $SIG{PIPE} = 'IGNORE';
4320 my $oldAutoCommit = $FS::UID::AutoCommit;
4321 local $FS::UID::AutoCommit = 0;
4324 $self->select_for_update; #mutex
4326 unless ( $self->total_credited ) {
4327 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4331 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4332 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4334 my @invoices = $self->open_cust_bill;
4335 @invoices = sort { $b->_date <=> $a->_date } @invoices
4336 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4339 foreach my $cust_bill ( @invoices ) {
4342 if ( !defined($credit) || $credit->credited == 0) {
4343 $credit = pop @credits or last;
4346 if ($cust_bill->owed >= $credit->credited) {
4347 $amount=$credit->credited;
4349 $amount=$cust_bill->owed;
4352 my $cust_credit_bill = new FS::cust_credit_bill ( {
4353 'crednum' => $credit->crednum,
4354 'invnum' => $cust_bill->invnum,
4355 'amount' => $amount,
4357 my $error = $cust_credit_bill->insert;
4359 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4363 redo if ($cust_bill->owed > 0);
4367 my $total_credited = $self->total_credited;
4369 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4371 return $total_credited;
4374 =item apply_payments
4376 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4377 to outstanding invoice balances in chronological order.
4379 #and returns the value of any remaining unapplied payments.
4381 Dies if there is an error.
4385 sub apply_payments {
4388 local $SIG{HUP} = 'IGNORE';
4389 local $SIG{INT} = 'IGNORE';
4390 local $SIG{QUIT} = 'IGNORE';
4391 local $SIG{TERM} = 'IGNORE';
4392 local $SIG{TSTP} = 'IGNORE';
4393 local $SIG{PIPE} = 'IGNORE';
4395 my $oldAutoCommit = $FS::UID::AutoCommit;
4396 local $FS::UID::AutoCommit = 0;
4399 $self->select_for_update; #mutex
4403 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4404 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4406 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4407 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4411 foreach my $cust_bill ( @invoices ) {
4414 if ( !defined($payment) || $payment->unapplied == 0 ) {
4415 $payment = pop @payments or last;
4418 if ( $cust_bill->owed >= $payment->unapplied ) {
4419 $amount = $payment->unapplied;
4421 $amount = $cust_bill->owed;
4424 my $cust_bill_pay = new FS::cust_bill_pay ( {
4425 'paynum' => $payment->paynum,
4426 'invnum' => $cust_bill->invnum,
4427 'amount' => $amount,
4429 my $error = $cust_bill_pay->insert;
4431 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4435 redo if ( $cust_bill->owed > 0);
4439 my $total_unapplied_payments = $self->total_unapplied_payments;
4441 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4443 return $total_unapplied_payments;
4446 =item total_credited
4448 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4449 customer. See L<FS::cust_credit/credited>.
4453 sub total_credited {
4455 my $total_credit = 0;
4456 foreach my $cust_credit ( qsearch('cust_credit', {
4457 'custnum' => $self->custnum,
4459 $total_credit += $cust_credit->credited;
4461 sprintf( "%.2f", $total_credit );
4464 =item total_unapplied_payments
4466 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4467 See L<FS::cust_pay/unapplied>.
4471 sub total_unapplied_payments {
4473 my $total_unapplied = 0;
4474 foreach my $cust_pay ( qsearch('cust_pay', {
4475 'custnum' => $self->custnum,
4477 $total_unapplied += $cust_pay->unapplied;
4479 sprintf( "%.2f", $total_unapplied );
4482 =item total_unapplied_refunds
4484 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4485 customer. See L<FS::cust_refund/unapplied>.
4489 sub total_unapplied_refunds {
4491 my $total_unapplied = 0;
4492 foreach my $cust_refund ( qsearch('cust_refund', {
4493 'custnum' => $self->custnum,
4495 $total_unapplied += $cust_refund->unapplied;
4497 sprintf( "%.2f", $total_unapplied );
4502 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4503 total_credited minus total_unapplied_payments).
4511 + $self->total_unapplied_refunds
4512 - $self->total_credited
4513 - $self->total_unapplied_payments
4517 =item balance_date TIME
4519 Returns the balance for this customer, only considering invoices with date
4520 earlier than TIME (total_owed_date minus total_credited minus
4521 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
4522 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
4531 $self->total_owed_date($time)
4532 + $self->total_unapplied_refunds
4533 - $self->total_credited
4534 - $self->total_unapplied_payments
4538 =item in_transit_payments
4540 Returns the total of requests for payments for this customer pending in
4541 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
4545 sub in_transit_payments {
4547 my $in_transit_payments = 0;
4548 foreach my $pay_batch ( qsearch('pay_batch', {
4551 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4552 'batchnum' => $pay_batch->batchnum,
4553 'custnum' => $self->custnum,
4555 $in_transit_payments += $cust_pay_batch->amount;
4558 sprintf( "%.2f", $in_transit_payments );
4561 =item paydate_monthyear
4563 Returns a two-element list consisting of the month and year of this customer's
4564 paydate (credit card expiration date for CARD customers)
4568 sub paydate_monthyear {
4570 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4572 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4579 =item invoicing_list [ ARRAYREF ]
4581 If an arguement is given, sets these email addresses as invoice recipients
4582 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
4583 (except as warnings), so use check_invoicing_list first.
4585 Returns a list of email addresses (with svcnum entries expanded).
4587 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
4588 check it without disturbing anything by passing nothing.
4590 This interface may change in the future.
4594 sub invoicing_list {
4595 my( $self, $arrayref ) = @_;
4598 my @cust_main_invoice;
4599 if ( $self->custnum ) {
4600 @cust_main_invoice =
4601 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4603 @cust_main_invoice = ();
4605 foreach my $cust_main_invoice ( @cust_main_invoice ) {
4606 #warn $cust_main_invoice->destnum;
4607 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4608 #warn $cust_main_invoice->destnum;
4609 my $error = $cust_main_invoice->delete;
4610 warn $error if $error;
4613 if ( $self->custnum ) {
4614 @cust_main_invoice =
4615 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4617 @cust_main_invoice = ();
4619 my %seen = map { $_->address => 1 } @cust_main_invoice;
4620 foreach my $address ( @{$arrayref} ) {
4621 next if exists $seen{$address} && $seen{$address};
4622 $seen{$address} = 1;
4623 my $cust_main_invoice = new FS::cust_main_invoice ( {
4624 'custnum' => $self->custnum,
4627 my $error = $cust_main_invoice->insert;
4628 warn $error if $error;
4632 if ( $self->custnum ) {
4634 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4641 =item check_invoicing_list ARRAYREF
4643 Checks these arguements as valid input for the invoicing_list method. If there
4644 is an error, returns the error, otherwise returns false.
4648 sub check_invoicing_list {
4649 my( $self, $arrayref ) = @_;
4651 foreach my $address ( @$arrayref ) {
4653 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4654 return 'Can\'t add FAX invoice destination with a blank FAX number.';
4657 my $cust_main_invoice = new FS::cust_main_invoice ( {
4658 'custnum' => $self->custnum,
4661 my $error = $self->custnum
4662 ? $cust_main_invoice->check
4663 : $cust_main_invoice->checkdest
4665 return $error if $error;
4669 return "Email address required"
4670 if $conf->exists('cust_main-require_invoicing_list_email')
4671 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4676 =item set_default_invoicing_list
4678 Sets the invoicing list to all accounts associated with this customer,
4679 overwriting any previous invoicing list.
4683 sub set_default_invoicing_list {
4685 $self->invoicing_list($self->all_emails);
4690 Returns the email addresses of all accounts provisioned for this customer.
4697 foreach my $cust_pkg ( $self->all_pkgs ) {
4698 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4700 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4701 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4703 $list{$_}=1 foreach map { $_->email } @svc_acct;
4708 =item invoicing_list_addpost
4710 Adds postal invoicing to this customer. If this customer is already configured
4711 to receive postal invoices, does nothing.
4715 sub invoicing_list_addpost {
4717 return if grep { $_ eq 'POST' } $self->invoicing_list;
4718 my @invoicing_list = $self->invoicing_list;
4719 push @invoicing_list, 'POST';
4720 $self->invoicing_list(\@invoicing_list);
4723 =item invoicing_list_emailonly
4725 Returns the list of email invoice recipients (invoicing_list without non-email
4726 destinations such as POST and FAX).
4730 sub invoicing_list_emailonly {
4732 warn "$me invoicing_list_emailonly called"
4734 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4737 =item invoicing_list_emailonly_scalar
4739 Returns the list of email invoice recipients (invoicing_list without non-email
4740 destinations such as POST and FAX) as a comma-separated scalar.
4744 sub invoicing_list_emailonly_scalar {
4746 warn "$me invoicing_list_emailonly_scalar called"
4748 join(', ', $self->invoicing_list_emailonly);
4751 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4753 Returns an array of customers referred by this customer (referral_custnum set
4754 to this custnum). If DEPTH is given, recurses up to the given depth, returning
4755 customers referred by customers referred by this customer and so on, inclusive.
4756 The default behavior is DEPTH 1 (no recursion).
4760 sub referral_cust_main {
4762 my $depth = @_ ? shift : 1;
4763 my $exclude = @_ ? shift : {};
4766 map { $exclude->{$_->custnum}++; $_; }
4767 grep { ! $exclude->{ $_->custnum } }
4768 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4772 map { $_->referral_cust_main($depth-1, $exclude) }
4779 =item referral_cust_main_ncancelled
4781 Same as referral_cust_main, except only returns customers with uncancelled
4786 sub referral_cust_main_ncancelled {
4788 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4791 =item referral_cust_pkg [ DEPTH ]
4793 Like referral_cust_main, except returns a flat list of all unsuspended (and
4794 uncancelled) packages for each customer. The number of items in this list may
4795 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4799 sub referral_cust_pkg {
4801 my $depth = @_ ? shift : 1;
4803 map { $_->unsuspended_pkgs }
4804 grep { $_->unsuspended_pkgs }
4805 $self->referral_cust_main($depth);
4808 =item referring_cust_main
4810 Returns the single cust_main record for the customer who referred this customer
4811 (referral_custnum), or false.
4815 sub referring_cust_main {
4817 return '' unless $self->referral_custnum;
4818 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4821 =item credit AMOUNT, REASON
4823 Applies a credit to this customer. If there is an error, returns the error,
4824 otherwise returns false.
4829 my( $self, $amount, $reason, %options ) = @_;
4830 my $cust_credit = new FS::cust_credit {
4831 'custnum' => $self->custnum,
4832 'amount' => $amount,
4833 'reason' => $reason,
4835 $cust_credit->insert(%options);
4838 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4840 Creates a one-time charge for this customer. If there is an error, returns
4841 the error, otherwise returns false.
4847 my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4848 my ( $taxproduct, $override );
4849 if ( ref( $_[0] ) ) {
4850 $amount = $_[0]->{amount};
4851 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4852 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4853 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4854 : '$'. sprintf("%.2f",$amount);
4855 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4856 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4857 $additional = $_[0]->{additional};
4858 $taxproduct = $_[0]->{taxproductnum};
4859 $override = { '' => $_[0]->{tax_override} };
4863 $pkg = @_ ? shift : 'One-time charge';
4864 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4865 $taxclass = @_ ? shift : '';
4869 local $SIG{HUP} = 'IGNORE';
4870 local $SIG{INT} = 'IGNORE';
4871 local $SIG{QUIT} = 'IGNORE';
4872 local $SIG{TERM} = 'IGNORE';
4873 local $SIG{TSTP} = 'IGNORE';
4874 local $SIG{PIPE} = 'IGNORE';
4876 my $oldAutoCommit = $FS::UID::AutoCommit;
4877 local $FS::UID::AutoCommit = 0;
4880 my $part_pkg = new FS::part_pkg ( {
4882 'comment' => $comment,
4886 'classnum' => $classnum ? $classnum : '',
4887 'taxclass' => $taxclass,
4888 'taxproductnum' => $taxproduct,
4891 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4892 ( 0 .. @$additional - 1 )
4894 'additional_count' => scalar(@$additional),
4895 'setup_fee' => $amount,
4898 my $error = $part_pkg->insert( options => \%options,
4899 tax_overrides => $override,
4902 $dbh->rollback if $oldAutoCommit;
4906 my $pkgpart = $part_pkg->pkgpart;
4907 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4908 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4909 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4910 $error = $type_pkgs->insert;
4912 $dbh->rollback if $oldAutoCommit;
4917 my $cust_pkg = new FS::cust_pkg ( {
4918 'custnum' => $self->custnum,
4919 'pkgpart' => $pkgpart,
4920 'quantity' => $quantity,
4923 $error = $cust_pkg->insert;
4925 $dbh->rollback if $oldAutoCommit;
4929 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4934 #=item charge_postal_fee
4936 #Applies a one time charge this customer. If there is an error,
4937 #returns the error, returns the cust_pkg charge object or false
4938 #if there was no charge.
4942 # This should be a customer event. For that to work requires that bill
4943 # also be a customer event.
4945 sub charge_postal_fee {
4948 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4949 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4951 my $cust_pkg = new FS::cust_pkg ( {
4952 'custnum' => $self->custnum,
4953 'pkgpart' => $pkgpart,
4957 my $error = $cust_pkg->insert;
4958 $error ? $error : $cust_pkg;
4963 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4969 sort { $a->_date <=> $b->_date }
4970 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4973 =item open_cust_bill
4975 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4980 sub open_cust_bill {
4982 grep { $_->owed > 0 } $self->cust_bill;
4987 Returns all the credits (see L<FS::cust_credit>) for this customer.
4993 sort { $a->_date <=> $b->_date }
4994 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4999 Returns all the payments (see L<FS::cust_pay>) for this customer.
5005 sort { $a->_date <=> $b->_date }
5006 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
5011 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
5017 sort { $a->_date <=> $b->_date }
5018 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
5021 =item cust_pay_batch
5023 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
5027 sub cust_pay_batch {
5029 sort { $a->_date <=> $b->_date }
5030 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
5035 Returns all the refunds (see L<FS::cust_refund>) for this customer.
5041 sort { $a->_date <=> $b->_date }
5042 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
5047 Returns a name string for this customer, either "Company (Last, First)" or
5054 my $name = $self->contact;
5055 $name = $self->company. " ($name)" if $self->company;
5061 Returns a name string for this (service/shipping) contact, either
5062 "Company (Last, First)" or "Last, First".
5068 if ( $self->get('ship_last') ) {
5069 my $name = $self->ship_contact;
5070 $name = $self->ship_company. " ($name)" if $self->ship_company;
5079 Returns this customer's full (billing) contact name only, "Last, First"
5085 $self->get('last'). ', '. $self->first;
5090 Returns this customer's full (shipping) contact name only, "Last, First"
5096 $self->get('ship_last')
5097 ? $self->get('ship_last'). ', '. $self->ship_first
5103 Returns this customer's full country name
5109 code2country($self->country);
5112 =item geocode DATA_VENDOR
5114 Returns a value for the customer location as encoded by DATA_VENDOR.
5115 Currently this only makes sense for "CCH" as DATA_VENDOR.
5120 my ($self, $data_vendor) = (shift, shift); #always cch for now
5122 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5126 my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5127 if $self->country eq 'US';
5129 #CCH specific location stuff
5130 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5133 my $cust_tax_location =
5135 'table' => 'cust_tax_location',
5136 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5137 'extra_sql' => $extra_sql,
5140 $geocode = $cust_tax_location->geocode
5141 if $cust_tax_location;
5150 Returns a status string for this customer, currently:
5154 =item prospect - No packages have ever been ordered
5156 =item active - One or more recurring packages is active
5158 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5160 =item suspended - All non-cancelled recurring packages are suspended
5162 =item cancelled - All recurring packages are cancelled
5168 sub status { shift->cust_status(@_); }
5172 for my $status (qw( prospect active inactive suspended cancelled )) {
5173 my $method = $status.'_sql';
5174 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5175 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5176 $sth->execute( ($self->custnum) x $numnum )
5177 or die "Error executing 'SELECT $sql': ". $sth->errstr;
5178 return $status if $sth->fetchrow_arrayref->[0];
5182 =item ucfirst_cust_status
5184 =item ucfirst_status
5186 Returns the status with the first character capitalized.
5190 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5192 sub ucfirst_cust_status {
5194 ucfirst($self->cust_status);
5199 Returns a hex triplet color string for this customer's status.
5203 use vars qw(%statuscolor);
5204 tie %statuscolor, 'Tie::IxHash',
5205 'prospect' => '7e0079', #'000000', #black? naw, purple
5206 'active' => '00CC00', #green
5207 'inactive' => '0000CC', #blue
5208 'suspended' => 'FF9900', #yellow
5209 'cancelled' => 'FF0000', #red
5212 sub statuscolor { shift->cust_statuscolor(@_); }
5214 sub cust_statuscolor {
5216 $statuscolor{$self->cust_status};
5221 Returns an array of hashes representing the customer's RT tickets.
5228 my $num = $conf->config('cust_main-max_tickets') || 10;
5231 unless ( $conf->config('ticket_system-custom_priority_field') ) {
5233 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5237 foreach my $priority (
5238 $conf->config('ticket_system-custom_priority_field-values'), ''
5240 last if scalar(@tickets) >= $num;
5242 @{ FS::TicketSystem->customer_tickets( $self->custnum,
5243 $num - scalar(@tickets),
5252 # Return services representing svc_accts in customer support packages
5253 sub support_services {
5255 my %packages = map { $_ => 1 } $conf->config('support_packages');
5257 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5258 grep { $_->part_svc->svcdb eq 'svc_acct' }
5259 map { $_->cust_svc }
5260 grep { exists $packages{ $_->pkgpart } }
5261 $self->ncancelled_pkgs;
5267 =head1 CLASS METHODS
5273 Class method that returns the list of possible status strings for customers
5274 (see L<the status method|/status>). For example:
5276 @statuses = FS::cust_main->statuses();
5281 #my $self = shift; #could be class...
5287 Returns an SQL expression identifying prospective cust_main records (customers
5288 with no packages ever ordered)
5292 use vars qw($select_count_pkgs);
5293 $select_count_pkgs =
5294 "SELECT COUNT(*) FROM cust_pkg
5295 WHERE cust_pkg.custnum = cust_main.custnum";
5297 sub select_count_pkgs_sql {
5301 sub prospect_sql { "
5302 0 = ( $select_count_pkgs )
5307 Returns an SQL expression identifying active cust_main records (customers with
5308 active recurring packages).
5313 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5319 Returns an SQL expression identifying inactive cust_main records (customers with
5320 no active recurring packages, but otherwise unsuspended/uncancelled).
5324 sub inactive_sql { "
5325 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5327 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5333 Returns an SQL expression identifying suspended cust_main records.
5338 sub suspended_sql { susp_sql(@_); }
5340 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5342 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5348 Returns an SQL expression identifying cancelled cust_main records.
5352 sub cancelled_sql { cancel_sql(@_); }
5355 my $recurring_sql = FS::cust_pkg->recurring_sql;
5356 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5359 0 < ( $select_count_pkgs )
5360 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
5361 AND 0 = ( $select_count_pkgs AND $recurring_sql
5362 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5364 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5370 =item uncancelled_sql
5372 Returns an SQL expression identifying un-cancelled cust_main records.
5376 sub uncancelled_sql { uncancel_sql(@_); }
5377 sub uncancel_sql { "
5378 ( 0 < ( $select_count_pkgs
5379 AND ( cust_pkg.cancel IS NULL
5380 OR cust_pkg.cancel = 0
5383 OR 0 = ( $select_count_pkgs )
5389 Returns an SQL fragment to retreive the balance.
5394 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5395 WHERE cust_bill.custnum = cust_main.custnum )
5396 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5397 WHERE cust_pay.custnum = cust_main.custnum )
5398 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5399 WHERE cust_credit.custnum = cust_main.custnum )
5400 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5401 WHERE cust_refund.custnum = cust_main.custnum )
5404 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5406 Returns an SQL fragment to retreive the balance for this customer, only
5407 considering invoices with date earlier than START_TIME, and optionally not
5408 later than END_TIME (total_owed_date minus total_credited minus
5409 total_unapplied_payments).
5411 Times are specified as SQL fragments or numeric
5412 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5413 L<Date::Parse> for conversion functions. The empty string can be passed
5414 to disable that time constraint completely.
5416 Available options are:
5420 =item unapplied_date
5422 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
5427 set to true to remove all customer comparison clauses, for totals
5432 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5437 JOIN clause (typically used with the total option)
5443 sub balance_date_sql {
5444 my( $class, $start, $end, %opt ) = @_;
5446 my $owed = FS::cust_bill->owed_sql;
5447 my $unapp_refund = FS::cust_refund->unapplied_sql;
5448 my $unapp_credit = FS::cust_credit->unapplied_sql;
5449 my $unapp_pay = FS::cust_pay->unapplied_sql;
5451 my $j = $opt{'join'} || '';
5453 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5454 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5455 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5456 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5458 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5459 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5460 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5461 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5466 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5468 Helper method for balance_date_sql; name (and usage) subject to change
5469 (suggestions welcome).
5471 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5472 cust_refund, cust_credit or cust_pay).
5474 If TABLE is "cust_bill" or the unapplied_date option is true, only
5475 considers records with date earlier than START_TIME, and optionally not
5476 later than END_TIME .
5480 sub _money_table_where {
5481 my( $class, $table, $start, $end, %opt ) = @_;
5484 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5485 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5486 push @where, "$table._date <= $start" if defined($start) && length($start);
5487 push @where, "$table._date > $end" if defined($end) && length($end);
5489 push @where, @{$opt{'where'}} if $opt{'where'};
5490 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5496 =item search_sql HASHREF
5500 Returns a qsearch hash expression to search for parameters specified in HREF.
5501 Valid parameters are
5509 =item cancelled_pkgs
5515 listref of start date, end date
5521 =item current_balance
5523 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5527 =item flattened_pkgs
5536 my ($class, $params) = @_;
5547 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5549 "cust_main.agentnum = $1";
5556 #prospect active inactive suspended cancelled
5557 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5558 my $method = $params->{'status'}. '_sql';
5559 #push @where, $class->$method();
5560 push @where, FS::cust_main->$method();
5564 # parse cancelled package checkbox
5569 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5570 unless $params->{'cancelled_pkgs'};
5576 foreach my $field (qw( signupdate )) {
5578 next unless exists($params->{$field});
5580 my($beginning, $ending) = @{$params->{$field}};
5583 "cust_main.$field IS NOT NULL",
5584 "cust_main.$field >= $beginning",
5585 "cust_main.$field <= $ending";
5587 $orderby ||= "ORDER BY cust_main.$field";
5595 my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5597 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5604 #my $balance_sql = $class->balance_sql();
5605 my $balance_sql = FS::cust_main->balance_sql();
5607 push @where, map { s/current_balance/$balance_sql/; $_ }
5608 @{ $params->{'current_balance'} };
5614 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
5616 "cust_main.custbatch = '$1'";
5620 # setup queries, subs, etc. for the search
5623 $orderby ||= 'ORDER BY custnum';
5625 # here is the agent virtualization
5626 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5628 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5630 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
5632 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5634 my $select = join(', ',
5635 'cust_main.custnum',
5636 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5639 my(@extra_headers) = ();
5640 my(@extra_fields) = ();
5642 if ($params->{'flattened_pkgs'}) {
5644 if ($dbh->{Driver}->{Name} eq 'Pg') {
5646 $select .= ", array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
5648 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5649 $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5650 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5652 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
5653 "omitting packing information from report.";
5656 my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
5658 my $sth = dbh->prepare($header_query) or die dbh->errstr;
5659 $sth->execute() or die $sth->errstr;
5660 my $headerrow = $sth->fetchrow_arrayref;
5661 my $headercount = $headerrow ? $headerrow->[0] : 0;
5662 while($headercount) {
5663 unshift @extra_headers, "Package ". $headercount;
5664 unshift @extra_fields, eval q!sub {my $c = shift;
5665 my @a = split '\|', $c->magic;
5666 my $p = $a[!.--$headercount. q!];
5674 'table' => 'cust_main',
5675 'select' => $select,
5677 'extra_sql' => $extra_sql,
5678 'order_by' => $orderby,
5679 'count_query' => $count_query,
5680 'extra_headers' => \@extra_headers,
5681 'extra_fields' => \@extra_fields,
5686 =item email_search_sql HASHREF
5690 Emails a notice to the specified customers.
5692 Valid parameters are those of the L<search_sql> method, plus the following:
5714 Optional job queue job for status updates.
5718 Returns an error message, or false for success.
5720 If an error occurs during any email, stops the enture send and returns that
5721 error. Presumably if you're getting SMTP errors aborting is better than
5722 retrying everything.
5726 sub email_search_sql {
5727 my($class, $params) = @_;
5729 my $from = delete $params->{from};
5730 my $subject = delete $params->{subject};
5731 my $html_body = delete $params->{html_body};
5732 my $text_body = delete $params->{text_body};
5734 my $job = delete $params->{'job'};
5736 my $sql_query = $class->search_sql($params);
5738 my $count_query = delete($sql_query->{'count_query'});
5739 my $count_sth = dbh->prepare($count_query)
5740 or die "Error preparing $count_query: ". dbh->errstr;
5742 or die "Error executing $count_query: ". $count_sth->errstr;
5743 my $count_arrayref = $count_sth->fetchrow_arrayref;
5744 my $num_cust = $count_arrayref->[0];
5746 #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5747 #my @extra_fields = @{ delete($sql_query->{'extra_fields'}) };
5750 my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5752 #eventually order+limit magic to reduce memory use?
5753 foreach my $cust_main ( qsearch($sql_query) ) {
5755 my $to = $cust_main->invoicing_list_emailonly_scalar;
5758 my $error = send_email(
5762 'subject' => $subject,
5763 'html_body' => $html_body,
5764 'text_body' => $text_body,
5767 return $error if $error;
5769 if ( $job ) { #progressbar foo
5771 if ( time - $min_sec > $last ) {
5772 my $error = $job->update_statustext(
5773 int( 100 * $num / $num_cust )
5775 die $error if $error;
5785 use Storable qw(thaw);
5788 sub process_email_search_sql {
5790 #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5792 my $param = thaw(decode_base64(shift));
5793 warn Dumper($param) if $DEBUG;
5795 $param->{'job'} = $job;
5797 my $error = FS::cust_main->email_search_sql( $param );
5798 die $error if $error;
5802 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5804 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5805 records. Currently, I<first>, I<last> and/or I<company> may be specified (the
5806 appropriate ship_ field is also searched).
5808 Additional options are the same as FS::Record::qsearch
5813 my( $self, $fuzzy, $hash, @opt) = @_;
5818 check_and_rebuild_fuzzyfiles();
5819 foreach my $field ( keys %$fuzzy ) {
5821 my $all = $self->all_X($field);
5822 next unless scalar(@$all);
5825 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5828 foreach ( keys %match ) {
5829 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5830 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5833 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5836 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5838 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5846 Returns a masked version of the named field
5851 my ($self,$field) = @_;
5855 'x'x(length($self->getfield($field))-4).
5856 substr($self->getfield($field), (length($self->getfield($field))-4));
5866 =item smart_search OPTION => VALUE ...
5868 Accepts the following options: I<search>, the string to search for. The string
5869 will be searched for as a customer number, phone number, name or company name,
5870 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5871 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5872 skip fuzzy matching when an exact match is found.
5874 Any additional options are treated as an additional qualifier on the search
5877 Returns a (possibly empty) array of FS::cust_main objects.
5884 #here is the agent virtualization
5885 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5889 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5890 my $search = delete $options{'search'};
5891 ( my $alphanum_search = $search ) =~ s/\W//g;
5893 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5895 #false laziness w/Record::ut_phone
5896 my $phonen = "$1-$2-$3";
5897 $phonen .= " x$4" if $4;
5899 push @cust_main, qsearch( {
5900 'table' => 'cust_main',
5901 'hashref' => { %options },
5902 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5904 join(' OR ', map "$_ = '$phonen'",
5905 qw( daytime night fax
5906 ship_daytime ship_night ship_fax )
5909 " AND $agentnums_sql", #agent virtualization
5912 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5913 #try looking for matches with extensions unless one was specified
5915 push @cust_main, qsearch( {
5916 'table' => 'cust_main',
5917 'hashref' => { %options },
5918 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5920 join(' OR ', map "$_ LIKE '$phonen\%'",
5922 ship_daytime ship_night )
5925 " AND $agentnums_sql", #agent virtualization
5930 # custnum search (also try agent_custid), with some tweaking options if your
5931 # legacy cust "numbers" have letters
5932 } elsif ( $search =~ /^\s*(\d+)\s*$/
5933 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5934 && $search =~ /^\s*(\w\w?\d+)\s*$/
5939 push @cust_main, qsearch( {
5940 'table' => 'cust_main',
5941 'hashref' => { 'custnum' => $1, %options },
5942 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5945 push @cust_main, qsearch( {
5946 'table' => 'cust_main',
5947 'hashref' => { 'agent_custid' => $1, %options },
5948 'extra_sql' => " AND $agentnums_sql", #agent virtualization
5951 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5953 my($company, $last, $first) = ( $1, $2, $3 );
5955 # "Company (Last, First)"
5956 #this is probably something a browser remembered,
5957 #so just do an exact search
5959 foreach my $prefix ( '', 'ship_' ) {
5960 push @cust_main, qsearch( {
5961 'table' => 'cust_main',
5962 'hashref' => { $prefix.'first' => $first,
5963 $prefix.'last' => $last,
5964 $prefix.'company' => $company,
5967 'extra_sql' => " AND $agentnums_sql",
5971 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5972 # try (ship_){last,company}
5976 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5977 # # full strings the browser remembers won't work
5978 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5980 use Lingua::EN::NameParse;
5981 my $NameParse = new Lingua::EN::NameParse(
5983 allow_reversed => 1,
5986 my($last, $first) = ( '', '' );
5987 #maybe disable this too and just rely on NameParse?
5988 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5990 ($last, $first) = ( $1, $2 );
5992 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
5993 } elsif ( ! $NameParse->parse($value) ) {
5995 my %name = $NameParse->components;
5996 $first = $name{'given_name_1'};
5997 $last = $name{'surname_1'};
6001 if ( $first && $last ) {
6003 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
6006 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6008 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
6009 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
6012 push @cust_main, qsearch( {
6013 'table' => 'cust_main',
6014 'hashref' => \%options,
6015 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6018 # or it just be something that was typed in... (try that in a sec)
6022 my $q_value = dbh->quote($value);
6025 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
6026 $sql .= " ( LOWER(last) = $q_value
6027 OR LOWER(company) = $q_value
6028 OR LOWER(ship_last) = $q_value
6029 OR LOWER(ship_company) = $q_value
6032 push @cust_main, qsearch( {
6033 'table' => 'cust_main',
6034 'hashref' => \%options,
6035 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
6038 #no exact match, trying substring/fuzzy
6039 #always do substring & fuzzy (unless they're explicity config'ed off)
6040 #getting complaints searches are not returning enough
6041 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
6043 #still some false laziness w/search_sql (was search/cust_main.cgi)
6048 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
6049 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
6052 if ( $first && $last ) {
6055 { 'first' => { op=>'ILIKE', value=>"%$first%" },
6056 'last' => { op=>'ILIKE', value=>"%$last%" },
6058 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
6059 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
6066 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
6067 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
6071 foreach my $hashref ( @hashrefs ) {
6073 push @cust_main, qsearch( {
6074 'table' => 'cust_main',
6075 'hashref' => { %$hashref,
6078 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6087 " AND $agentnums_sql", #extra_sql #agent virtualization
6090 if ( $first && $last ) {
6091 push @cust_main, FS::cust_main->fuzzy_search(
6092 { 'last' => $last, #fuzzy hashref
6093 'first' => $first }, #
6097 foreach my $field ( 'last', 'company' ) {
6099 FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6104 #eliminate duplicates
6106 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6116 Accepts the following options: I<email>, the email address to search for. The
6117 email address will be searched for as an email invoice destination and as an
6120 #Any additional options are treated as an additional qualifier on the search
6121 #(i.e. I<agentnum>).
6123 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6133 my $email = delete $options{'email'};
6135 #we're only being used by RT at the moment... no agent virtualization yet
6136 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6140 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6142 my ( $user, $domain ) = ( $1, $2 );
6144 warn "$me smart_search: searching for $user in domain $domain"
6150 'table' => 'cust_main_invoice',
6151 'hashref' => { 'dest' => $email },
6158 map $_->cust_svc->cust_pkg,
6160 'table' => 'svc_acct',
6161 'hashref' => { 'username' => $user, },
6163 'AND ( SELECT domain FROM svc_domain
6164 WHERE svc_acct.domsvc = svc_domain.svcnum
6165 ) = '. dbh->quote($domain),
6171 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6173 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6180 =item check_and_rebuild_fuzzyfiles
6184 use vars qw(@fuzzyfields);
6185 @fuzzyfields = ( 'last', 'first', 'company' );
6187 sub check_and_rebuild_fuzzyfiles {
6188 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6189 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6192 =item rebuild_fuzzyfiles
6196 sub rebuild_fuzzyfiles {
6198 use Fcntl qw(:flock);
6200 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6201 mkdir $dir, 0700 unless -d $dir;
6203 foreach my $fuzzy ( @fuzzyfields ) {
6205 open(LOCK,">>$dir/cust_main.$fuzzy")
6206 or die "can't open $dir/cust_main.$fuzzy: $!";
6208 or die "can't lock $dir/cust_main.$fuzzy: $!";
6210 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6211 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6213 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6214 my $sth = dbh->prepare("SELECT $field FROM cust_main".
6215 " WHERE $field != '' AND $field IS NOT NULL");
6216 $sth->execute or die $sth->errstr;
6218 while ( my $row = $sth->fetchrow_arrayref ) {
6219 print CACHE $row->[0]. "\n";
6224 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6226 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6237 my( $self, $field ) = @_;
6238 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6239 open(CACHE,"<$dir/cust_main.$field")
6240 or die "can't open $dir/cust_main.$field: $!";
6241 my @array = map { chomp; $_; } <CACHE>;
6246 =item append_fuzzyfiles LASTNAME COMPANY
6250 sub append_fuzzyfiles {
6251 #my( $first, $last, $company ) = @_;
6253 &check_and_rebuild_fuzzyfiles;
6255 use Fcntl qw(:flock);
6257 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6259 foreach my $field (qw( first last company )) {
6264 open(CACHE,">>$dir/cust_main.$field")
6265 or die "can't open $dir/cust_main.$field: $!";
6266 flock(CACHE,LOCK_EX)
6267 or die "can't lock $dir/cust_main.$field: $!";
6269 print CACHE "$value\n";
6271 flock(CACHE,LOCK_UN)
6272 or die "can't unlock $dir/cust_main.$field: $!";
6281 =item process_batch_import
6283 Load a batch import as a queued JSRPC job
6287 use Storable qw(thaw);
6290 sub process_batch_import {
6293 my $param = thaw(decode_base64(shift));
6294 warn Dumper($param) if $DEBUG;
6296 my $files = $param->{'uploaded_files'}
6297 or die "No files provided.\n";
6299 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
6301 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
6302 my $file = $dir. $files{'file'};
6305 if ( $file =~ /\.(\w+)$/i ) {
6309 warn "can't parse file type from filename $file; defaulting to CSV";
6314 FS::cust_main::batch_import( {
6318 custbatch => $param->{custbatch},
6319 agentnum => $param->{'agentnum'},
6320 refnum => $param->{'refnum'},
6321 pkgpart => $param->{'pkgpart'},
6322 #'fields' => [qw( cust_pkg.setup dayphone first last address1 address2
6323 # city state zip comments )],
6324 'format' => $param->{'format'},
6329 die "$error\n" if $error;
6337 #some false laziness w/cdr.pm now
6341 my $job = $param->{job};
6343 my $filename = $param->{file};
6344 my $type = $param->{type} || 'csv';
6346 my $custbatch = $param->{custbatch};
6348 my $agentnum = $param->{agentnum};
6349 my $refnum = $param->{refnum};
6350 my $pkgpart = $param->{pkgpart};
6352 my $format = $param->{'format'};
6356 if ( $format eq 'simple' ) {
6357 @fields = qw( cust_pkg.setup dayphone first last
6358 address1 address2 city state zip comments );
6360 } elsif ( $format eq 'extended' ) {
6361 @fields = qw( agent_custid refnum
6362 last first address1 address2 city state zip country
6364 ship_last ship_first ship_address1 ship_address2
6365 ship_city ship_state ship_zip ship_country
6366 payinfo paycvv paydate
6369 svc_acct.username svc_acct._password
6372 } elsif ( $format eq 'extended-plus_company' ) {
6373 @fields = qw( agent_custid refnum
6374 last first company address1 address2 city state zip country
6376 ship_last ship_first ship_company ship_address1 ship_address2
6377 ship_city ship_state ship_zip ship_country
6378 payinfo paycvv paydate
6381 svc_acct.username svc_acct._password
6385 die "unknown format $format";
6391 if ( $type eq 'csv' ) {
6393 eval "use Text::CSV_XS;";
6396 $parser = new Text::CSV_XS;
6398 @buffer = split(/\r?\n/, slurp($filename) );
6399 $count = scalar(@buffer);
6401 } elsif ( $type eq 'xls' ) {
6403 eval "use Spreadsheet::ParseExcel;";
6406 my $excel = new Spreadsheet::ParseExcel::Workbook->Parse($filename);
6407 $parser = $excel->{Worksheet}[0]; #first sheet
6409 $count = $parser->{MaxRow} || $parser->{MinRow};
6413 die "Unknown file type $type\n";
6418 local $SIG{HUP} = 'IGNORE';
6419 local $SIG{INT} = 'IGNORE';
6420 local $SIG{QUIT} = 'IGNORE';
6421 local $SIG{TERM} = 'IGNORE';
6422 local $SIG{TSTP} = 'IGNORE';
6423 local $SIG{PIPE} = 'IGNORE';
6425 my $oldAutoCommit = $FS::UID::AutoCommit;
6426 local $FS::UID::AutoCommit = 0;
6431 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
6435 if ( $type eq 'csv' ) {
6437 last unless scalar(@buffer);
6438 $line = shift(@buffer);
6440 $parser->parse($line) or do {
6441 $dbh->rollback if $oldAutoCommit;
6442 return "can't parse: ". $parser->error_input();
6444 @columns = $parser->fields();
6446 } elsif ( $type eq 'xls' ) {
6448 last if $row > ($parser->{MaxRow} || $parser->{MinRow});
6450 my @row = @{ $parser->{Cells}[$row] };
6451 @columns = map $_->{Val}, @row;
6454 #warn $z++. ": $_\n" for @columns;
6457 die "Unknown file type $type\n";
6460 #warn join('-',@columns);
6463 custbatch => $custbatch,
6464 agentnum => $agentnum,
6466 country => $conf->config('countrydefault') || 'US',
6467 payby => $payby, #default
6468 paydate => '12/2037', #default
6470 my $billtime = time;
6471 my %cust_pkg = ( pkgpart => $pkgpart );
6473 foreach my $field ( @fields ) {
6475 if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
6477 #$cust_pkg{$1} = str2time( shift @$columns );
6478 if ( $1 eq 'pkgpart' ) {
6479 $cust_pkg{$1} = shift @columns;
6480 } elsif ( $1 eq 'setup' ) {
6481 $billtime = str2time(shift @columns);
6483 $cust_pkg{$1} = str2time( shift @columns );
6486 } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
6488 $svc_acct{$1} = shift @columns;
6492 #refnum interception
6493 if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
6495 my $referral = $columns[0];
6496 my %hash = ( 'referral' => $referral,
6497 'agentnum' => $agentnum,
6501 my $part_referral = qsearchs('part_referral', \%hash )
6502 || new FS::part_referral \%hash;
6504 unless ( $part_referral->refnum ) {
6505 my $error = $part_referral->insert;
6507 $dbh->rollback if $oldAutoCommit;
6508 return "can't auto-insert advertising source: $referral: $error";
6512 $columns[0] = $part_referral->refnum;
6515 my $value = shift @columns;
6516 $cust_main{$field} = $value if length($value);
6520 $cust_main{'payby'} = 'CARD'
6521 if defined $cust_main{'payinfo'}
6522 && length $cust_main{'payinfo'};
6524 my $invoicing_list = $cust_main{'invoicing_list'}
6525 ? [ delete $cust_main{'invoicing_list'} ]
6528 my $cust_main = new FS::cust_main ( \%cust_main );
6531 tie my %hash, 'Tie::RefHash'; #this part is important
6533 if ( $cust_pkg{'pkgpart'} ) {
6534 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
6537 if ( $svc_acct{'username'} ) {
6538 my $part_pkg = $cust_pkg->part_pkg;
6539 unless ( $part_pkg ) {
6540 $dbh->rollback if $oldAutoCommit;
6541 return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
6543 $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
6544 push @svc_acct, new FS::svc_acct ( \%svc_acct )
6547 $hash{$cust_pkg} = \@svc_acct;
6550 my $error = $cust_main->insert( \%hash, $invoicing_list );
6553 $dbh->rollback if $oldAutoCommit;
6554 return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
6557 if ( $format eq 'simple' ) {
6559 #false laziness w/bill.cgi
6560 $error = $cust_main->bill( 'time' => $billtime );
6562 $dbh->rollback if $oldAutoCommit;
6563 return "can't bill customer for $line: $error";
6566 $error = $cust_main->apply_payments_and_credits;
6568 $dbh->rollback if $oldAutoCommit;
6569 return "can't bill customer for $line: $error";
6572 $error = $cust_main->collect();
6574 $dbh->rollback if $oldAutoCommit;
6575 return "can't collect customer for $line: $error";
6582 if ( $job && time - $min_sec > $last ) { #progress bar
6583 $job->update_statustext( int(100 * $row / $count) );
6589 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
6591 return "Empty file!" unless $row;
6603 #warn join('-',keys %$param);
6604 my $fh = $param->{filehandle};
6605 my @fields = @{$param->{fields}};
6607 eval "use Text::CSV_XS;";
6610 my $csv = new Text::CSV_XS;
6617 local $SIG{HUP} = 'IGNORE';
6618 local $SIG{INT} = 'IGNORE';
6619 local $SIG{QUIT} = 'IGNORE';
6620 local $SIG{TERM} = 'IGNORE';
6621 local $SIG{TSTP} = 'IGNORE';
6622 local $SIG{PIPE} = 'IGNORE';
6624 my $oldAutoCommit = $FS::UID::AutoCommit;
6625 local $FS::UID::AutoCommit = 0;
6628 #while ( $columns = $csv->getline($fh) ) {
6630 while ( defined($line=<$fh>) ) {
6632 $csv->parse($line) or do {
6633 $dbh->rollback if $oldAutoCommit;
6634 return "can't parse: ". $csv->error_input();
6637 my @columns = $csv->fields();
6638 #warn join('-',@columns);
6641 foreach my $field ( @fields ) {
6642 $row{$field} = shift @columns;
6645 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6646 unless ( $cust_main ) {
6647 $dbh->rollback if $oldAutoCommit;
6648 return "unknown custnum $row{'custnum'}";
6651 if ( $row{'amount'} > 0 ) {
6652 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6654 $dbh->rollback if $oldAutoCommit;
6658 } elsif ( $row{'amount'} < 0 ) {
6659 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6662 $dbh->rollback if $oldAutoCommit;
6672 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6674 return "Empty file!" unless $imported;
6680 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6682 Sends a templated email notification to the customer (see L<Text::Template>).
6684 OPTIONS is a hash and may include
6686 I<from> - the email sender (default is invoice_from)
6688 I<to> - comma-separated scalar or arrayref of recipients
6689 (default is invoicing_list)
6691 I<subject> - The subject line of the sent email notification
6692 (default is "Notice from company_name")
6694 I<extra_fields> - a hashref of name/value pairs which will be substituted
6697 The following variables are vavailable in the template.
6699 I<$first> - the customer first name
6700 I<$last> - the customer last name
6701 I<$company> - the customer company
6702 I<$payby> - a description of the method of payment for the customer
6703 # would be nice to use FS::payby::shortname
6704 I<$payinfo> - the account information used to collect for this customer
6705 I<$expdate> - the expiration of the customer payment in seconds from epoch
6710 my ($customer, $template, %options) = @_;
6712 return unless $conf->exists($template);
6714 my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6715 $from = $options{from} if exists($options{from});
6717 my $to = join(',', $customer->invoicing_list_emailonly);
6718 $to = $options{to} if exists($options{to});
6720 my $subject = "Notice from " . $conf->config('company_name')
6721 if $conf->exists('company_name');
6722 $subject = $options{subject} if exists($options{subject});
6724 my $notify_template = new Text::Template (TYPE => 'ARRAY',
6725 SOURCE => [ map "$_\n",
6726 $conf->config($template)]
6728 or die "can't create new Text::Template object: Text::Template::ERROR";
6729 $notify_template->compile()
6730 or die "can't compile template: Text::Template::ERROR";
6732 $FS::notify_template::_template::company_name = $conf->config('company_name');
6733 $FS::notify_template::_template::company_address =
6734 join("\n", $conf->config('company_address') ). "\n";
6736 my $paydate = $customer->paydate || '2037-12-31';
6737 $FS::notify_template::_template::first = $customer->first;
6738 $FS::notify_template::_template::last = $customer->last;
6739 $FS::notify_template::_template::company = $customer->company;
6740 $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6741 my $payby = $customer->payby;
6742 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6743 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6745 #credit cards expire at the end of the month/year of their exp date
6746 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6747 $FS::notify_template::_template::payby = 'credit card';
6748 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6749 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6751 }elsif ($payby eq 'COMP') {
6752 $FS::notify_template::_template::payby = 'complimentary account';
6754 $FS::notify_template::_template::payby = 'current method';
6756 $FS::notify_template::_template::expdate = $expire_time;
6758 for (keys %{$options{extra_fields}}){
6760 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6763 send_email(from => $from,
6765 subject => $subject,
6766 body => $notify_template->fill_in( PACKAGE =>
6767 'FS::notify_template::_template' ),
6772 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6774 Generates a templated notification to the customer (see L<Text::Template>).
6776 OPTIONS is a hash and may include
6778 I<extra_fields> - a hashref of name/value pairs which will be substituted
6779 into the template. These values may override values mentioned below
6780 and those from the customer record.
6782 The following variables are available in the template instead of or in addition
6783 to the fields of the customer record.
6785 I<$payby> - a description of the method of payment for the customer
6786 # would be nice to use FS::payby::shortname
6787 I<$payinfo> - the masked account information used to collect for this customer
6788 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6789 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6793 sub generate_letter {
6794 my ($self, $template, %options) = @_;
6796 return unless $conf->exists($template);
6798 my $letter_template = new Text::Template
6800 SOURCE => [ map "$_\n", $conf->config($template)],
6801 DELIMITERS => [ '[@--', '--@]' ],
6803 or die "can't create new Text::Template object: Text::Template::ERROR";
6805 $letter_template->compile()
6806 or die "can't compile template: Text::Template::ERROR";
6808 my %letter_data = map { $_ => $self->$_ } $self->fields;
6809 $letter_data{payinfo} = $self->mask_payinfo;
6811 #my $paydate = $self->paydate || '2037-12-31';
6812 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6814 my $payby = $self->payby;
6815 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6816 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6818 #credit cards expire at the end of the month/year of their exp date
6819 if ($payby eq 'CARD' || $payby eq 'DCRD') {
6820 $letter_data{payby} = 'credit card';
6821 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6822 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6824 }elsif ($payby eq 'COMP') {
6825 $letter_data{payby} = 'complimentary account';
6827 $letter_data{payby} = 'current method';
6829 $letter_data{expdate} = $expire_time;
6831 for (keys %{$options{extra_fields}}){
6832 $letter_data{$_} = $options{extra_fields}->{$_};
6835 unless(exists($letter_data{returnaddress})){
6836 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6837 $self->agent_template)
6839 if ( length($retadd) ) {
6840 $letter_data{returnaddress} = $retadd;
6841 } elsif ( grep /\S/, $conf->config('company_address') ) {
6842 $letter_data{returnaddress} =
6843 join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6844 $conf->config('company_address')
6847 $letter_data{returnaddress} = '~';
6851 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6853 $letter_data{company_name} = $conf->config('company_name');
6855 my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6856 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6860 ) or die "can't open temp file: $!\n";
6862 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6864 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6868 =item print_ps TEMPLATE
6870 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6876 my $file = $self->generate_letter(@_);
6877 FS::Misc::generate_ps($file);
6880 =item print TEMPLATE
6882 Prints the filled in template.
6884 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6888 sub queueable_print {
6891 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6892 or die "invalid customer number: " . $opt{custvnum};
6894 my $error = $self->print( $opt{template} );
6895 die $error if $error;
6899 my ($self, $template) = (shift, shift);
6900 do_print [ $self->print_ps($template) ];
6903 sub agent_template {
6905 $self->_agent_plandata('agent_templatename');
6908 sub agent_invoice_from {
6910 $self->_agent_plandata('agent_invoice_from');
6913 sub _agent_plandata {
6914 my( $self, $option ) = @_;
6916 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
6917 #agent-specific Conf
6919 use FS::part_event::Condition;
6921 my $agentnum = $self->agentnum;
6924 if ( driver_name =~ /^Pg/i ) {
6926 } elsif ( driver_name =~ /^mysql/i ) {
6929 die "don't know how to use regular expressions in ". driver_name. " databases";
6932 my $part_event_option =
6934 'select' => 'part_event_option.*',
6935 'table' => 'part_event_option',
6937 LEFT JOIN part_event USING ( eventpart )
6938 LEFT JOIN part_event_option AS peo_agentnum
6939 ON ( part_event.eventpart = peo_agentnum.eventpart
6940 AND peo_agentnum.optionname = 'agentnum'
6941 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6943 LEFT JOIN part_event_option AS peo_cust_bill_age
6944 ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6945 AND peo_cust_bill_age.optionname = 'cust_bill_age'
6948 #'hashref' => { 'optionname' => $option },
6949 #'hashref' => { 'part_event_option.optionname' => $option },
6951 " WHERE part_event_option.optionname = ". dbh->quote($option).
6952 " AND action = 'cust_bill_send_agent' ".
6953 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6954 " AND peo_agentnum.optionname = 'agentnum' ".
6955 " AND agentnum IS NULL OR agentnum = $agentnum ".
6957 CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6959 ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6961 , part_event.weight".
6965 unless ( $part_event_option ) {
6966 return $self->agent->invoice_template || ''
6967 if $option eq 'agent_templatename';
6971 $part_event_option->optionvalue;
6976 ## actual sub, not a method, designed to be called from the queue.
6977 ## sets up the customer, and calls the bill_and_collect
6978 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6979 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6980 $cust_main->bill_and_collect(
6991 The delete method should possibly take an FS::cust_main object reference
6992 instead of a scalar customer number.
6994 Bill and collect options should probably be passed as references instead of a
6997 There should probably be a configuration file with a list of allowed credit
7000 No multiple currency support (probably a larger project than just this module).
7002 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
7004 Birthdates rely on negative epoch values.
7006 The payby for card/check batches is broken. With mixed batching, bad
7009 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
7013 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
7014 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
7015 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.