5 use base qw( FS::cust_main::Billing FS::cust_main::Billing_Realtime
6 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
9 use vars qw( $DEBUG $me $conf
11 $import $ignore_expired_card $ignore_illegal_zip
12 $skip_fuzzyfiles @fuzzyfields
15 use vars qw( $realtime_bop_decline_quiet ); #ugh
17 use Scalar::Util qw( blessed );
18 use List::Util qw( min );
19 use Time::Local qw(timelocal);
20 use Storable qw(thaw);
24 use Digest::MD5 qw(md5_base64);
27 use File::Temp qw( tempfile );
28 use Business::CreditCard 0.28;
30 use FS::UID qw( getotaker dbh driver_name );
31 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
32 use FS::Misc qw( generate_email send_email generate_ps do_print );
33 use FS::Msgcat qw(gettext);
40 use FS::cust_pay_pending;
41 use FS::cust_pay_void;
42 use FS::cust_pay_batch;
45 use FS::part_referral;
46 use FS::cust_main_county;
47 use FS::cust_location;
49 use FS::cust_main_exemption;
50 use FS::cust_tax_adjustment;
51 use FS::cust_tax_location;
53 use FS::cust_main_invoice;
55 use FS::prepay_credit;
59 use FS::part_event_condition;
63 use FS::payment_gateway;
64 use FS::agent_payment_gateway;
68 $realtime_bop_decline_quiet = 0; #move to Billing_Realtime
70 # 1 is mostly method/subroutine entry and options
71 # 2 traces progress of some operations
72 # 3 is even more information including possibly sensitive data
74 $me = '[FS::cust_main]';
77 $ignore_expired_card = 0;
78 $ignore_illegal_zip = 0;
81 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
83 @encrypted_fields = ('payinfo', 'paycvv');
84 sub nohistory_fields { ('payinfo', 'paycvv'); }
86 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
88 #ask FS::UID to run this stuff for us later
89 #$FS::UID::callback{'FS::cust_main'} = sub {
90 install_callback FS::UID sub {
92 #yes, need it for stuff below (prolly should be cached)
97 my ( $hashref, $cache ) = @_;
98 if ( exists $hashref->{'pkgnum'} ) {
99 #@{ $self->{'_pkgnum'} } = ();
100 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
101 $self->{'_pkgnum'} = $subcache;
102 #push @{ $self->{'_pkgnum'} },
103 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
109 FS::cust_main - Object methods for cust_main records
115 $record = new FS::cust_main \%hash;
116 $record = new FS::cust_main { 'column' => 'value' };
118 $error = $record->insert;
120 $error = $new_record->replace($old_record);
122 $error = $record->delete;
124 $error = $record->check;
126 @cust_pkg = $record->all_pkgs;
128 @cust_pkg = $record->ncancelled_pkgs;
130 @cust_pkg = $record->suspended_pkgs;
132 $error = $record->bill;
133 $error = $record->bill %options;
134 $error = $record->bill 'time' => $time;
136 $error = $record->collect;
137 $error = $record->collect %options;
138 $error = $record->collect 'invoice_time' => $time,
143 An FS::cust_main object represents a customer. FS::cust_main inherits from
144 FS::Record. The following fields are currently supported:
150 Primary key (assigned automatically for new customers)
154 Agent (see L<FS::agent>)
158 Advertising source (see L<FS::part_referral>)
170 Cocial security number (optional)
186 (optional, see L<FS::cust_main_county>)
190 (see L<FS::cust_main_county>)
196 (see L<FS::cust_main_county>)
232 (optional, see L<FS::cust_main_county>)
236 (see L<FS::cust_main_county>)
242 (see L<FS::cust_main_county>)
258 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
262 Payment Information (See L<FS::payinfo_Mixin> for data format)
266 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
270 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
274 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
278 Start date month (maestro/solo cards only)
282 Start date year (maestro/solo cards only)
286 Issue number (maestro/solo cards only)
290 Name on card or billing name
294 IP address from which payment information was received
298 Tax exempt, empty or `Y'
302 Order taker (see L<FS::access_user>)
308 =item referral_custnum
310 Referring customer number
314 Enable individual CDR spooling, empty or `Y'
318 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
322 Discourage individual CDR printing, empty or `Y'
332 Creates a new customer. To add the customer to the database, see L<"insert">.
334 Note that this stores the hash reference, not a distinct copy of the hash it
335 points to. You can ask the object for a copy with the I<hash> method.
339 sub table { 'cust_main'; }
341 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
343 Adds this customer to the database. If there is an error, returns the error,
344 otherwise returns false.
346 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
347 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
348 are inserted atomicly, or the transaction is rolled back. Passing an empty
349 hash reference is equivalent to not supplying this parameter. There should be
350 a better explanation of this, but until then, here's an example:
353 tie %hash, 'Tie::RefHash'; #this part is important
355 $cust_pkg => [ $svc_acct ],
358 $cust_main->insert( \%hash );
360 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
361 be set as the invoicing list (see L<"invoicing_list">). Errors return as
362 expected and rollback the entire transaction; it is not necessary to call
363 check_invoicing_list first. The invoicing_list is set after the records in the
364 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
365 invoicing_list destination to the newly-created svc_acct. Here's an example:
367 $cust_main->insert( {}, [ $email, 'POST' ] );
369 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
371 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
372 on the supplied jobnum (they will not run until the specific job completes).
373 This can be used to defer provisioning until some action completes (such
374 as running the customer's credit card successfully).
376 The I<noexport> option is deprecated. If I<noexport> is set true, no
377 provisioning jobs (exports) are scheduled. (You can schedule them later with
378 the B<reexport> method.)
380 The I<tax_exemption> option can be set to an arrayref of tax names.
381 FS::cust_main_exemption records will be created and inserted.
387 my $cust_pkgs = @_ ? shift : {};
388 my $invoicing_list = @_ ? shift : '';
390 warn "$me insert called with options ".
391 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
394 local $SIG{HUP} = 'IGNORE';
395 local $SIG{INT} = 'IGNORE';
396 local $SIG{QUIT} = 'IGNORE';
397 local $SIG{TERM} = 'IGNORE';
398 local $SIG{TSTP} = 'IGNORE';
399 local $SIG{PIPE} = 'IGNORE';
401 my $oldAutoCommit = $FS::UID::AutoCommit;
402 local $FS::UID::AutoCommit = 0;
405 my $prepay_identifier = '';
406 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
408 if ( $self->payby eq 'PREPAY' ) {
410 $self->payby('BILL');
411 $prepay_identifier = $self->payinfo;
414 warn " looking up prepaid card $prepay_identifier\n"
417 my $error = $self->get_prepay( $prepay_identifier,
418 'amount_ref' => \$amount,
419 'seconds_ref' => \$seconds,
420 'upbytes_ref' => \$upbytes,
421 'downbytes_ref' => \$downbytes,
422 'totalbytes_ref' => \$totalbytes,
425 $dbh->rollback if $oldAutoCommit;
426 #return "error applying prepaid card (transaction rolled back): $error";
430 $payby = 'PREP' if $amount;
432 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
435 $self->payby('BILL');
436 $amount = $self->paid;
440 warn " inserting $self\n"
443 $self->signupdate(time) unless $self->signupdate;
445 $self->auto_agent_custid()
446 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
448 my $error = $self->SUPER::insert;
450 $dbh->rollback if $oldAutoCommit;
451 #return "inserting cust_main record (transaction rolled back): $error";
455 warn " setting invoicing list\n"
458 if ( $invoicing_list ) {
459 $error = $self->check_invoicing_list( $invoicing_list );
461 $dbh->rollback if $oldAutoCommit;
462 #return "checking invoicing_list (transaction rolled back): $error";
465 $self->invoicing_list( $invoicing_list );
468 warn " setting customer tags\n"
471 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
472 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
473 'custnum' => $self->custnum };
474 my $error = $cust_tag->insert;
476 $dbh->rollback if $oldAutoCommit;
481 if ( $invoicing_list ) {
482 $error = $self->check_invoicing_list( $invoicing_list );
484 $dbh->rollback if $oldAutoCommit;
485 #return "checking invoicing_list (transaction rolled back): $error";
488 $self->invoicing_list( $invoicing_list );
492 warn " setting cust_main_exemption\n"
495 my $tax_exemption = delete $options{'tax_exemption'};
496 if ( $tax_exemption ) {
497 foreach my $taxname ( @$tax_exemption ) {
498 my $cust_main_exemption = new FS::cust_main_exemption {
499 'custnum' => $self->custnum,
500 'taxname' => $taxname,
502 my $error = $cust_main_exemption->insert;
504 $dbh->rollback if $oldAutoCommit;
505 return "inserting cust_main_exemption (transaction rolled back): $error";
510 if ( $conf->config('cust_main-skeleton_tables')
511 && $conf->config('cust_main-skeleton_custnum') ) {
513 warn " inserting skeleton records\n"
516 my $error = $self->start_copy_skel;
518 $dbh->rollback if $oldAutoCommit;
524 warn " ordering packages\n"
527 $error = $self->order_pkgs( $cust_pkgs,
529 'seconds_ref' => \$seconds,
530 'upbytes_ref' => \$upbytes,
531 'downbytes_ref' => \$downbytes,
532 'totalbytes_ref' => \$totalbytes,
535 $dbh->rollback if $oldAutoCommit;
540 $dbh->rollback if $oldAutoCommit;
541 return "No svc_acct record to apply pre-paid time";
543 if ( $upbytes || $downbytes || $totalbytes ) {
544 $dbh->rollback if $oldAutoCommit;
545 return "No svc_acct record to apply pre-paid data";
549 warn " inserting initial $payby payment of $amount\n"
551 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
553 $dbh->rollback if $oldAutoCommit;
554 return "inserting payment (transaction rolled back): $error";
558 unless ( $import || $skip_fuzzyfiles ) {
559 warn " queueing fuzzyfiles update\n"
561 $error = $self->queue_fuzzyfiles_update;
563 $dbh->rollback if $oldAutoCommit;
564 return "updating fuzzy search cache: $error";
569 warn " exporting\n" if $DEBUG > 1;
571 my $export_args = $options{'export_args'} || [];
574 map qsearch( 'part_export', {exportnum=>$_} ),
575 $conf->config('cust_main-exports'); #, $agentnum
577 foreach my $part_export ( @part_export ) {
578 my $error = $part_export->export_insert($self, @$export_args);
580 $dbh->rollback if $oldAutoCommit;
581 return "exporting to ". $part_export->exporttype.
582 " (transaction rolled back): $error";
586 #foreach my $depend_jobnum ( @$depend_jobnums ) {
587 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
589 # foreach my $jobnum ( @jobnums ) {
590 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
591 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
593 # my $error = $queue->depend_insert($depend_jobnum);
595 # $dbh->rollback if $oldAutoCommit;
596 # return "error queuing job dependancy: $error";
603 #if ( exists $options{'jobnums'} ) {
604 # push @{ $options{'jobnums'} }, @jobnums;
607 warn " insert complete; committing transaction\n"
610 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
615 use File::CounterFile;
616 sub auto_agent_custid {
619 my $format = $conf->config('cust_main-auto_agent_custid');
621 if ( $format eq '1YMMXXXXXXXX' ) {
623 my $counter = new File::CounterFile 'cust_main.agent_custid';
626 my $ym = 100000000000 + time2str('%y%m00000000', time);
627 if ( $ym > $counter->value ) {
628 $counter->{'value'} = $agent_custid = $ym;
629 $counter->{'updated'} = 1;
631 $agent_custid = $counter->inc;
637 die "Unknown cust_main-auto_agent_custid format: $format";
640 $self->agent_custid($agent_custid);
644 sub start_copy_skel {
647 #'mg_user_preference' => {},
648 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
649 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
650 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
651 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
652 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
655 _copy_skel( 'cust_main', #tablename
656 $conf->config('cust_main-skeleton_custnum'), #sourceid
657 $self->custnum, #destid
658 @tables, #child tables
662 #recursive subroutine, not a method
664 my( $table, $sourceid, $destid, %child_tables ) = @_;
667 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
668 ( $table, $primary_key ) = ( $1, $2 );
670 my $dbdef_table = dbdef->table($table);
671 $primary_key = $dbdef_table->primary_key
672 or return "$table has no primary key".
673 " (or do you need to run dbdef-create?)";
676 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
677 join (', ', keys %child_tables). "\n"
680 foreach my $child_table_def ( keys %child_tables ) {
684 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
685 ( $child_table, $child_pkey ) = ( $1, $2 );
687 $child_table = $child_table_def;
689 $child_pkey = dbdef->table($child_table)->primary_key;
690 # or return "$table has no primary key".
691 # " (or do you need to run dbdef-create?)\n";
695 if ( keys %{ $child_tables{$child_table_def} } ) {
697 return "$child_table has no primary key".
698 " (run dbdef-create or try specifying it?)\n"
701 #false laziness w/Record::insert and only works on Pg
702 #refactor the proper last-inserted-id stuff out of Record::insert if this
703 # ever gets use for anything besides a quick kludge for one customer
704 my $default = dbdef->table($child_table)->column($child_pkey)->default;
705 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
706 or return "can't parse $child_table.$child_pkey default value ".
707 " for sequence name: $default";
712 my @sel_columns = grep { $_ ne $primary_key }
713 dbdef->table($child_table)->columns;
714 my $sel_columns = join(', ', @sel_columns );
716 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
717 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
718 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
720 my $sel_st = "SELECT $sel_columns FROM $child_table".
721 " WHERE $primary_key = $sourceid";
724 my $sel_sth = dbh->prepare( $sel_st )
725 or return dbh->errstr;
727 $sel_sth->execute or return $sel_sth->errstr;
729 while ( my $row = $sel_sth->fetchrow_hashref ) {
731 warn " selected row: ".
732 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
736 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
737 my $ins_sth =dbh->prepare($statement)
738 or return dbh->errstr;
739 my @param = ( $destid, map $row->{$_}, @ins_columns );
740 warn " $statement: [ ". join(', ', @param). " ]\n"
742 $ins_sth->execute( @param )
743 or return $ins_sth->errstr;
745 #next unless keys %{ $child_tables{$child_table} };
746 next unless $sequence;
748 #another section of that laziness
749 my $seq_sql = "SELECT currval('$sequence')";
750 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
751 $seq_sth->execute or return $seq_sth->errstr;
752 my $insertid = $seq_sth->fetchrow_arrayref->[0];
754 # don't drink soap! recurse! recurse! okay!
756 _copy_skel( $child_table_def,
757 $row->{$child_pkey}, #sourceid
759 %{ $child_tables{$child_table_def} },
761 return $error if $error;
771 =item order_pkg HASHREF | OPTION => VALUE ...
773 Orders a single package.
775 Options may be passed as a list of key/value pairs or as a hash reference.
786 Optional FS::cust_location object
790 Optional arryaref of FS::svc_* service objects.
794 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
795 jobs will have a dependancy on the supplied job (they will not run until the
796 specific job completes). This can be used to defer provisioning until some
797 action completes (such as running the customer's credit card successfully).
801 Optional subject for a ticket created and attached to this customer
805 Optional queue name for ticket additions
813 my $opt = ref($_[0]) ? shift : { @_ };
815 warn "$me order_pkg called with options ".
816 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
819 my $cust_pkg = $opt->{'cust_pkg'};
820 my $svcs = $opt->{'svcs'} || [];
822 my %svc_options = ();
823 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
824 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
826 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
827 qw( ticket_subject ticket_queue );
829 local $SIG{HUP} = 'IGNORE';
830 local $SIG{INT} = 'IGNORE';
831 local $SIG{QUIT} = 'IGNORE';
832 local $SIG{TERM} = 'IGNORE';
833 local $SIG{TSTP} = 'IGNORE';
834 local $SIG{PIPE} = 'IGNORE';
836 my $oldAutoCommit = $FS::UID::AutoCommit;
837 local $FS::UID::AutoCommit = 0;
840 if ( $opt->{'cust_location'} &&
841 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
842 my $error = $opt->{'cust_location'}->insert;
844 $dbh->rollback if $oldAutoCommit;
845 return "inserting cust_location (transaction rolled back): $error";
847 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
850 $cust_pkg->custnum( $self->custnum );
852 my $error = $cust_pkg->insert( %insert_params );
854 $dbh->rollback if $oldAutoCommit;
855 return "inserting cust_pkg (transaction rolled back): $error";
858 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
859 if ( $svc_something->svcnum ) {
860 my $old_cust_svc = $svc_something->cust_svc;
861 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
862 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
863 $error = $new_cust_svc->replace($old_cust_svc);
865 $svc_something->pkgnum( $cust_pkg->pkgnum );
866 if ( $svc_something->isa('FS::svc_acct') ) {
867 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
868 qw( seconds upbytes downbytes totalbytes ) ) {
869 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
870 ${ $opt->{$_.'_ref'} } = 0;
873 $error = $svc_something->insert(%svc_options);
876 $dbh->rollback if $oldAutoCommit;
877 return "inserting svc_ (transaction rolled back): $error";
881 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
886 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
887 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
889 Like the insert method on an existing record, this method orders multiple
890 packages and included services atomicaly. Pass a Tie::RefHash data structure
891 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
892 There should be a better explanation of this, but until then, here's an
896 tie %hash, 'Tie::RefHash'; #this part is important
898 $cust_pkg => [ $svc_acct ],
901 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
903 Services can be new, in which case they are inserted, or existing unaudited
904 services, in which case they are linked to the newly-created package.
906 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
907 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
909 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
910 on the supplied jobnum (they will not run until the specific job completes).
911 This can be used to defer provisioning until some action completes (such
912 as running the customer's credit card successfully).
914 The I<noexport> option is deprecated. If I<noexport> is set true, no
915 provisioning jobs (exports) are scheduled. (You can schedule them later with
916 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
917 on the cust_main object is not recommended, as existing services will also be
920 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
921 provided, the scalars (provided by references) will be incremented by the
922 values of the prepaid card.`
928 my $cust_pkgs = shift;
929 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
931 $seconds_ref ||= $options{'seconds_ref'};
933 warn "$me order_pkgs called with options ".
934 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
937 local $SIG{HUP} = 'IGNORE';
938 local $SIG{INT} = 'IGNORE';
939 local $SIG{QUIT} = 'IGNORE';
940 local $SIG{TERM} = 'IGNORE';
941 local $SIG{TSTP} = 'IGNORE';
942 local $SIG{PIPE} = 'IGNORE';
944 my $oldAutoCommit = $FS::UID::AutoCommit;
945 local $FS::UID::AutoCommit = 0;
948 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
950 foreach my $cust_pkg ( keys %$cust_pkgs ) {
952 my $error = $self->order_pkg(
953 'cust_pkg' => $cust_pkg,
954 'svcs' => $cust_pkgs->{$cust_pkg},
955 'seconds_ref' => $seconds_ref,
956 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
961 $dbh->rollback if $oldAutoCommit;
967 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
971 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
973 Recharges this (existing) customer with the specified prepaid card (see
974 L<FS::prepay_credit>), specified either by I<identifier> or as an
975 FS::prepay_credit object. If there is an error, returns the error, otherwise
978 Optionally, five scalar references can be passed as well. They will have their
979 values filled in with the amount, number of seconds, and number of upload,
980 download, and total bytes applied by this prepaid card.
984 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
985 #the only place that uses these args
986 sub recharge_prepay {
987 my( $self, $prepay_credit, $amountref, $secondsref,
988 $upbytesref, $downbytesref, $totalbytesref ) = @_;
990 local $SIG{HUP} = 'IGNORE';
991 local $SIG{INT} = 'IGNORE';
992 local $SIG{QUIT} = 'IGNORE';
993 local $SIG{TERM} = 'IGNORE';
994 local $SIG{TSTP} = 'IGNORE';
995 local $SIG{PIPE} = 'IGNORE';
997 my $oldAutoCommit = $FS::UID::AutoCommit;
998 local $FS::UID::AutoCommit = 0;
1001 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
1003 my $error = $self->get_prepay( $prepay_credit,
1004 'amount_ref' => \$amount,
1005 'seconds_ref' => \$seconds,
1006 'upbytes_ref' => \$upbytes,
1007 'downbytes_ref' => \$downbytes,
1008 'totalbytes_ref' => \$totalbytes,
1010 || $self->increment_seconds($seconds)
1011 || $self->increment_upbytes($upbytes)
1012 || $self->increment_downbytes($downbytes)
1013 || $self->increment_totalbytes($totalbytes)
1014 || $self->insert_cust_pay_prepay( $amount,
1016 ? $prepay_credit->identifier
1021 $dbh->rollback if $oldAutoCommit;
1025 if ( defined($amountref) ) { $$amountref = $amount; }
1026 if ( defined($secondsref) ) { $$secondsref = $seconds; }
1027 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1028 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1029 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1031 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1036 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1038 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1039 specified either by I<identifier> or as an FS::prepay_credit object.
1041 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>. The scalars (provided by references) will be
1042 incremented by the values of the prepaid card.
1044 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1045 check or set this customer's I<agentnum>.
1047 If there is an error, returns the error, otherwise returns false.
1053 my( $self, $prepay_credit, %opt ) = @_;
1055 local $SIG{HUP} = 'IGNORE';
1056 local $SIG{INT} = 'IGNORE';
1057 local $SIG{QUIT} = 'IGNORE';
1058 local $SIG{TERM} = 'IGNORE';
1059 local $SIG{TSTP} = 'IGNORE';
1060 local $SIG{PIPE} = 'IGNORE';
1062 my $oldAutoCommit = $FS::UID::AutoCommit;
1063 local $FS::UID::AutoCommit = 0;
1066 unless ( ref($prepay_credit) ) {
1068 my $identifier = $prepay_credit;
1070 $prepay_credit = qsearchs(
1072 { 'identifier' => $prepay_credit },
1077 unless ( $prepay_credit ) {
1078 $dbh->rollback if $oldAutoCommit;
1079 return "Invalid prepaid card: ". $identifier;
1084 if ( $prepay_credit->agentnum ) {
1085 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1086 $dbh->rollback if $oldAutoCommit;
1087 return "prepaid card not valid for agent ". $self->agentnum;
1089 $self->agentnum($prepay_credit->agentnum);
1092 my $error = $prepay_credit->delete;
1094 $dbh->rollback if $oldAutoCommit;
1095 return "removing prepay_credit (transaction rolled back): $error";
1098 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1099 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1101 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1106 =item increment_upbytes SECONDS
1108 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1109 the specified number of upbytes. If there is an error, returns the error,
1110 otherwise returns false.
1114 sub increment_upbytes {
1115 _increment_column( shift, 'upbytes', @_);
1118 =item increment_downbytes SECONDS
1120 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1121 the specified number of downbytes. If there is an error, returns the error,
1122 otherwise returns false.
1126 sub increment_downbytes {
1127 _increment_column( shift, 'downbytes', @_);
1130 =item increment_totalbytes SECONDS
1132 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1133 the specified number of totalbytes. If there is an error, returns the error,
1134 otherwise returns false.
1138 sub increment_totalbytes {
1139 _increment_column( shift, 'totalbytes', @_);
1142 =item increment_seconds SECONDS
1144 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1145 the specified number of seconds. If there is an error, returns the error,
1146 otherwise returns false.
1150 sub increment_seconds {
1151 _increment_column( shift, 'seconds', @_);
1154 =item _increment_column AMOUNT
1156 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1157 the specified number of seconds or bytes. If there is an error, returns
1158 the error, otherwise returns false.
1162 sub _increment_column {
1163 my( $self, $column, $amount ) = @_;
1164 warn "$me increment_column called: $column, $amount\n"
1167 return '' unless $amount;
1169 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1170 $self->ncancelled_pkgs;
1172 if ( ! @cust_pkg ) {
1173 return 'No packages with primary or single services found'.
1174 ' to apply pre-paid time';
1175 } elsif ( scalar(@cust_pkg) > 1 ) {
1176 #maybe have a way to specify the package/account?
1177 return 'Multiple packages found to apply pre-paid time';
1180 my $cust_pkg = $cust_pkg[0];
1181 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1185 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1187 if ( ! @cust_svc ) {
1188 return 'No account found to apply pre-paid time';
1189 } elsif ( scalar(@cust_svc) > 1 ) {
1190 return 'Multiple accounts found to apply pre-paid time';
1193 my $svc_acct = $cust_svc[0]->svc_x;
1194 warn " found service svcnum ". $svc_acct->pkgnum.
1195 ' ('. $svc_acct->email. ")\n"
1198 $column = "increment_$column";
1199 $svc_acct->$column($amount);
1203 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1205 Inserts a prepayment in the specified amount for this customer. An optional
1206 second argument can specify the prepayment identifier for tracking purposes.
1207 If there is an error, returns the error, otherwise returns false.
1211 sub insert_cust_pay_prepay {
1212 shift->insert_cust_pay('PREP', @_);
1215 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1217 Inserts a cash payment in the specified amount for this customer. An optional
1218 second argument can specify the payment identifier for tracking purposes.
1219 If there is an error, returns the error, otherwise returns false.
1223 sub insert_cust_pay_cash {
1224 shift->insert_cust_pay('CASH', @_);
1227 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1229 Inserts a Western Union payment in the specified amount for this customer. An
1230 optional second argument can specify the prepayment identifier for tracking
1231 purposes. If there is an error, returns the error, otherwise returns false.
1235 sub insert_cust_pay_west {
1236 shift->insert_cust_pay('WEST', @_);
1239 sub insert_cust_pay {
1240 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1241 my $payinfo = scalar(@_) ? shift : '';
1243 my $cust_pay = new FS::cust_pay {
1244 'custnum' => $self->custnum,
1245 'paid' => sprintf('%.2f', $amount),
1246 #'_date' => #date the prepaid card was purchased???
1248 'payinfo' => $payinfo,
1256 This method is deprecated. See the I<depend_jobnum> option to the insert and
1257 order_pkgs methods for a better way to defer provisioning.
1259 Re-schedules all exports by calling the B<reexport> method of all associated
1260 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1261 otherwise returns false.
1268 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1269 "use the depend_jobnum option to insert or order_pkgs to delay export";
1271 local $SIG{HUP} = 'IGNORE';
1272 local $SIG{INT} = 'IGNORE';
1273 local $SIG{QUIT} = 'IGNORE';
1274 local $SIG{TERM} = 'IGNORE';
1275 local $SIG{TSTP} = 'IGNORE';
1276 local $SIG{PIPE} = 'IGNORE';
1278 my $oldAutoCommit = $FS::UID::AutoCommit;
1279 local $FS::UID::AutoCommit = 0;
1282 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1283 my $error = $cust_pkg->reexport;
1285 $dbh->rollback if $oldAutoCommit;
1290 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1295 =item delete [ OPTION => VALUE ... ]
1297 This deletes the customer. If there is an error, returns the error, otherwise
1300 This will completely remove all traces of the customer record. This is not
1301 what you want when a customer cancels service; for that, cancel all of the
1302 customer's packages (see L</cancel>).
1304 If the customer has any uncancelled packages, you need to pass a new (valid)
1305 customer number for those packages to be transferred to, as the "new_customer"
1306 option. Cancelled packages will be deleted. Did I mention that this is NOT
1307 what you want when a customer cancels service and that you really should be
1308 looking at L<FS::cust_pkg/cancel>?
1310 You can't delete a customer with invoices (see L<FS::cust_bill>),
1311 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1312 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1313 set the "delete_financials" option to a true value.
1318 my( $self, %opt ) = @_;
1320 local $SIG{HUP} = 'IGNORE';
1321 local $SIG{INT} = 'IGNORE';
1322 local $SIG{QUIT} = 'IGNORE';
1323 local $SIG{TERM} = 'IGNORE';
1324 local $SIG{TSTP} = 'IGNORE';
1325 local $SIG{PIPE} = 'IGNORE';
1327 my $oldAutoCommit = $FS::UID::AutoCommit;
1328 local $FS::UID::AutoCommit = 0;
1331 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1332 $dbh->rollback if $oldAutoCommit;
1333 return "Can't delete a master agent customer";
1336 #use FS::access_user
1337 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1338 $dbh->rollback if $oldAutoCommit;
1339 return "Can't delete a master employee customer";
1342 tie my %financial_tables, 'Tie::IxHash',
1343 'cust_bill' => 'invoices',
1344 'cust_statement' => 'statements',
1345 'cust_credit' => 'credits',
1346 'cust_pay' => 'payments',
1347 'cust_refund' => 'refunds',
1350 foreach my $table ( keys %financial_tables ) {
1352 my @records = $self->$table();
1354 if ( @records && ! $opt{'delete_financials'} ) {
1355 $dbh->rollback if $oldAutoCommit;
1356 return "Can't delete a customer with ". $financial_tables{$table};
1359 foreach my $record ( @records ) {
1360 my $error = $record->delete;
1362 $dbh->rollback if $oldAutoCommit;
1363 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1369 my @cust_pkg = $self->ncancelled_pkgs;
1371 my $new_custnum = $opt{'new_custnum'};
1372 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1373 $dbh->rollback if $oldAutoCommit;
1374 return "Invalid new customer number: $new_custnum";
1376 foreach my $cust_pkg ( @cust_pkg ) {
1377 my %hash = $cust_pkg->hash;
1378 $hash{'custnum'} = $new_custnum;
1379 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1380 my $error = $new_cust_pkg->replace($cust_pkg,
1381 options => { $cust_pkg->options },
1384 $dbh->rollback if $oldAutoCommit;
1389 my @cancelled_cust_pkg = $self->all_pkgs;
1390 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1391 my $error = $cust_pkg->delete;
1393 $dbh->rollback if $oldAutoCommit;
1398 #cust_tax_adjustment in financials?
1399 #cust_pay_pending? ouch
1401 foreach my $table (qw(
1402 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1403 cust_location cust_main_note cust_tax_adjustment
1404 cust_pay_void cust_pay_batch queue cust_tax_exempt
1406 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1407 my $error = $record->delete;
1409 $dbh->rollback if $oldAutoCommit;
1415 my $sth = $dbh->prepare(
1416 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1418 my $errstr = $dbh->errstr;
1419 $dbh->rollback if $oldAutoCommit;
1422 $sth->execute($self->custnum) or do {
1423 my $errstr = $sth->errstr;
1424 $dbh->rollback if $oldAutoCommit;
1430 my $ticket_dbh = '';
1431 if ($conf->config('ticket_system') eq 'RT_Internal') {
1433 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1434 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1435 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1436 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1439 if ( $ticket_dbh ) {
1441 my $ticket_sth = $ticket_dbh->prepare(
1442 'DELETE FROM Links WHERE Target = ?'
1444 my $errstr = $ticket_dbh->errstr;
1445 $dbh->rollback if $oldAutoCommit;
1448 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1450 my $errstr = $ticket_sth->errstr;
1451 $dbh->rollback if $oldAutoCommit;
1455 #check and see if the customer is the only link on the ticket, and
1456 #if so, set the ticket to deleted status in RT?
1457 #maybe someday, for now this will at least fix tickets not displaying
1461 #delete the customer record
1463 my $error = $self->SUPER::delete;
1465 $dbh->rollback if $oldAutoCommit;
1469 # cust_main exports!
1471 #my $export_args = $options{'export_args'} || [];
1474 map qsearch( 'part_export', {exportnum=>$_} ),
1475 $conf->config('cust_main-exports'); #, $agentnum
1477 foreach my $part_export ( @part_export ) {
1478 my $error = $part_export->export_delete( $self ); #, @$export_args);
1480 $dbh->rollback if $oldAutoCommit;
1481 return "exporting to ". $part_export->exporttype.
1482 " (transaction rolled back): $error";
1486 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1491 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1494 Replaces the OLD_RECORD with this one in the database. If there is an error,
1495 returns the error, otherwise returns false.
1497 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1498 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1499 expected and rollback the entire transaction; it is not necessary to call
1500 check_invoicing_list first. Here's an example:
1502 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1504 Currently available options are: I<tax_exemption>.
1506 The I<tax_exemption> option can be set to an arrayref of tax names.
1507 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1514 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1516 : $self->replace_old;
1520 warn "$me replace called\n"
1523 my $curuser = $FS::CurrentUser::CurrentUser;
1524 if ( $self->payby eq 'COMP'
1525 && $self->payby ne $old->payby
1526 && ! $curuser->access_right('Complimentary customer')
1529 return "You are not permitted to create complimentary accounts.";
1532 local($ignore_expired_card) = 1
1533 if $old->payby =~ /^(CARD|DCRD)$/
1534 && $self->payby =~ /^(CARD|DCRD)$/
1535 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1537 local $SIG{HUP} = 'IGNORE';
1538 local $SIG{INT} = 'IGNORE';
1539 local $SIG{QUIT} = 'IGNORE';
1540 local $SIG{TERM} = 'IGNORE';
1541 local $SIG{TSTP} = 'IGNORE';
1542 local $SIG{PIPE} = 'IGNORE';
1544 my $oldAutoCommit = $FS::UID::AutoCommit;
1545 local $FS::UID::AutoCommit = 0;
1548 my $error = $self->SUPER::replace($old);
1551 $dbh->rollback if $oldAutoCommit;
1555 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1556 my $invoicing_list = shift @param;
1557 $error = $self->check_invoicing_list( $invoicing_list );
1559 $dbh->rollback if $oldAutoCommit;
1562 $self->invoicing_list( $invoicing_list );
1565 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1567 #this could be more efficient than deleting and re-inserting, if it matters
1568 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1569 my $error = $cust_tag->delete;
1571 $dbh->rollback if $oldAutoCommit;
1575 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1576 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1577 'custnum' => $self->custnum };
1578 my $error = $cust_tag->insert;
1580 $dbh->rollback if $oldAutoCommit;
1587 my %options = @param;
1589 my $tax_exemption = delete $options{'tax_exemption'};
1590 if ( $tax_exemption ) {
1592 my %cust_main_exemption =
1593 map { $_->taxname => $_ }
1594 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1596 foreach my $taxname ( @$tax_exemption ) {
1598 next if delete $cust_main_exemption{$taxname};
1600 my $cust_main_exemption = new FS::cust_main_exemption {
1601 'custnum' => $self->custnum,
1602 'taxname' => $taxname,
1604 my $error = $cust_main_exemption->insert;
1606 $dbh->rollback if $oldAutoCommit;
1607 return "inserting cust_main_exemption (transaction rolled back): $error";
1611 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1612 my $error = $cust_main_exemption->delete;
1614 $dbh->rollback if $oldAutoCommit;
1615 return "deleting cust_main_exemption (transaction rolled back): $error";
1621 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1622 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1623 && $self->get('payinfo') !~ /^99\d{14}$/
1625 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1630 # card/check/lec info has changed, want to retry realtime_ invoice events
1631 my $error = $self->retry_realtime;
1633 $dbh->rollback if $oldAutoCommit;
1638 unless ( $import || $skip_fuzzyfiles ) {
1639 $error = $self->queue_fuzzyfiles_update;
1641 $dbh->rollback if $oldAutoCommit;
1642 return "updating fuzzy search cache: $error";
1646 # cust_main exports!
1648 my $export_args = $options{'export_args'} || [];
1651 map qsearch( 'part_export', {exportnum=>$_} ),
1652 $conf->config('cust_main-exports'); #, $agentnum
1654 foreach my $part_export ( @part_export ) {
1655 my $error = $part_export->export_replace( $self, $old, @$export_args);
1657 $dbh->rollback if $oldAutoCommit;
1658 return "exporting to ". $part_export->exporttype.
1659 " (transaction rolled back): $error";
1663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1668 =item queue_fuzzyfiles_update
1670 Used by insert & replace to update the fuzzy search cache
1674 sub queue_fuzzyfiles_update {
1677 local $SIG{HUP} = 'IGNORE';
1678 local $SIG{INT} = 'IGNORE';
1679 local $SIG{QUIT} = 'IGNORE';
1680 local $SIG{TERM} = 'IGNORE';
1681 local $SIG{TSTP} = 'IGNORE';
1682 local $SIG{PIPE} = 'IGNORE';
1684 my $oldAutoCommit = $FS::UID::AutoCommit;
1685 local $FS::UID::AutoCommit = 0;
1688 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1689 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1691 $dbh->rollback if $oldAutoCommit;
1692 return "queueing job (transaction rolled back): $error";
1695 if ( $self->ship_last ) {
1696 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1697 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1699 $dbh->rollback if $oldAutoCommit;
1700 return "queueing job (transaction rolled back): $error";
1704 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1711 Checks all fields to make sure this is a valid customer record. If there is
1712 an error, returns the error, otherwise returns false. Called by the insert
1713 and replace methods.
1720 warn "$me check BEFORE: \n". $self->_dump
1724 $self->ut_numbern('custnum')
1725 || $self->ut_number('agentnum')
1726 || $self->ut_textn('agent_custid')
1727 || $self->ut_number('refnum')
1728 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1729 || $self->ut_textn('custbatch')
1730 || $self->ut_name('last')
1731 || $self->ut_name('first')
1732 || $self->ut_snumbern('birthdate')
1733 || $self->ut_snumbern('signupdate')
1734 || $self->ut_textn('company')
1735 || $self->ut_text('address1')
1736 || $self->ut_textn('address2')
1737 || $self->ut_text('city')
1738 || $self->ut_textn('county')
1739 || $self->ut_textn('state')
1740 || $self->ut_country('country')
1741 || $self->ut_anything('comments')
1742 || $self->ut_numbern('referral_custnum')
1743 || $self->ut_textn('stateid')
1744 || $self->ut_textn('stateid_state')
1745 || $self->ut_textn('invoice_terms')
1746 || $self->ut_alphan('geocode')
1747 || $self->ut_floatn('cdr_termination_percentage')
1750 #barf. need message catalogs. i18n. etc.
1751 $error .= "Please select an advertising source."
1752 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1753 return $error if $error;
1755 return "Unknown agent"
1756 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1758 return "Unknown refnum"
1759 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1761 return "Unknown referring custnum: ". $self->referral_custnum
1762 unless ! $self->referral_custnum
1763 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1765 if ( $self->censustract ne '' ) {
1766 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1767 or return "Illegal census tract: ". $self->censustract;
1769 $self->censustract("$1.$2");
1772 if ( $self->ss eq '' ) {
1777 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1778 or return "Illegal social security number: ". $self->ss;
1779 $self->ss("$1-$2-$3");
1783 # bad idea to disable, causes billing to fail because of no tax rates later
1784 # except we don't fail any more
1785 unless ( $import ) {
1786 unless ( qsearch('cust_main_county', {
1787 'country' => $self->country,
1790 return "Unknown state/county/country: ".
1791 $self->state. "/". $self->county. "/". $self->country
1792 unless qsearch('cust_main_county',{
1793 'state' => $self->state,
1794 'county' => $self->county,
1795 'country' => $self->country,
1801 $self->ut_phonen('daytime', $self->country)
1802 || $self->ut_phonen('night', $self->country)
1803 || $self->ut_phonen('fax', $self->country)
1805 return $error if $error;
1807 unless ( $ignore_illegal_zip ) {
1808 $error = $self->ut_zip('zip', $self->country);
1809 return $error if $error;
1812 if ( $conf->exists('cust_main-require_phone')
1813 && ! length($self->daytime) && ! length($self->night)
1816 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1818 : FS::Msgcat::_gettext('daytime');
1819 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1821 : FS::Msgcat::_gettext('night');
1823 return "$daytime_label or $night_label is required"
1827 if ( $self->has_ship_address
1828 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1829 $self->addr_fields )
1833 $self->ut_name('ship_last')
1834 || $self->ut_name('ship_first')
1835 || $self->ut_textn('ship_company')
1836 || $self->ut_text('ship_address1')
1837 || $self->ut_textn('ship_address2')
1838 || $self->ut_text('ship_city')
1839 || $self->ut_textn('ship_county')
1840 || $self->ut_textn('ship_state')
1841 || $self->ut_country('ship_country')
1843 return $error if $error;
1845 #false laziness with above
1846 unless ( qsearchs('cust_main_county', {
1847 'country' => $self->ship_country,
1850 return "Unknown ship_state/ship_county/ship_country: ".
1851 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1852 unless qsearch('cust_main_county',{
1853 'state' => $self->ship_state,
1854 'county' => $self->ship_county,
1855 'country' => $self->ship_country,
1861 $self->ut_phonen('ship_daytime', $self->ship_country)
1862 || $self->ut_phonen('ship_night', $self->ship_country)
1863 || $self->ut_phonen('ship_fax', $self->ship_country)
1865 return $error if $error;
1867 unless ( $ignore_illegal_zip ) {
1868 $error = $self->ut_zip('ship_zip', $self->ship_country);
1869 return $error if $error;
1871 return "Unit # is required."
1872 if $self->ship_address2 =~ /^\s*$/
1873 && $conf->exists('cust_main-require_address2');
1875 } else { # ship_ info eq billing info, so don't store dup info in database
1877 $self->setfield("ship_$_", '')
1878 foreach $self->addr_fields;
1880 return "Unit # is required."
1881 if $self->address2 =~ /^\s*$/
1882 && $conf->exists('cust_main-require_address2');
1886 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1887 # or return "Illegal payby: ". $self->payby;
1889 FS::payby->can_payby($self->table, $self->payby)
1890 or return "Illegal payby: ". $self->payby;
1892 $error = $self->ut_numbern('paystart_month')
1893 || $self->ut_numbern('paystart_year')
1894 || $self->ut_numbern('payissue')
1895 || $self->ut_textn('paytype')
1897 return $error if $error;
1899 if ( $self->payip eq '' ) {
1902 $error = $self->ut_ip('payip');
1903 return $error if $error;
1906 # If it is encrypted and the private key is not availaible then we can't
1907 # check the credit card.
1908 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1910 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1912 my $payinfo = $self->payinfo;
1913 $payinfo =~ s/\D//g;
1914 $payinfo =~ /^(\d{13,16})$/
1915 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1917 $self->payinfo($payinfo);
1919 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1921 return gettext('unknown_card_type')
1922 if $self->payinfo !~ /^99\d{14}$/ #token
1923 && cardtype($self->payinfo) eq "Unknown";
1925 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1927 return 'Banned credit card: banned on '.
1928 time2str('%a %h %o at %r', $ban->_date).
1929 ' by '. $ban->otaker.
1930 ' (ban# '. $ban->bannum. ')';
1933 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1934 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1935 $self->paycvv =~ /^(\d{4})$/
1936 or return "CVV2 (CID) for American Express cards is four digits.";
1939 $self->paycvv =~ /^(\d{3})$/
1940 or return "CVV2 (CVC2/CID) is three digits.";
1947 my $cardtype = cardtype($payinfo);
1948 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1950 return "Start date or issue number is required for $cardtype cards"
1951 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1953 return "Start month must be between 1 and 12"
1954 if $self->paystart_month
1955 and $self->paystart_month < 1 || $self->paystart_month > 12;
1957 return "Start year must be 1990 or later"
1958 if $self->paystart_year
1959 and $self->paystart_year < 1990;
1961 return "Issue number must be beween 1 and 99"
1963 and $self->payissue < 1 || $self->payissue > 99;
1966 $self->paystart_month('');
1967 $self->paystart_year('');
1968 $self->payissue('');
1971 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1973 my $payinfo = $self->payinfo;
1974 $payinfo =~ s/[^\d\@]//g;
1975 if ( $conf->exists('echeck-nonus') ) {
1976 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1977 $payinfo = "$1\@$2";
1979 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1980 $payinfo = "$1\@$2";
1982 $self->payinfo($payinfo);
1985 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1987 return 'Banned ACH account: banned on '.
1988 time2str('%a %h %o at %r', $ban->_date).
1989 ' by '. $ban->otaker.
1990 ' (ban# '. $ban->bannum. ')';
1993 } elsif ( $self->payby eq 'LECB' ) {
1995 my $payinfo = $self->payinfo;
1996 $payinfo =~ s/\D//g;
1997 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1999 $self->payinfo($payinfo);
2002 } elsif ( $self->payby eq 'BILL' ) {
2004 $error = $self->ut_textn('payinfo');
2005 return "Illegal P.O. number: ". $self->payinfo if $error;
2008 } elsif ( $self->payby eq 'COMP' ) {
2010 my $curuser = $FS::CurrentUser::CurrentUser;
2011 if ( ! $self->custnum
2012 && ! $curuser->access_right('Complimentary customer')
2015 return "You are not permitted to create complimentary accounts."
2018 $error = $self->ut_textn('payinfo');
2019 return "Illegal comp account issuer: ". $self->payinfo if $error;
2022 } elsif ( $self->payby eq 'PREPAY' ) {
2024 my $payinfo = $self->payinfo;
2025 $payinfo =~ s/\W//g; #anything else would just confuse things
2026 $self->payinfo($payinfo);
2027 $error = $self->ut_alpha('payinfo');
2028 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2029 return "Unknown prepayment identifier"
2030 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2035 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2036 return "Expiration date required"
2037 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2041 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2042 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2043 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2044 ( $m, $y ) = ( $2, "19$1" );
2045 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2046 ( $m, $y ) = ( $3, "20$2" );
2048 return "Illegal expiration date: ". $self->paydate;
2050 $self->paydate("$y-$m-01");
2051 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2052 return gettext('expired_card')
2054 && !$ignore_expired_card
2055 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2058 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2059 ( ! $conf->exists('require_cardname')
2060 || $self->payby !~ /^(CARD|DCRD)$/ )
2062 $self->payname( $self->first. " ". $self->getfield('last') );
2064 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2065 or return gettext('illegal_name'). " payname: ". $self->payname;
2069 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2070 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2074 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2076 warn "$me check AFTER: \n". $self->_dump
2079 $self->SUPER::check;
2084 Returns a list of fields which have ship_ duplicates.
2089 qw( last first company
2090 address1 address2 city county state zip country
2095 =item has_ship_address
2097 Returns true if this customer record has a separate shipping address.
2101 sub has_ship_address {
2103 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2108 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2109 city, county, state, zip, country. The shipping address is used if present.
2113 #geocode? dependent on tax-ship_address config, not available in cust_location
2114 #mostly. not yet then.
2118 my $prefix = $self->has_ship_address ? 'ship_' : '';
2120 map { $_ => $self->get($prefix.$_) }
2121 qw( address1 address2 city county state zip country geocode );
2122 #fields that cust_location has
2125 =item all_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2127 Returns all packages (see L<FS::cust_pkg>) for this customer.
2133 my $extra_qsearch = ref($_[0]) ? shift : {};
2135 return $self->num_pkgs unless wantarray || keys(%$extra_qsearch);
2138 if ( $self->{'_pkgnum'} ) {
2139 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2141 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2144 sort sort_packages @cust_pkg;
2149 Synonym for B<all_pkgs>.
2154 shift->all_pkgs(@_);
2159 Returns all locations (see L<FS::cust_location>) for this customer.
2165 qsearch('cust_location', { 'custnum' => $self->custnum } );
2168 =item location_label [ OPTION => VALUE ... ]
2170 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2178 used to separate the address elements (defaults to ', ')
2180 =item escape_function
2182 a callback used for escaping the text of the address elements
2188 # false laziness with FS::cust_location::line
2190 sub location_label {
2194 my $separator = $opt{join_string} || ', ';
2195 my $escape = $opt{escape_function} || sub{ shift };
2197 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2198 my $prefix = length($self->ship_last) ? 'ship_' : '';
2201 foreach (qw ( address1 address2 ) ) {
2202 my $method = "$prefix$_";
2203 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2208 foreach (qw ( city county state zip ) ) {
2209 my $method = "$prefix$_";
2210 if ( $self->$method ) {
2211 $line .= ' (' if $method eq 'county';
2212 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2213 $line .= ' )' if $method eq 'county';
2217 $line .= $separator. &$escape(code2country($self->country))
2218 if $self->country ne $cydefault;
2223 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2225 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2229 sub ncancelled_pkgs {
2231 my $extra_qsearch = ref($_[0]) ? shift : {};
2233 return $self->num_ncancelled_pkgs unless wantarray;
2236 if ( $self->{'_pkgnum'} ) {
2238 warn "$me ncancelled_pkgs: returning cached objects"
2241 @cust_pkg = grep { ! $_->getfield('cancel') }
2242 values %{ $self->{'_pkgnum'}->cache };
2246 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2247 $self->custnum. "\n"
2250 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2252 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2256 sort sort_packages @cust_pkg;
2262 my $extra_qsearch = ref($_[0]) ? shift : {};
2264 $extra_qsearch->{'select'} ||= '*';
2265 $extra_qsearch->{'select'} .=
2266 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2270 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2275 'table' => 'cust_pkg',
2276 'hashref' => { 'custnum' => $self->custnum },
2281 # This should be generalized to use config options to determine order.
2284 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2285 return $locationsort if $locationsort;
2287 if ( $a->get('cancel') xor $b->get('cancel') ) {
2288 return -1 if $b->get('cancel');
2289 return 1 if $a->get('cancel');
2290 #shouldn't get here...
2293 my $a_num_cust_svc = $a->num_cust_svc;
2294 my $b_num_cust_svc = $b->num_cust_svc;
2295 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2296 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2297 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2298 my @a_cust_svc = $a->cust_svc;
2299 my @b_cust_svc = $b->cust_svc;
2300 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2301 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2302 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
2303 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2308 =item suspended_pkgs
2310 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2314 sub suspended_pkgs {
2316 grep { $_->susp } $self->ncancelled_pkgs;
2319 =item unflagged_suspended_pkgs
2321 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2322 customer (thouse packages without the `manual_flag' set).
2326 sub unflagged_suspended_pkgs {
2328 return $self->suspended_pkgs
2329 unless dbdef->table('cust_pkg')->column('manual_flag');
2330 grep { ! $_->manual_flag } $self->suspended_pkgs;
2333 =item unsuspended_pkgs
2335 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2340 sub unsuspended_pkgs {
2342 grep { ! $_->susp } $self->ncancelled_pkgs;
2345 =item next_bill_date
2347 Returns the next date this customer will be billed, as a UNIX timestamp, or
2348 undef if no active package has a next bill date.
2352 sub next_bill_date {
2354 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2357 =item num_cancelled_pkgs
2359 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2364 sub num_cancelled_pkgs {
2365 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2368 sub num_ncancelled_pkgs {
2369 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2373 my( $self ) = shift;
2374 my $sql = scalar(@_) ? shift : '';
2375 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2376 my $sth = dbh->prepare(
2377 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2378 ) or die dbh->errstr;
2379 $sth->execute($self->custnum) or die $sth->errstr;
2380 $sth->fetchrow_arrayref->[0];
2385 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2386 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2387 on success or a list of errors.
2393 grep { $_->unsuspend } $self->suspended_pkgs;
2398 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2400 Returns a list: an empty list on success or a list of errors.
2406 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2409 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2411 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2412 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2413 of a list of pkgparts; the hashref has the following keys:
2417 =item pkgparts - listref of pkgparts
2419 =item (other options are passed to the suspend method)
2424 Returns a list: an empty list on success or a list of errors.
2428 sub suspend_if_pkgpart {
2430 my (@pkgparts, %opt);
2431 if (ref($_[0]) eq 'HASH'){
2432 @pkgparts = @{$_[0]{pkgparts}};
2437 grep { $_->suspend(%opt) }
2438 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2439 $self->unsuspended_pkgs;
2442 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2444 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2445 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2446 instead of a list of pkgparts; the hashref has the following keys:
2450 =item pkgparts - listref of pkgparts
2452 =item (other options are passed to the suspend method)
2456 Returns a list: an empty list on success or a list of errors.
2460 sub suspend_unless_pkgpart {
2462 my (@pkgparts, %opt);
2463 if (ref($_[0]) eq 'HASH'){
2464 @pkgparts = @{$_[0]{pkgparts}};
2469 grep { $_->suspend(%opt) }
2470 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2471 $self->unsuspended_pkgs;
2474 =item cancel [ OPTION => VALUE ... ]
2476 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2478 Available options are:
2482 =item quiet - can be set true to supress email cancellation notices.
2484 =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.
2486 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2488 =item nobill - can be set true to skip billing if it might otherwise be done.
2492 Always returns a list: an empty list on success or a list of errors.
2496 # nb that dates are not specified as valid options to this method
2499 my( $self, %opt ) = @_;
2501 warn "$me cancel called on customer ". $self->custnum. " with options ".
2502 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2505 return ( 'access denied' )
2506 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2508 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2510 #should try decryption (we might have the private key)
2511 # and if not maybe queue a job for the server that does?
2512 return ( "Can't (yet) ban encrypted credit cards" )
2513 if $self->is_encrypted($self->payinfo);
2515 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2516 my $error = $ban->insert;
2517 return ( $error ) if $error;
2521 my @pkgs = $self->ncancelled_pkgs;
2523 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2525 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2526 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2530 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2531 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2534 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2537 sub _banned_pay_hashref {
2548 'payby' => $payby2ban{$self->payby},
2549 'payinfo' => md5_base64($self->payinfo),
2550 #don't ever *search* on reason! #'reason' =>
2556 Returns all notes (see L<FS::cust_main_note>) for this customer.
2563 qsearch( 'cust_main_note',
2564 { 'custnum' => $self->custnum },
2566 'ORDER BY _DATE DESC'
2572 Returns the agent (see L<FS::agent>) for this customer.
2578 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2583 Returns the agent name (see L<FS::agent>) for this customer.
2589 $self->agent->agent;
2594 Returns any tags associated with this customer, as FS::cust_tag objects,
2595 or an empty list if there are no tags.
2601 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2606 Returns any tags associated with this customer, as FS::part_tag objects,
2607 or an empty list if there are no tags.
2613 map $_->part_tag, $self->cust_tag;
2619 Returns the customer class, as an FS::cust_class object, or the empty string
2620 if there is no customer class.
2626 if ( $self->classnum ) {
2627 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2635 Returns the customer category name, or the empty string if there is no customer
2642 my $cust_class = $self->cust_class;
2644 ? $cust_class->categoryname
2650 Returns the customer class name, or the empty string if there is no customer
2657 my $cust_class = $self->cust_class;
2659 ? $cust_class->classname
2663 =item BILLING METHODS
2665 Documentation on billing methods has been moved to
2666 L<FS::cust_main::Billing>.
2668 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
2670 Runs billing events; see L<FS::part_event> and the billing events web
2673 If there is an error, returns the error, otherwise returns false.
2675 Options are passed as name-value pairs.
2677 Currently available options are:
2683 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.
2687 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2691 "collect" (the default) or "pre-bill"
2695 set true to surpress email card/ACH decline notices.
2699 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)
2705 # allows for one time override of normal customer billing method
2709 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2712 my( $self, %options ) = @_;
2713 my $time = $options{'time'} || time;
2716 local $SIG{HUP} = 'IGNORE';
2717 local $SIG{INT} = 'IGNORE';
2718 local $SIG{QUIT} = 'IGNORE';
2719 local $SIG{TERM} = 'IGNORE';
2720 local $SIG{TSTP} = 'IGNORE';
2721 local $SIG{PIPE} = 'IGNORE';
2723 my $oldAutoCommit = $FS::UID::AutoCommit;
2724 local $FS::UID::AutoCommit = 0;
2727 $self->select_for_update; #mutex
2730 my $balance = $self->balance;
2731 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
2734 # if ( exists($options{'retry_card'}) ) {
2735 # carp 'retry_card option passed to collect is deprecated; use retry';
2736 # $options{'retry'} ||= $options{'retry_card'};
2738 # if ( exists($options{'retry'}) && $options{'retry'} ) {
2739 # my $error = $self->retry_realtime;
2741 # $dbh->rollback if $oldAutoCommit;
2746 # false laziness w/pay_batch::import_results
2748 my $due_cust_event = $self->due_cust_event(
2749 'debug' => ( $options{'debug'} || 0 ),
2751 'check_freq' => $options{'check_freq'},
2752 'stage' => ( $options{'stage'} || 'collect' ),
2754 unless( ref($due_cust_event) ) {
2755 $dbh->rollback if $oldAutoCommit;
2756 return $due_cust_event;
2759 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2760 #never want to roll back an event just because it or a different one
2762 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
2764 foreach my $cust_event ( @$due_cust_event ) {
2768 #re-eval event conditions (a previous event could have changed things)
2769 unless ( $cust_event->test_conditions( 'time' => $time ) ) {
2770 #don't leave stray "new/locked" records around
2771 my $error = $cust_event->delete;
2772 return $error if $error;
2777 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2778 warn " running cust_event ". $cust_event->eventnum. "\n"
2781 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2782 if ( my $error = $cust_event->do_event() ) {
2783 #XXX wtf is this? figure out a proper dealio with return value
2795 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2797 Inserts database records for and returns an ordered listref of new events due
2798 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
2799 events are due, an empty listref is returned. If there is an error, returns a
2800 scalar error message.
2802 To actually run the events, call each event's test_condition method, and if
2803 still true, call the event's do_event method.
2805 Options are passed as a hashref or as a list of name-value pairs. Available
2812 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.
2816 "collect" (the default) or "pre-bill"
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).
2836 Set to true to return the objects, but not actually insert them into the
2843 sub due_cust_event {
2845 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2848 #my $DEBUG = $opt{'debug'}
2849 local($DEBUG) = $opt{'debug'}
2850 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2852 warn "$me due_cust_event called with options ".
2853 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2856 $opt{'time'} ||= time;
2858 local $SIG{HUP} = 'IGNORE';
2859 local $SIG{INT} = 'IGNORE';
2860 local $SIG{QUIT} = 'IGNORE';
2861 local $SIG{TERM} = 'IGNORE';
2862 local $SIG{TSTP} = 'IGNORE';
2863 local $SIG{PIPE} = 'IGNORE';
2865 my $oldAutoCommit = $FS::UID::AutoCommit;
2866 local $FS::UID::AutoCommit = 0;
2869 $self->select_for_update #mutex
2870 unless $opt{testonly};
2873 # find possible events (initial search)
2876 my @cust_event = ();
2878 my @eventtable = $opt{'eventtable'}
2879 ? ( $opt{'eventtable'} )
2880 : FS::part_event->eventtables_runorder;
2882 foreach my $eventtable ( @eventtable ) {
2885 if ( $opt{'objects'} ) {
2887 @objects = @{ $opt{'objects'} };
2891 #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2892 @objects = ( $eventtable eq 'cust_main' )
2894 : ( $self->$eventtable() );
2898 my @e_cust_event = ();
2900 my $cross = "CROSS JOIN $eventtable";
2901 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2902 unless $eventtable eq 'cust_main';
2904 foreach my $object ( @objects ) {
2906 #this first search uses the condition_sql magic for optimization.
2907 #the more possible events we can eliminate in this step the better
2909 my $cross_where = '';
2910 my $pkey = $object->primary_key;
2911 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2913 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2915 FS::part_event_condition->where_conditions_sql( $eventtable,
2916 'time'=>$opt{'time'}
2918 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2920 $extra_sql = "AND $extra_sql" if $extra_sql;
2922 #here is the agent virtualization
2923 $extra_sql .= " AND ( part_event.agentnum IS NULL
2924 OR part_event.agentnum = ". $self->agentnum. ' )';
2926 $extra_sql .= " $order";
2928 warn "searching for events for $eventtable ". $object->$pkey. "\n"
2929 if $opt{'debug'} > 2;
2930 my @part_event = qsearch( {
2931 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
2932 'select' => 'part_event.*',
2933 'table' => 'part_event',
2934 'addl_from' => "$cross $join",
2935 'hashref' => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2936 'eventtable' => $eventtable,
2939 'extra_sql' => "AND $cross_where $extra_sql",
2943 my $pkey = $object->primary_key;
2944 warn " ". scalar(@part_event).
2945 " possible events found for $eventtable ". $object->$pkey(). "\n";
2948 push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2952 warn " ". scalar(@e_cust_event).
2953 " subtotal possible cust events found for $eventtable\n"
2956 push @cust_event, @e_cust_event;
2960 warn " ". scalar(@cust_event).
2961 " total possible cust events found in initial search\n"
2969 $opt{stage} ||= 'collect';
2971 grep { my $stage = $_->part_event->event_stage;
2972 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
2982 @cust_event = grep $_->test_conditions( 'time' => $opt{'time'},
2983 'stats_hashref' => \%unsat ),
2986 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
2989 warn " invalid conditions not eliminated with condition_sql:\n".
2990 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
2991 if keys %unsat && $DEBUG; # > 1;
2997 unless( $opt{testonly} ) {
2998 foreach my $cust_event ( @cust_event ) {
3000 my $error = $cust_event->insert();
3002 $dbh->rollback if $oldAutoCommit;
3009 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3015 warn " returning events: ". Dumper(@cust_event). "\n"
3022 =item retry_realtime
3024 Schedules realtime / batch credit card / electronic check / LEC billing
3025 events for for retry. Useful if card information has changed or manual
3026 retry is desired. The 'collect' method must be called to actually retry
3029 Implementation details: For either this customer, or for each of this
3030 customer's open invoices, changes the status of the first "done" (with
3031 statustext error) realtime processing event to "failed".
3035 sub retry_realtime {
3038 local $SIG{HUP} = 'IGNORE';
3039 local $SIG{INT} = 'IGNORE';
3040 local $SIG{QUIT} = 'IGNORE';
3041 local $SIG{TERM} = 'IGNORE';
3042 local $SIG{TSTP} = 'IGNORE';
3043 local $SIG{PIPE} = 'IGNORE';
3045 my $oldAutoCommit = $FS::UID::AutoCommit;
3046 local $FS::UID::AutoCommit = 0;
3049 #a little false laziness w/due_cust_event (not too bad, really)
3051 my $join = FS::part_event_condition->join_conditions_sql;
3052 my $order = FS::part_event_condition->order_conditions_sql;
3055 . join ( ' OR ' , map {
3056 "( part_event.eventtable = " . dbh->quote($_)
3057 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
3058 } FS::part_event->eventtables)
3061 #here is the agent virtualization
3062 my $agent_virt = " ( part_event.agentnum IS NULL
3063 OR part_event.agentnum = ". $self->agentnum. ' )';
3065 #XXX this shouldn't be hardcoded, actions should declare it...
3066 my @realtime_events = qw(
3067 cust_bill_realtime_card
3068 cust_bill_realtime_check
3069 cust_bill_realtime_lec
3073 my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
3078 my @cust_event = qsearchs({
3079 'table' => 'cust_event',
3080 'select' => 'cust_event.*',
3081 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3082 'hashref' => { 'status' => 'done' },
3083 'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3084 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3087 my %seen_invnum = ();
3088 foreach my $cust_event (@cust_event) {
3090 #max one for the customer, one for each open invoice
3091 my $cust_X = $cust_event->cust_X;
3092 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3096 or $cust_event->part_event->eventtable eq 'cust_bill'
3099 my $error = $cust_event->retry;
3101 $dbh->rollback if $oldAutoCommit;
3102 return "error scheduling event for retry: $error";
3107 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3115 =item REALTIME BILLING METHODS
3117 Documentation on realtime billing methods has been moved to
3118 L<FS::cust_main::Billing_Realtime>.
3122 Removes the I<paycvv> field from the database directly.
3124 If there is an error, returns the error, otherwise returns false.
3130 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3131 or return dbh->errstr;
3132 $sth->execute($self->custnum)
3133 or return $sth->errstr;
3138 =item batch_card OPTION => VALUE...
3140 Adds a payment for this invoice to the pending credit card batch (see
3141 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3142 runs the payment using a realtime gateway.
3147 my ($self, %options) = @_;
3150 if (exists($options{amount})) {
3151 $amount = $options{amount};
3153 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3155 return '' unless $amount > 0;
3157 my $invnum = delete $options{invnum};
3158 my $payby = $options{invnum} || $self->payby; #dubious
3160 if ($options{'realtime'}) {
3161 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3167 my $oldAutoCommit = $FS::UID::AutoCommit;
3168 local $FS::UID::AutoCommit = 0;
3171 #this needs to handle mysql as well as Pg, like svc_acct.pm
3172 #(make it into a common function if folks need to do batching with mysql)
3173 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3174 or return "Cannot lock pay_batch: " . $dbh->errstr;
3178 'payby' => FS::payby->payby2payment($payby),
3181 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3183 unless ( $pay_batch ) {
3184 $pay_batch = new FS::pay_batch \%pay_batch;
3185 my $error = $pay_batch->insert;
3187 $dbh->rollback if $oldAutoCommit;
3188 die "error creating new batch: $error\n";
3192 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3193 'batchnum' => $pay_batch->batchnum,
3194 'custnum' => $self->custnum,
3197 foreach (qw( address1 address2 city state zip country payby payinfo paydate
3199 $options{$_} = '' unless exists($options{$_});
3202 my $cust_pay_batch = new FS::cust_pay_batch ( {
3203 'batchnum' => $pay_batch->batchnum,
3204 'invnum' => $invnum || 0, # is there a better value?
3205 # this field should be
3207 # cust_bill_pay_batch now
3208 'custnum' => $self->custnum,
3209 'last' => $self->getfield('last'),
3210 'first' => $self->getfield('first'),
3211 'address1' => $options{address1} || $self->address1,
3212 'address2' => $options{address2} || $self->address2,
3213 'city' => $options{city} || $self->city,
3214 'state' => $options{state} || $self->state,
3215 'zip' => $options{zip} || $self->zip,
3216 'country' => $options{country} || $self->country,
3217 'payby' => $options{payby} || $self->payby,
3218 'payinfo' => $options{payinfo} || $self->payinfo,
3219 'exp' => $options{paydate} || $self->paydate,
3220 'payname' => $options{payname} || $self->payname,
3221 'amount' => $amount, # consolidating
3224 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3225 if $old_cust_pay_batch;
3228 if ($old_cust_pay_batch) {
3229 $error = $cust_pay_batch->replace($old_cust_pay_batch)
3231 $error = $cust_pay_batch->insert;
3235 $dbh->rollback if $oldAutoCommit;
3239 my $unapplied = $self->total_unapplied_credits
3240 + $self->total_unapplied_payments
3241 + $self->in_transit_payments;
3242 foreach my $cust_bill ($self->open_cust_bill) {
3243 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3244 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3245 'invnum' => $cust_bill->invnum,
3246 'paybatchnum' => $cust_pay_batch->paybatchnum,
3247 'amount' => $cust_bill->owed,
3250 if ($unapplied >= $cust_bill_pay_batch->amount){
3251 $unapplied -= $cust_bill_pay_batch->amount;
3254 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
3255 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
3257 $error = $cust_bill_pay_batch->insert;
3259 $dbh->rollback if $oldAutoCommit;
3264 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3270 Returns the total owed for this customer on all invoices
3271 (see L<FS::cust_bill/owed>).
3277 $self->total_owed_date(2145859200); #12/31/2037
3280 =item total_owed_date TIME
3282 Returns the total owed for this customer on all invoices with date earlier than
3283 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3284 see L<Time::Local> and L<Date::Parse> for conversion functions.
3288 sub total_owed_date {
3292 my $custnum = $self->custnum;
3294 my $owed_sql = FS::cust_bill->owed_sql;
3297 SELECT SUM($owed_sql) FROM cust_bill
3298 WHERE custnum = $custnum
3302 sprintf( "%.2f", $self->scalar_sql($sql) );
3306 =item total_owed_pkgnum PKGNUM
3308 Returns the total owed on all invoices for this customer's specific package
3309 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
3313 sub total_owed_pkgnum {
3314 my( $self, $pkgnum ) = @_;
3315 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
3318 =item total_owed_date_pkgnum TIME PKGNUM
3320 Returns the total owed for this customer's specific package when using
3321 experimental package balances on all invoices with date earlier than
3322 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3323 see L<Time::Local> and L<Date::Parse> for conversion functions.
3327 sub total_owed_date_pkgnum {
3328 my( $self, $time, $pkgnum ) = @_;
3331 foreach my $cust_bill (
3332 grep { $_->_date <= $time }
3333 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3335 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
3337 sprintf( "%.2f", $total_bill );
3343 Returns the total amount of all payments.
3350 $total += $_->paid foreach $self->cust_pay;
3351 sprintf( "%.2f", $total );
3354 =item total_unapplied_credits
3356 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3357 customer. See L<FS::cust_credit/credited>.
3359 =item total_credited
3361 Old name for total_unapplied_credits. Don't use.
3365 sub total_credited {
3366 #carp "total_credited deprecated, use total_unapplied_credits";
3367 shift->total_unapplied_credits(@_);
3370 sub total_unapplied_credits {
3373 my $custnum = $self->custnum;
3375 my $unapplied_sql = FS::cust_credit->unapplied_sql;
3378 SELECT SUM($unapplied_sql) FROM cust_credit
3379 WHERE custnum = $custnum
3382 sprintf( "%.2f", $self->scalar_sql($sql) );
3386 =item total_unapplied_credits_pkgnum PKGNUM
3388 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3389 customer. See L<FS::cust_credit/credited>.
3393 sub total_unapplied_credits_pkgnum {
3394 my( $self, $pkgnum ) = @_;
3395 my $total_credit = 0;
3396 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
3397 sprintf( "%.2f", $total_credit );
3401 =item total_unapplied_payments
3403 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3404 See L<FS::cust_pay/unapplied>.
3408 sub total_unapplied_payments {
3411 my $custnum = $self->custnum;
3413 my $unapplied_sql = FS::cust_pay->unapplied_sql;
3416 SELECT SUM($unapplied_sql) FROM cust_pay
3417 WHERE custnum = $custnum
3420 sprintf( "%.2f", $self->scalar_sql($sql) );
3424 =item total_unapplied_payments_pkgnum PKGNUM
3426 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
3427 specific package when using experimental package balances. See
3428 L<FS::cust_pay/unapplied>.
3432 sub total_unapplied_payments_pkgnum {
3433 my( $self, $pkgnum ) = @_;
3434 my $total_unapplied = 0;
3435 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
3436 sprintf( "%.2f", $total_unapplied );
3440 =item total_unapplied_refunds
3442 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
3443 customer. See L<FS::cust_refund/unapplied>.
3447 sub total_unapplied_refunds {
3449 my $custnum = $self->custnum;
3451 my $unapplied_sql = FS::cust_refund->unapplied_sql;
3454 SELECT SUM($unapplied_sql) FROM cust_refund
3455 WHERE custnum = $custnum
3458 sprintf( "%.2f", $self->scalar_sql($sql) );
3464 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3465 total_unapplied_credits minus total_unapplied_payments).
3471 $self->balance_date_range;
3474 =item balance_date TIME
3476 Returns the balance for this customer, only considering invoices with date
3477 earlier than TIME (total_owed_date minus total_credited minus
3478 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3479 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3486 $self->balance_date_range(shift);
3489 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
3491 Returns the balance for this customer, optionally considering invoices with
3492 date earlier than START_TIME, and not later than END_TIME
3493 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
3495 Times are specified as SQL fragments or numeric
3496 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
3497 L<Date::Parse> for conversion functions. The empty string can be passed
3498 to disable that time constraint completely.
3500 Available options are:
3504 =item unapplied_date
3506 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)
3512 sub balance_date_range {
3514 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
3515 ') FROM cust_main WHERE custnum='. $self->custnum;
3516 sprintf( '%.2f', $self->scalar_sql($sql) );
3519 =item balance_pkgnum PKGNUM
3521 Returns the balance for this customer's specific package when using
3522 experimental package balances (total_owed plus total_unrefunded, minus
3523 total_unapplied_credits minus total_unapplied_payments)
3527 sub balance_pkgnum {
3528 my( $self, $pkgnum ) = @_;
3531 $self->total_owed_pkgnum($pkgnum)
3532 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
3533 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
3534 - $self->total_unapplied_credits_pkgnum($pkgnum)
3535 - $self->total_unapplied_payments_pkgnum($pkgnum)
3539 =item in_transit_payments
3541 Returns the total of requests for payments for this customer pending in
3542 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3546 sub in_transit_payments {
3548 my $in_transit_payments = 0;
3549 foreach my $pay_batch ( qsearch('pay_batch', {
3552 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3553 'batchnum' => $pay_batch->batchnum,
3554 'custnum' => $self->custnum,
3556 $in_transit_payments += $cust_pay_batch->amount;
3559 sprintf( "%.2f", $in_transit_payments );
3564 Returns a hash of useful information for making a payment.
3574 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3575 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3576 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3580 For credit card transactions:
3592 For electronic check transactions:
3607 $return{balance} = $self->balance;
3609 $return{payname} = $self->payname
3610 || ( $self->first. ' '. $self->get('last') );
3612 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
3614 $return{payby} = $self->payby;
3615 $return{stateid_state} = $self->stateid_state;
3617 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3618 $return{card_type} = cardtype($self->payinfo);
3619 $return{payinfo} = $self->paymask;
3621 @return{'month', 'year'} = $self->paydate_monthyear;
3625 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3626 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3627 $return{payinfo1} = $payinfo1;
3628 $return{payinfo2} = $payinfo2;
3629 $return{paytype} = $self->paytype;
3630 $return{paystate} = $self->paystate;
3634 #doubleclick protection
3636 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3642 =item paydate_monthyear
3644 Returns a two-element list consisting of the month and year of this customer's
3645 paydate (credit card expiration date for CARD customers)
3649 sub paydate_monthyear {
3651 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3653 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3660 =item tax_exemption TAXNAME
3665 my( $self, $taxname ) = @_;
3667 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3668 'taxname' => $taxname,
3673 =item cust_main_exemption
3677 sub cust_main_exemption {
3679 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3682 =item invoicing_list [ ARRAYREF ]
3684 If an arguement is given, sets these email addresses as invoice recipients
3685 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3686 (except as warnings), so use check_invoicing_list first.
3688 Returns a list of email addresses (with svcnum entries expanded).
3690 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3691 check it without disturbing anything by passing nothing.
3693 This interface may change in the future.
3697 sub invoicing_list {
3698 my( $self, $arrayref ) = @_;
3701 my @cust_main_invoice;
3702 if ( $self->custnum ) {
3703 @cust_main_invoice =
3704 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3706 @cust_main_invoice = ();
3708 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3709 #warn $cust_main_invoice->destnum;
3710 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3711 #warn $cust_main_invoice->destnum;
3712 my $error = $cust_main_invoice->delete;
3713 warn $error if $error;
3716 if ( $self->custnum ) {
3717 @cust_main_invoice =
3718 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3720 @cust_main_invoice = ();
3722 my %seen = map { $_->address => 1 } @cust_main_invoice;
3723 foreach my $address ( @{$arrayref} ) {
3724 next if exists $seen{$address} && $seen{$address};
3725 $seen{$address} = 1;
3726 my $cust_main_invoice = new FS::cust_main_invoice ( {
3727 'custnum' => $self->custnum,
3730 my $error = $cust_main_invoice->insert;
3731 warn $error if $error;
3735 if ( $self->custnum ) {
3737 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3744 =item check_invoicing_list ARRAYREF
3746 Checks these arguements as valid input for the invoicing_list method. If there
3747 is an error, returns the error, otherwise returns false.
3751 sub check_invoicing_list {
3752 my( $self, $arrayref ) = @_;
3754 foreach my $address ( @$arrayref ) {
3756 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3757 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3760 my $cust_main_invoice = new FS::cust_main_invoice ( {
3761 'custnum' => $self->custnum,
3764 my $error = $self->custnum
3765 ? $cust_main_invoice->check
3766 : $cust_main_invoice->checkdest
3768 return $error if $error;
3772 return "Email address required"
3773 if $conf->exists('cust_main-require_invoicing_list_email')
3774 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3779 =item set_default_invoicing_list
3781 Sets the invoicing list to all accounts associated with this customer,
3782 overwriting any previous invoicing list.
3786 sub set_default_invoicing_list {
3788 $self->invoicing_list($self->all_emails);
3793 Returns the email addresses of all accounts provisioned for this customer.
3800 foreach my $cust_pkg ( $self->all_pkgs ) {
3801 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3803 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3804 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3806 $list{$_}=1 foreach map { $_->email } @svc_acct;
3811 =item invoicing_list_addpost
3813 Adds postal invoicing to this customer. If this customer is already configured
3814 to receive postal invoices, does nothing.
3818 sub invoicing_list_addpost {
3820 return if grep { $_ eq 'POST' } $self->invoicing_list;
3821 my @invoicing_list = $self->invoicing_list;
3822 push @invoicing_list, 'POST';
3823 $self->invoicing_list(\@invoicing_list);
3826 =item invoicing_list_emailonly
3828 Returns the list of email invoice recipients (invoicing_list without non-email
3829 destinations such as POST and FAX).
3833 sub invoicing_list_emailonly {
3835 warn "$me invoicing_list_emailonly called"
3837 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3840 =item invoicing_list_emailonly_scalar
3842 Returns the list of email invoice recipients (invoicing_list without non-email
3843 destinations such as POST and FAX) as a comma-separated scalar.
3847 sub invoicing_list_emailonly_scalar {
3849 warn "$me invoicing_list_emailonly_scalar called"
3851 join(', ', $self->invoicing_list_emailonly);
3854 =item referral_custnum_cust_main
3856 Returns the customer who referred this customer (or the empty string, if
3857 this customer was not referred).
3859 Note the difference with referral_cust_main method: This method,
3860 referral_custnum_cust_main returns the single customer (if any) who referred
3861 this customer, while referral_cust_main returns an array of customers referred
3866 sub referral_custnum_cust_main {
3868 return '' unless $self->referral_custnum;
3869 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3872 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3874 Returns an array of customers referred by this customer (referral_custnum set
3875 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3876 customers referred by customers referred by this customer and so on, inclusive.
3877 The default behavior is DEPTH 1 (no recursion).
3879 Note the difference with referral_custnum_cust_main method: This method,
3880 referral_cust_main, returns an array of customers referred BY this customer,
3881 while referral_custnum_cust_main returns the single customer (if any) who
3882 referred this customer.
3886 sub referral_cust_main {
3888 my $depth = @_ ? shift : 1;
3889 my $exclude = @_ ? shift : {};
3892 map { $exclude->{$_->custnum}++; $_; }
3893 grep { ! $exclude->{ $_->custnum } }
3894 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3898 map { $_->referral_cust_main($depth-1, $exclude) }
3905 =item referral_cust_main_ncancelled
3907 Same as referral_cust_main, except only returns customers with uncancelled
3912 sub referral_cust_main_ncancelled {
3914 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3917 =item referral_cust_pkg [ DEPTH ]
3919 Like referral_cust_main, except returns a flat list of all unsuspended (and
3920 uncancelled) packages for each customer. The number of items in this list may
3921 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3925 sub referral_cust_pkg {
3927 my $depth = @_ ? shift : 1;
3929 map { $_->unsuspended_pkgs }
3930 grep { $_->unsuspended_pkgs }
3931 $self->referral_cust_main($depth);
3934 =item referring_cust_main
3936 Returns the single cust_main record for the customer who referred this customer
3937 (referral_custnum), or false.
3941 sub referring_cust_main {
3943 return '' unless $self->referral_custnum;
3944 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3947 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3949 Applies a credit to this customer. If there is an error, returns the error,
3950 otherwise returns false.
3952 REASON can be a text string, an FS::reason object, or a scalar reference to
3953 a reasonnum. If a text string, it will be automatically inserted as a new
3954 reason, and a 'reason_type' option must be passed to indicate the
3955 FS::reason_type for the new reason.
3957 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3959 Any other options are passed to FS::cust_credit::insert.
3964 my( $self, $amount, $reason, %options ) = @_;
3966 my $cust_credit = new FS::cust_credit {
3967 'custnum' => $self->custnum,
3968 'amount' => $amount,
3971 if ( ref($reason) ) {
3973 if ( ref($reason) eq 'SCALAR' ) {
3974 $cust_credit->reasonnum( $$reason );
3976 $cust_credit->reasonnum( $reason->reasonnum );
3980 $cust_credit->set('reason', $reason)
3983 for (qw( addlinfo eventnum )) {
3984 $cust_credit->$_( delete $options{$_} )
3985 if exists($options{$_});
3988 $cust_credit->insert(%options);
3992 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3994 Creates a one-time charge for this customer. If there is an error, returns
3995 the error, otherwise returns false.
3997 New-style, with a hashref of options:
3999 my $error = $cust_main->charge(
4003 'start_date' => str2time('7/4/2009'),
4004 'pkg' => 'Description',
4005 'comment' => 'Comment',
4006 'additional' => [], #extra invoice detail
4007 'classnum' => 1, #pkg_class
4009 'setuptax' => '', # or 'Y' for tax exempt
4012 'taxclass' => 'Tax class',
4015 'taxproduct' => 2, #part_pkg_taxproduct
4016 'override' => {}, #XXX describe
4018 #will be filled in with the new object
4019 'cust_pkg_ref' => \$cust_pkg,
4021 #generate an invoice immediately
4023 'invoice_terms' => '', #with these terms
4029 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
4035 my ( $amount, $quantity, $start_date, $classnum );
4036 my ( $pkg, $comment, $additional );
4037 my ( $setuptax, $taxclass ); #internal taxes
4038 my ( $taxproduct, $override ); #vendor (CCH) taxes
4040 my $cust_pkg_ref = '';
4041 my ( $bill_now, $invoice_terms ) = ( 0, '' );
4042 if ( ref( $_[0] ) ) {
4043 $amount = $_[0]->{amount};
4044 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4045 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
4046 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
4047 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4048 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
4049 : '$'. sprintf("%.2f",$amount);
4050 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
4051 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4052 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4053 $additional = $_[0]->{additional} || [];
4054 $taxproduct = $_[0]->{taxproductnum};
4055 $override = { '' => $_[0]->{tax_override} };
4056 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
4057 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
4058 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
4063 $pkg = @_ ? shift : 'One-time charge';
4064 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
4066 $taxclass = @_ ? shift : '';
4070 local $SIG{HUP} = 'IGNORE';
4071 local $SIG{INT} = 'IGNORE';
4072 local $SIG{QUIT} = 'IGNORE';
4073 local $SIG{TERM} = 'IGNORE';
4074 local $SIG{TSTP} = 'IGNORE';
4075 local $SIG{PIPE} = 'IGNORE';
4077 my $oldAutoCommit = $FS::UID::AutoCommit;
4078 local $FS::UID::AutoCommit = 0;
4081 my $part_pkg = new FS::part_pkg ( {
4083 'comment' => $comment,
4087 'classnum' => ( $classnum ? $classnum : '' ),
4088 'setuptax' => $setuptax,
4089 'taxclass' => $taxclass,
4090 'taxproductnum' => $taxproduct,
4093 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4094 ( 0 .. @$additional - 1 )
4096 'additional_count' => scalar(@$additional),
4097 'setup_fee' => $amount,
4100 my $error = $part_pkg->insert( options => \%options,
4101 tax_overrides => $override,
4104 $dbh->rollback if $oldAutoCommit;
4108 my $pkgpart = $part_pkg->pkgpart;
4109 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4110 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4111 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4112 $error = $type_pkgs->insert;
4114 $dbh->rollback if $oldAutoCommit;
4119 my $cust_pkg = new FS::cust_pkg ( {
4120 'custnum' => $self->custnum,
4121 'pkgpart' => $pkgpart,
4122 'quantity' => $quantity,
4123 'start_date' => $start_date,
4124 'no_auto' => $no_auto,
4127 $error = $cust_pkg->insert;
4129 $dbh->rollback if $oldAutoCommit;
4131 } elsif ( $cust_pkg_ref ) {
4132 ${$cust_pkg_ref} = $cust_pkg;
4136 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
4137 'pkg_list' => [ $cust_pkg ],
4140 $dbh->rollback if $oldAutoCommit;
4145 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4150 #=item charge_postal_fee
4152 #Applies a one time charge this customer. If there is an error,
4153 #returns the error, returns the cust_pkg charge object or false
4154 #if there was no charge.
4158 # This should be a customer event. For that to work requires that bill
4159 # also be a customer event.
4161 sub charge_postal_fee {
4164 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4165 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4167 my $cust_pkg = new FS::cust_pkg ( {
4168 'custnum' => $self->custnum,
4169 'pkgpart' => $pkgpart,
4173 my $error = $cust_pkg->insert;
4174 $error ? $error : $cust_pkg;
4179 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4185 map { $_ } #return $self->num_cust_bill unless wantarray;
4186 sort { $a->_date <=> $b->_date }
4187 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4190 =item open_cust_bill
4192 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4197 sub open_cust_bill {
4201 'table' => 'cust_bill',
4202 'hashref' => { 'custnum' => $self->custnum, },
4203 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
4204 'order_by' => 'ORDER BY _date ASC',
4209 =item cust_statements
4211 Returns all the statements (see L<FS::cust_statement>) for this customer.
4215 sub cust_statement {
4217 map { $_ } #return $self->num_cust_statement unless wantarray;
4218 sort { $a->_date <=> $b->_date }
4219 qsearch('cust_statement', { 'custnum' => $self->custnum, } )
4224 Returns all the credits (see L<FS::cust_credit>) for this customer.
4230 map { $_ } #return $self->num_cust_credit unless wantarray;
4231 sort { $a->_date <=> $b->_date }
4232 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4235 =item cust_credit_pkgnum
4237 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
4238 package when using experimental package balances.
4242 sub cust_credit_pkgnum {
4243 my( $self, $pkgnum ) = @_;
4244 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
4245 sort { $a->_date <=> $b->_date }
4246 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
4247 'pkgnum' => $pkgnum,
4254 Returns all the payments (see L<FS::cust_pay>) for this customer.
4260 return $self->num_cust_pay unless wantarray;
4261 sort { $a->_date <=> $b->_date }
4262 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4267 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
4268 called automatically when the cust_pay method is used in a scalar context.
4274 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
4275 my $sth = dbh->prepare($sql) or die dbh->errstr;
4276 $sth->execute($self->custnum) or die $sth->errstr;
4277 $sth->fetchrow_arrayref->[0];
4280 =item cust_pay_pkgnum
4282 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
4283 package when using experimental package balances.
4287 sub cust_pay_pkgnum {
4288 my( $self, $pkgnum ) = @_;
4289 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
4290 sort { $a->_date <=> $b->_date }
4291 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
4292 'pkgnum' => $pkgnum,
4299 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4305 map { $_ } #return $self->num_cust_pay_void unless wantarray;
4306 sort { $a->_date <=> $b->_date }
4307 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4310 =item cust_pay_batch
4312 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
4316 sub cust_pay_batch {
4318 map { $_ } #return $self->num_cust_pay_batch unless wantarray;
4319 sort { $a->paybatchnum <=> $b->paybatchnum }
4320 qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
4323 =item cust_pay_pending
4325 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
4326 (without status "done").
4330 sub cust_pay_pending {
4332 return $self->num_cust_pay_pending unless wantarray;
4333 sort { $a->_date <=> $b->_date }
4334 qsearch( 'cust_pay_pending', {
4335 'custnum' => $self->custnum,
4336 'status' => { op=>'!=', value=>'done' },
4341 =item cust_pay_pending_attempt
4343 Returns all payment attempts / declined payments for this customer, as pending
4344 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
4345 a corresponding payment (see L<FS::cust_pay>).
4349 sub cust_pay_pending_attempt {
4351 return $self->num_cust_pay_pending_attempt unless wantarray;
4352 sort { $a->_date <=> $b->_date }
4353 qsearch( 'cust_pay_pending', {
4354 'custnum' => $self->custnum,
4361 =item num_cust_pay_pending
4363 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4364 customer (without status "done"). Also called automatically when the
4365 cust_pay_pending method is used in a scalar context.
4369 sub num_cust_pay_pending {
4372 " SELECT COUNT(*) FROM cust_pay_pending ".
4373 " WHERE custnum = ? AND status != 'done' ",
4378 =item num_cust_pay_pending_attempt
4380 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4381 customer, with status "done" but without a corresp. Also called automatically when the
4382 cust_pay_pending method is used in a scalar context.
4386 sub num_cust_pay_pending_attempt {
4389 " SELECT COUNT(*) FROM cust_pay_pending ".
4390 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4397 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4403 map { $_ } #return $self->num_cust_refund unless wantarray;
4404 sort { $a->_date <=> $b->_date }
4405 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4408 =item display_custnum
4410 Returns the displayed customer number for this customer: agent_custid if
4411 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4415 sub display_custnum {
4417 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
4418 return $self->agent_custid;
4420 return $self->custnum;
4426 Returns a name string for this customer, either "Company (Last, First)" or
4433 my $name = $self->contact;
4434 $name = $self->company. " ($name)" if $self->company;
4440 Returns a name string for this (service/shipping) contact, either
4441 "Company (Last, First)" or "Last, First".
4447 if ( $self->get('ship_last') ) {
4448 my $name = $self->ship_contact;
4449 $name = $self->ship_company. " ($name)" if $self->ship_company;
4458 Returns a name string for this customer, either "Company" or "First Last".
4464 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4467 =item ship_name_short
4469 Returns a name string for this (service/shipping) contact, either "Company"
4474 sub ship_name_short {
4476 if ( $self->get('ship_last') ) {
4477 $self->ship_company !~ /^\s*$/
4478 ? $self->ship_company
4479 : $self->ship_contact_firstlast;
4481 $self->name_company_or_firstlast;
4487 Returns this customer's full (billing) contact name only, "Last, First"
4493 $self->get('last'). ', '. $self->first;
4498 Returns this customer's full (shipping) contact name only, "Last, First"
4504 $self->get('ship_last')
4505 ? $self->get('ship_last'). ', '. $self->ship_first
4509 =item contact_firstlast
4511 Returns this customers full (billing) contact name only, "First Last".
4515 sub contact_firstlast {
4517 $self->first. ' '. $self->get('last');
4520 =item ship_contact_firstlast
4522 Returns this customer's full (shipping) contact name only, "First Last".
4526 sub ship_contact_firstlast {
4528 $self->get('ship_last')
4529 ? $self->first. ' '. $self->get('ship_last')
4530 : $self->contact_firstlast;
4535 Returns this customer's full country name
4541 code2country($self->country);
4544 =item geocode DATA_VENDOR
4546 Returns a value for the customer location as encoded by DATA_VENDOR.
4547 Currently this only makes sense for "CCH" as DATA_VENDOR.
4552 my ($self, $data_vendor) = (shift, shift); #always cch for now
4554 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
4555 return $geocode if $geocode;
4557 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
4561 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
4562 if $self->country eq 'US';
4566 #CCH specific location stuff
4567 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
4569 my @cust_tax_location =
4571 'table' => 'cust_tax_location',
4572 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
4573 'extra_sql' => $extra_sql,
4574 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
4577 $geocode = $cust_tax_location[0]->geocode
4578 if scalar(@cust_tax_location);
4587 Returns a status string for this customer, currently:
4591 =item prospect - No packages have ever been ordered
4593 =item ordered - Recurring packages all are new (not yet billed).
4595 =item active - One or more recurring packages is active
4597 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4599 =item suspended - All non-cancelled recurring packages are suspended
4601 =item cancelled - All recurring packages are cancelled
4607 sub status { shift->cust_status(@_); }
4611 # prospect ordered active inactive suspended cancelled
4612 for my $status ( FS::cust_main->statuses() ) {
4613 my $method = $status.'_sql';
4614 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4615 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4616 $sth->execute( ($self->custnum) x $numnum )
4617 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4618 return $status if $sth->fetchrow_arrayref->[0];
4622 =item ucfirst_cust_status
4624 =item ucfirst_status
4626 Returns the status with the first character capitalized.
4630 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4632 sub ucfirst_cust_status {
4634 ucfirst($self->cust_status);
4639 Returns a hex triplet color string for this customer's status.
4643 use vars qw(%statuscolor);
4644 tie %statuscolor, 'Tie::IxHash',
4645 'prospect' => '7e0079', #'000000', #black? naw, purple
4646 'active' => '00CC00', #green
4647 'ordered' => '009999', #teal? cyan?
4648 'inactive' => '0000CC', #blue
4649 'suspended' => 'FF9900', #yellow
4650 'cancelled' => 'FF0000', #red
4653 sub statuscolor { shift->cust_statuscolor(@_); }
4655 sub cust_statuscolor {
4657 $statuscolor{$self->cust_status};
4662 Returns an array of hashes representing the customer's RT tickets.
4669 my $num = $conf->config('cust_main-max_tickets') || 10;
4672 if ( $conf->config('ticket_system') ) {
4673 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4675 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4679 foreach my $priority (
4680 $conf->config('ticket_system-custom_priority_field-values'), ''
4682 last if scalar(@tickets) >= $num;
4684 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4685 $num - scalar(@tickets),
4695 # Return services representing svc_accts in customer support packages
4696 sub support_services {
4698 my %packages = map { $_ => 1 } $conf->config('support_packages');
4700 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4701 grep { $_->part_svc->svcdb eq 'svc_acct' }
4702 map { $_->cust_svc }
4703 grep { exists $packages{ $_->pkgpart } }
4704 $self->ncancelled_pkgs;
4708 # Return a list of latitude/longitude for one of the services (if any)
4709 sub service_coordinates {
4713 grep { $_->latitude && $_->longitude }
4715 map { $_->cust_svc }
4716 $self->ncancelled_pkgs;
4718 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4723 Returns a masked version of the named field
4728 my ($self,$field) = @_;
4732 'x'x(length($self->getfield($field))-4).
4733 substr($self->getfield($field), (length($self->getfield($field))-4));
4739 =head1 CLASS METHODS
4745 Class method that returns the list of possible status strings for customers
4746 (see L<the status method|/status>). For example:
4748 @statuses = FS::cust_main->statuses();
4753 #my $self = shift; #could be class...
4759 Returns an SQL expression identifying prospective cust_main records (customers
4760 with no packages ever ordered)
4764 use vars qw($select_count_pkgs);
4765 $select_count_pkgs =
4766 "SELECT COUNT(*) FROM cust_pkg
4767 WHERE cust_pkg.custnum = cust_main.custnum";
4769 sub select_count_pkgs_sql {
4774 " 0 = ( $select_count_pkgs ) ";
4779 Returns an SQL expression identifying ordered cust_main records (customers with
4780 recurring packages not yet setup).
4785 FS::cust_main->none_active_sql.
4786 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
4791 Returns an SQL expression identifying active cust_main records (customers with
4792 active recurring packages).
4797 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4800 =item none_active_sql
4802 Returns an SQL expression identifying cust_main records with no active
4803 recurring packages. This includes customers of status prospect, ordered,
4804 inactive, and suspended.
4808 sub none_active_sql {
4809 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4814 Returns an SQL expression identifying inactive cust_main records (customers with
4815 no active recurring packages, but otherwise unsuspended/uncancelled).
4820 FS::cust_main->none_active_sql.
4821 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4827 Returns an SQL expression identifying suspended cust_main records.
4832 sub suspended_sql { susp_sql(@_); }
4834 FS::cust_main->none_active_sql.
4835 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4841 Returns an SQL expression identifying cancelled cust_main records.
4845 sub cancelled_sql { cancel_sql(@_); }
4848 my $recurring_sql = FS::cust_pkg->recurring_sql;
4849 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
4852 0 < ( $select_count_pkgs )
4853 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
4854 AND 0 = ( $select_count_pkgs AND $recurring_sql
4855 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4857 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4863 =item uncancelled_sql
4865 Returns an SQL expression identifying un-cancelled cust_main records.
4869 sub uncancelled_sql { uncancel_sql(@_); }
4870 sub uncancel_sql { "
4871 ( 0 < ( $select_count_pkgs
4872 AND ( cust_pkg.cancel IS NULL
4873 OR cust_pkg.cancel = 0
4876 OR 0 = ( $select_count_pkgs )
4882 Returns an SQL fragment to retreive the balance.
4887 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4888 WHERE cust_bill.custnum = cust_main.custnum )
4889 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4890 WHERE cust_pay.custnum = cust_main.custnum )
4891 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4892 WHERE cust_credit.custnum = cust_main.custnum )
4893 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4894 WHERE cust_refund.custnum = cust_main.custnum )
4897 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4899 Returns an SQL fragment to retreive the balance for this customer, optionally
4900 considering invoices with date earlier than START_TIME, and not
4901 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4902 total_unapplied_payments).
4904 Times are specified as SQL fragments or numeric
4905 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4906 L<Date::Parse> for conversion functions. The empty string can be passed
4907 to disable that time constraint completely.
4909 Available options are:
4913 =item unapplied_date
4915 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)
4920 set to true to remove all customer comparison clauses, for totals
4925 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4930 JOIN clause (typically used with the total option)
4934 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4935 time will be ignored. Note that START_TIME and END_TIME only limit the date
4936 range for invoices and I<unapplied> payments, credits, and refunds.
4942 sub balance_date_sql {
4943 my( $class, $start, $end, %opt ) = @_;
4945 my $cutoff = $opt{'cutoff'};
4947 my $owed = FS::cust_bill->owed_sql($cutoff);
4948 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4949 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4950 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4952 my $j = $opt{'join'} || '';
4954 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4955 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4956 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4957 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4959 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4960 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4961 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4962 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4967 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4969 Returns an SQL fragment to retreive the total unapplied payments for this
4970 customer, only considering invoices with date earlier than START_TIME, and
4971 optionally not later than END_TIME.
4973 Times are specified as SQL fragments or numeric
4974 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4975 L<Date::Parse> for conversion functions. The empty string can be passed
4976 to disable that time constraint completely.
4978 Available options are:
4982 sub unapplied_payments_date_sql {
4983 my( $class, $start, $end, %opt ) = @_;
4985 my $cutoff = $opt{'cutoff'};
4987 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4989 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4990 'unapplied_date'=>1 );
4992 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4995 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4997 Helper method for balance_date_sql; name (and usage) subject to change
4998 (suggestions welcome).
5000 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5001 cust_refund, cust_credit or cust_pay).
5003 If TABLE is "cust_bill" or the unapplied_date option is true, only
5004 considers records with date earlier than START_TIME, and optionally not
5005 later than END_TIME .
5009 sub _money_table_where {
5010 my( $class, $table, $start, $end, %opt ) = @_;
5013 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5014 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5015 push @where, "$table._date <= $start" if defined($start) && length($start);
5016 push @where, "$table._date > $end" if defined($end) && length($end);
5018 push @where, @{$opt{'where'}} if $opt{'where'};
5019 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5025 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
5026 use FS::cust_main::Search;
5029 FS::cust_main::Search->search(@_);
5038 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
5042 sub append_fuzzyfiles {
5043 #my( $first, $last, $company ) = @_;
5045 &check_and_rebuild_fuzzyfiles;
5047 use Fcntl qw(:flock);
5049 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
5051 foreach my $field (@fuzzyfields) {
5056 open(CACHE,">>$dir/cust_main.$field")
5057 or die "can't open $dir/cust_main.$field: $!";
5058 flock(CACHE,LOCK_EX)
5059 or die "can't lock $dir/cust_main.$field: $!";
5061 print CACHE "$value\n";
5063 flock(CACHE,LOCK_UN)
5064 or die "can't unlock $dir/cust_main.$field: $!";
5079 #warn join('-',keys %$param);
5080 my $fh = $param->{filehandle};
5081 my $agentnum = $param->{agentnum};
5082 my $format = $param->{format};
5084 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
5087 if ( $format eq 'simple' ) {
5088 @fields = qw( custnum agent_custid amount pkg );
5090 die "unknown format $format";
5093 eval "use Text::CSV_XS;";
5096 my $csv = new Text::CSV_XS;
5103 local $SIG{HUP} = 'IGNORE';
5104 local $SIG{INT} = 'IGNORE';
5105 local $SIG{QUIT} = 'IGNORE';
5106 local $SIG{TERM} = 'IGNORE';
5107 local $SIG{TSTP} = 'IGNORE';
5108 local $SIG{PIPE} = 'IGNORE';
5110 my $oldAutoCommit = $FS::UID::AutoCommit;
5111 local $FS::UID::AutoCommit = 0;
5114 #while ( $columns = $csv->getline($fh) ) {
5116 while ( defined($line=<$fh>) ) {
5118 $csv->parse($line) or do {
5119 $dbh->rollback if $oldAutoCommit;
5120 return "can't parse: ". $csv->error_input();
5123 my @columns = $csv->fields();
5124 #warn join('-',@columns);
5127 foreach my $field ( @fields ) {
5128 $row{$field} = shift @columns;
5131 if ( $row{custnum} && $row{agent_custid} ) {
5132 dbh->rollback if $oldAutoCommit;
5133 return "can't specify custnum with agent_custid $row{agent_custid}";
5137 if ( $row{agent_custid} && $agentnum ) {
5138 %hash = ( 'agent_custid' => $row{agent_custid},
5139 'agentnum' => $agentnum,
5143 if ( $row{custnum} ) {
5144 %hash = ( 'custnum' => $row{custnum} );
5147 unless ( scalar(keys %hash) ) {
5148 $dbh->rollback if $oldAutoCommit;
5149 return "can't find customer without custnum or agent_custid and agentnum";
5152 my $cust_main = qsearchs('cust_main', { %hash } );
5153 unless ( $cust_main ) {
5154 $dbh->rollback if $oldAutoCommit;
5155 my $custnum = $row{custnum} || $row{agent_custid};
5156 return "unknown custnum $custnum";
5159 if ( $row{'amount'} > 0 ) {
5160 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5162 $dbh->rollback if $oldAutoCommit;
5166 } elsif ( $row{'amount'} < 0 ) {
5167 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5170 $dbh->rollback if $oldAutoCommit;
5180 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5182 return "Empty file!" unless $imported;
5188 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5190 Deprecated. Use event notification and message templates
5191 (L<FS::msg_template>) instead.
5193 Sends a templated email notification to the customer (see L<Text::Template>).
5195 OPTIONS is a hash and may include
5197 I<from> - the email sender (default is invoice_from)
5199 I<to> - comma-separated scalar or arrayref of recipients
5200 (default is invoicing_list)
5202 I<subject> - The subject line of the sent email notification
5203 (default is "Notice from company_name")
5205 I<extra_fields> - a hashref of name/value pairs which will be substituted
5208 The following variables are vavailable in the template.
5210 I<$first> - the customer first name
5211 I<$last> - the customer last name
5212 I<$company> - the customer company
5213 I<$payby> - a description of the method of payment for the customer
5214 # would be nice to use FS::payby::shortname
5215 I<$payinfo> - the account information used to collect for this customer
5216 I<$expdate> - the expiration of the customer payment in seconds from epoch
5221 my ($self, $template, %options) = @_;
5223 return unless $conf->exists($template);
5225 my $from = $conf->config('invoice_from', $self->agentnum)
5226 if $conf->exists('invoice_from', $self->agentnum);
5227 $from = $options{from} if exists($options{from});
5229 my $to = join(',', $self->invoicing_list_emailonly);
5230 $to = $options{to} if exists($options{to});
5232 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5233 if $conf->exists('company_name', $self->agentnum);
5234 $subject = $options{subject} if exists($options{subject});
5236 my $notify_template = new Text::Template (TYPE => 'ARRAY',
5237 SOURCE => [ map "$_\n",
5238 $conf->config($template)]
5240 or die "can't create new Text::Template object: Text::Template::ERROR";
5241 $notify_template->compile()
5242 or die "can't compile template: Text::Template::ERROR";
5244 $FS::notify_template::_template::company_name =
5245 $conf->config('company_name', $self->agentnum);
5246 $FS::notify_template::_template::company_address =
5247 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5249 my $paydate = $self->paydate || '2037-12-31';
5250 $FS::notify_template::_template::first = $self->first;
5251 $FS::notify_template::_template::last = $self->last;
5252 $FS::notify_template::_template::company = $self->company;
5253 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5254 my $payby = $self->payby;
5255 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5256 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5258 #credit cards expire at the end of the month/year of their exp date
5259 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5260 $FS::notify_template::_template::payby = 'credit card';
5261 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5262 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5264 }elsif ($payby eq 'COMP') {
5265 $FS::notify_template::_template::payby = 'complimentary account';
5267 $FS::notify_template::_template::payby = 'current method';
5269 $FS::notify_template::_template::expdate = $expire_time;
5271 for (keys %{$options{extra_fields}}){
5273 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5276 send_email(from => $from,
5278 subject => $subject,
5279 body => $notify_template->fill_in( PACKAGE =>
5280 'FS::notify_template::_template' ),
5285 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5287 Generates a templated notification to the customer (see L<Text::Template>).
5289 OPTIONS is a hash and may include
5291 I<extra_fields> - a hashref of name/value pairs which will be substituted
5292 into the template. These values may override values mentioned below
5293 and those from the customer record.
5295 The following variables are available in the template instead of or in addition
5296 to the fields of the customer record.
5298 I<$payby> - a description of the method of payment for the customer
5299 # would be nice to use FS::payby::shortname
5300 I<$payinfo> - the masked account information used to collect for this customer
5301 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5302 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5306 # a lot like cust_bill::print_latex
5307 sub generate_letter {
5308 my ($self, $template, %options) = @_;
5310 return unless $conf->exists($template);
5312 my $letter_template = new Text::Template
5314 SOURCE => [ map "$_\n", $conf->config($template)],
5315 DELIMITERS => [ '[@--', '--@]' ],
5317 or die "can't create new Text::Template object: Text::Template::ERROR";
5319 $letter_template->compile()
5320 or die "can't compile template: Text::Template::ERROR";
5322 my %letter_data = map { $_ => $self->$_ } $self->fields;
5323 $letter_data{payinfo} = $self->mask_payinfo;
5325 #my $paydate = $self->paydate || '2037-12-31';
5326 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5328 my $payby = $self->payby;
5329 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5330 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5332 #credit cards expire at the end of the month/year of their exp date
5333 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5334 $letter_data{payby} = 'credit card';
5335 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5336 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5338 }elsif ($payby eq 'COMP') {
5339 $letter_data{payby} = 'complimentary account';
5341 $letter_data{payby} = 'current method';
5343 $letter_data{expdate} = $expire_time;
5345 for (keys %{$options{extra_fields}}){
5346 $letter_data{$_} = $options{extra_fields}->{$_};
5349 unless(exists($letter_data{returnaddress})){
5350 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5351 $self->agent_template)
5353 if ( length($retadd) ) {
5354 $letter_data{returnaddress} = $retadd;
5355 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5356 $letter_data{returnaddress} =
5357 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5361 ( $conf->config('company_name', $self->agentnum),
5362 $conf->config('company_address', $self->agentnum),
5366 $letter_data{returnaddress} = '~';
5370 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5372 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5374 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5376 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5380 ) or die "can't open temp file: $!\n";
5381 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5382 or die "can't write temp file: $!\n";
5384 $letter_data{'logo_file'} = $lh->filename;
5386 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5390 ) or die "can't open temp file: $!\n";
5392 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5394 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5395 return ($1, $letter_data{'logo_file'});
5399 =item print_ps TEMPLATE
5401 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5407 my($file, $lfile) = $self->generate_letter(@_);
5408 my $ps = FS::Misc::generate_ps($file);
5409 unlink($file.'.tex');
5415 =item print TEMPLATE
5417 Prints the filled in template.
5419 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5423 sub queueable_print {
5426 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5427 or die "invalid customer number: " . $opt{custvnum};
5429 my $error = $self->print( $opt{template} );
5430 die $error if $error;
5434 my ($self, $template) = (shift, shift);
5435 do_print [ $self->print_ps($template) ];
5438 #these three subs should just go away once agent stuff is all config overrides
5440 sub agent_template {
5442 $self->_agent_plandata('agent_templatename');
5445 sub agent_invoice_from {
5447 $self->_agent_plandata('agent_invoice_from');
5450 sub _agent_plandata {
5451 my( $self, $option ) = @_;
5453 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5454 #agent-specific Conf
5456 use FS::part_event::Condition;
5458 my $agentnum = $self->agentnum;
5460 my $regexp = regexp_sql();
5462 my $part_event_option =
5464 'select' => 'part_event_option.*',
5465 'table' => 'part_event_option',
5467 LEFT JOIN part_event USING ( eventpart )
5468 LEFT JOIN part_event_option AS peo_agentnum
5469 ON ( part_event.eventpart = peo_agentnum.eventpart
5470 AND peo_agentnum.optionname = 'agentnum'
5471 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5473 LEFT JOIN part_event_condition
5474 ON ( part_event.eventpart = part_event_condition.eventpart
5475 AND part_event_condition.conditionname = 'cust_bill_age'
5477 LEFT JOIN part_event_condition_option
5478 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5479 AND part_event_condition_option.optionname = 'age'
5482 #'hashref' => { 'optionname' => $option },
5483 #'hashref' => { 'part_event_option.optionname' => $option },
5485 " WHERE part_event_option.optionname = ". dbh->quote($option).
5486 " AND action = 'cust_bill_send_agent' ".
5487 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5488 " AND peo_agentnum.optionname = 'agentnum' ".
5489 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5491 CASE WHEN part_event_condition_option.optionname IS NULL
5493 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5495 , part_event.weight".
5499 unless ( $part_event_option ) {
5500 return $self->agent->invoice_template || ''
5501 if $option eq 'agent_templatename';
5505 $part_event_option->optionvalue;
5509 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5511 Subroutine (not a method), designed to be called from the queue.
5513 Takes a list of options and values.
5515 Pulls up the customer record via the custnum option and calls bill_and_collect.
5520 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5522 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5523 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5525 $cust_main->bill_and_collect( %args );
5528 sub process_bill_and_collect {
5530 my $param = thaw(decode_base64(shift));
5531 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5532 or die "custnum '$param->{custnum}' not found!\n";
5533 $param->{'job'} = $job;
5534 $param->{'fatal'} = 1; # runs from job queue, will be caught
5535 $param->{'retry'} = 1;
5537 $cust_main->bill_and_collect( %$param );
5540 sub _upgrade_data { #class method
5541 my ($class, %opts) = @_;
5543 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
5544 my $sth = dbh->prepare($sql) or die dbh->errstr;
5545 $sth->execute or die $sth->errstr;
5547 local($ignore_expired_card) = 1;
5548 local($ignore_illegal_zip) = 1;
5549 local($skip_fuzzyfiles) = 1;
5550 $class->_upgrade_otaker(%opts);
5560 The delete method should possibly take an FS::cust_main object reference
5561 instead of a scalar customer number.
5563 Bill and collect options should probably be passed as references instead of a
5566 There should probably be a configuration file with a list of allowed credit
5569 No multiple currency support (probably a larger project than just this module).
5571 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5573 Birthdates rely on negative epoch values.
5575 The payby for card/check batches is broken. With mixed batching, bad
5578 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5582 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5583 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5584 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.