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
12 $ignore_expired_card $ignore_illegal_zip $ignore_banned_card
13 $skip_fuzzyfiles @fuzzyfields
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;
61 use FS::payment_gateway;
62 use FS::agent_payment_gateway;
66 # 1 is mostly method/subroutine entry and options
67 # 2 traces progress of some operations
68 # 3 is even more information including possibly sensitive data
70 $me = '[FS::cust_main]';
73 $ignore_expired_card = 0;
74 $ignore_illegal_zip = 0;
75 $ignore_banned_card = 0;
78 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
80 @encrypted_fields = ('payinfo', 'paycvv');
81 sub nohistory_fields { ('payinfo', 'paycvv'); }
83 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
85 #ask FS::UID to run this stuff for us later
86 #$FS::UID::callback{'FS::cust_main'} = sub {
87 install_callback FS::UID sub {
89 #yes, need it for stuff below (prolly should be cached)
94 my ( $hashref, $cache ) = @_;
95 if ( exists $hashref->{'pkgnum'} ) {
96 #@{ $self->{'_pkgnum'} } = ();
97 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
98 $self->{'_pkgnum'} = $subcache;
99 #push @{ $self->{'_pkgnum'} },
100 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
106 FS::cust_main - Object methods for cust_main records
112 $record = new FS::cust_main \%hash;
113 $record = new FS::cust_main { 'column' => 'value' };
115 $error = $record->insert;
117 $error = $new_record->replace($old_record);
119 $error = $record->delete;
121 $error = $record->check;
123 @cust_pkg = $record->all_pkgs;
125 @cust_pkg = $record->ncancelled_pkgs;
127 @cust_pkg = $record->suspended_pkgs;
129 $error = $record->bill;
130 $error = $record->bill %options;
131 $error = $record->bill 'time' => $time;
133 $error = $record->collect;
134 $error = $record->collect %options;
135 $error = $record->collect 'invoice_time' => $time,
140 An FS::cust_main object represents a customer. FS::cust_main inherits from
141 FS::Record. The following fields are currently supported:
147 Primary key (assigned automatically for new customers)
151 Agent (see L<FS::agent>)
155 Advertising source (see L<FS::part_referral>)
167 Cocial security number (optional)
183 (optional, see L<FS::cust_main_county>)
187 (see L<FS::cust_main_county>)
193 (see L<FS::cust_main_county>)
229 (optional, see L<FS::cust_main_county>)
233 (see L<FS::cust_main_county>)
239 (see L<FS::cust_main_county>)
255 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
259 Payment Information (See L<FS::payinfo_Mixin> for data format)
263 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
267 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
271 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
275 Start date month (maestro/solo cards only)
279 Start date year (maestro/solo cards only)
283 Issue number (maestro/solo cards only)
287 Name on card or billing name
291 IP address from which payment information was received
295 Tax exempt, empty or `Y'
299 Order taker (see L<FS::access_user>)
305 =item referral_custnum
307 Referring customer number
311 Enable individual CDR spooling, empty or `Y'
315 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
319 Discourage individual CDR printing, empty or `Y'
329 Creates a new customer. To add the customer to the database, see L<"insert">.
331 Note that this stores the hash reference, not a distinct copy of the hash it
332 points to. You can ask the object for a copy with the I<hash> method.
336 sub table { 'cust_main'; }
338 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
340 Adds this customer to the database. If there is an error, returns the error,
341 otherwise returns false.
343 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
344 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
345 are inserted atomicly, or the transaction is rolled back. Passing an empty
346 hash reference is equivalent to not supplying this parameter. There should be
347 a better explanation of this, but until then, here's an example:
350 tie %hash, 'Tie::RefHash'; #this part is important
352 $cust_pkg => [ $svc_acct ],
355 $cust_main->insert( \%hash );
357 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
358 be set as the invoicing list (see L<"invoicing_list">). Errors return as
359 expected and rollback the entire transaction; it is not necessary to call
360 check_invoicing_list first. The invoicing_list is set after the records in the
361 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
362 invoicing_list destination to the newly-created svc_acct. Here's an example:
364 $cust_main->insert( {}, [ $email, 'POST' ] );
366 Currently available options are: I<depend_jobnum>, I<noexport> and I<tax_exemption>.
368 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
369 on the supplied jobnum (they will not run until the specific job completes).
370 This can be used to defer provisioning until some action completes (such
371 as running the customer's credit card successfully).
373 The I<noexport> option is deprecated. If I<noexport> is set true, no
374 provisioning jobs (exports) are scheduled. (You can schedule them later with
375 the B<reexport> method.)
377 The I<tax_exemption> option can be set to an arrayref of tax names.
378 FS::cust_main_exemption records will be created and inserted.
384 my $cust_pkgs = @_ ? shift : {};
385 my $invoicing_list = @_ ? shift : '';
387 warn "$me insert called with options ".
388 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
391 local $SIG{HUP} = 'IGNORE';
392 local $SIG{INT} = 'IGNORE';
393 local $SIG{QUIT} = 'IGNORE';
394 local $SIG{TERM} = 'IGNORE';
395 local $SIG{TSTP} = 'IGNORE';
396 local $SIG{PIPE} = 'IGNORE';
398 my $oldAutoCommit = $FS::UID::AutoCommit;
399 local $FS::UID::AutoCommit = 0;
402 my $prepay_identifier = '';
403 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
405 if ( $self->payby eq 'PREPAY' ) {
407 $self->payby('BILL');
408 $prepay_identifier = $self->payinfo;
411 warn " looking up prepaid card $prepay_identifier\n"
414 my $error = $self->get_prepay( $prepay_identifier,
415 'amount_ref' => \$amount,
416 'seconds_ref' => \$seconds,
417 'upbytes_ref' => \$upbytes,
418 'downbytes_ref' => \$downbytes,
419 'totalbytes_ref' => \$totalbytes,
422 $dbh->rollback if $oldAutoCommit;
423 #return "error applying prepaid card (transaction rolled back): $error";
427 $payby = 'PREP' if $amount;
429 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
432 $self->payby('BILL');
433 $amount = $self->paid;
437 warn " inserting $self\n"
440 $self->signupdate(time) unless $self->signupdate;
442 $self->auto_agent_custid()
443 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
445 my $error = $self->SUPER::insert;
447 $dbh->rollback if $oldAutoCommit;
448 #return "inserting cust_main record (transaction rolled back): $error";
452 warn " setting invoicing list\n"
455 if ( $invoicing_list ) {
456 $error = $self->check_invoicing_list( $invoicing_list );
458 $dbh->rollback if $oldAutoCommit;
459 #return "checking invoicing_list (transaction rolled back): $error";
462 $self->invoicing_list( $invoicing_list );
465 warn " setting customer tags\n"
468 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
469 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
470 'custnum' => $self->custnum };
471 my $error = $cust_tag->insert;
473 $dbh->rollback if $oldAutoCommit;
478 if ( $invoicing_list ) {
479 $error = $self->check_invoicing_list( $invoicing_list );
481 $dbh->rollback if $oldAutoCommit;
482 #return "checking invoicing_list (transaction rolled back): $error";
485 $self->invoicing_list( $invoicing_list );
489 warn " setting cust_main_exemption\n"
492 my $tax_exemption = delete $options{'tax_exemption'};
493 if ( $tax_exemption ) {
494 foreach my $taxname ( @$tax_exemption ) {
495 my $cust_main_exemption = new FS::cust_main_exemption {
496 'custnum' => $self->custnum,
497 'taxname' => $taxname,
499 my $error = $cust_main_exemption->insert;
501 $dbh->rollback if $oldAutoCommit;
502 return "inserting cust_main_exemption (transaction rolled back): $error";
507 if ( $conf->config('cust_main-skeleton_tables')
508 && $conf->config('cust_main-skeleton_custnum') ) {
510 warn " inserting skeleton records\n"
513 my $error = $self->start_copy_skel;
515 $dbh->rollback if $oldAutoCommit;
521 warn " ordering packages\n"
524 $error = $self->order_pkgs( $cust_pkgs,
526 'seconds_ref' => \$seconds,
527 'upbytes_ref' => \$upbytes,
528 'downbytes_ref' => \$downbytes,
529 'totalbytes_ref' => \$totalbytes,
532 $dbh->rollback if $oldAutoCommit;
537 $dbh->rollback if $oldAutoCommit;
538 return "No svc_acct record to apply pre-paid time";
540 if ( $upbytes || $downbytes || $totalbytes ) {
541 $dbh->rollback if $oldAutoCommit;
542 return "No svc_acct record to apply pre-paid data";
546 warn " inserting initial $payby payment of $amount\n"
548 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
550 $dbh->rollback if $oldAutoCommit;
551 return "inserting payment (transaction rolled back): $error";
555 unless ( $import || $skip_fuzzyfiles ) {
556 warn " queueing fuzzyfiles update\n"
558 $error = $self->queue_fuzzyfiles_update;
560 $dbh->rollback if $oldAutoCommit;
561 return "updating fuzzy search cache: $error";
566 warn " exporting\n" if $DEBUG > 1;
568 my $export_args = $options{'export_args'} || [];
571 map qsearch( 'part_export', {exportnum=>$_} ),
572 $conf->config('cust_main-exports'); #, $agentnum
574 foreach my $part_export ( @part_export ) {
575 my $error = $part_export->export_insert($self, @$export_args);
577 $dbh->rollback if $oldAutoCommit;
578 return "exporting to ". $part_export->exporttype.
579 " (transaction rolled back): $error";
583 #foreach my $depend_jobnum ( @$depend_jobnums ) {
584 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
586 # foreach my $jobnum ( @jobnums ) {
587 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
588 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
590 # my $error = $queue->depend_insert($depend_jobnum);
592 # $dbh->rollback if $oldAutoCommit;
593 # return "error queuing job dependancy: $error";
600 #if ( exists $options{'jobnums'} ) {
601 # push @{ $options{'jobnums'} }, @jobnums;
604 warn " insert complete; committing transaction\n"
607 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
612 use File::CounterFile;
613 sub auto_agent_custid {
616 my $format = $conf->config('cust_main-auto_agent_custid');
618 if ( $format eq '1YMMXXXXXXXX' ) {
620 my $counter = new File::CounterFile 'cust_main.agent_custid';
623 my $ym = 100000000000 + time2str('%y%m00000000', time);
624 if ( $ym > $counter->value ) {
625 $counter->{'value'} = $agent_custid = $ym;
626 $counter->{'updated'} = 1;
628 $agent_custid = $counter->inc;
634 die "Unknown cust_main-auto_agent_custid format: $format";
637 $self->agent_custid($agent_custid);
641 sub start_copy_skel {
644 #'mg_user_preference' => {},
645 #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
646 #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
647 #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
648 #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
649 my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
652 _copy_skel( 'cust_main', #tablename
653 $conf->config('cust_main-skeleton_custnum'), #sourceid
654 $self->custnum, #destid
655 @tables, #child tables
659 #recursive subroutine, not a method
661 my( $table, $sourceid, $destid, %child_tables ) = @_;
664 if ( $table =~ /^(\w+)\.(\w+)$/ ) {
665 ( $table, $primary_key ) = ( $1, $2 );
667 my $dbdef_table = dbdef->table($table);
668 $primary_key = $dbdef_table->primary_key
669 or return "$table has no primary key".
670 " (or do you need to run dbdef-create?)";
673 warn " _copy_skel: $table.$primary_key $sourceid to $destid for ".
674 join (', ', keys %child_tables). "\n"
677 foreach my $child_table_def ( keys %child_tables ) {
681 if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
682 ( $child_table, $child_pkey ) = ( $1, $2 );
684 $child_table = $child_table_def;
686 $child_pkey = dbdef->table($child_table)->primary_key;
687 # or return "$table has no primary key".
688 # " (or do you need to run dbdef-create?)\n";
692 if ( keys %{ $child_tables{$child_table_def} } ) {
694 return "$child_table has no primary key".
695 " (run dbdef-create or try specifying it?)\n"
698 #false laziness w/Record::insert and only works on Pg
699 #refactor the proper last-inserted-id stuff out of Record::insert if this
700 # ever gets use for anything besides a quick kludge for one customer
701 my $default = dbdef->table($child_table)->column($child_pkey)->default;
702 $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
703 or return "can't parse $child_table.$child_pkey default value ".
704 " for sequence name: $default";
709 my @sel_columns = grep { $_ ne $primary_key }
710 dbdef->table($child_table)->columns;
711 my $sel_columns = join(', ', @sel_columns );
713 my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
714 my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
715 my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
717 my $sel_st = "SELECT $sel_columns FROM $child_table".
718 " WHERE $primary_key = $sourceid";
721 my $sel_sth = dbh->prepare( $sel_st )
722 or return dbh->errstr;
724 $sel_sth->execute or return $sel_sth->errstr;
726 while ( my $row = $sel_sth->fetchrow_hashref ) {
728 warn " selected row: ".
729 join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
733 "INSERT INTO $child_table $ins_columns VALUES $placeholders";
734 my $ins_sth =dbh->prepare($statement)
735 or return dbh->errstr;
736 my @param = ( $destid, map $row->{$_}, @ins_columns );
737 warn " $statement: [ ". join(', ', @param). " ]\n"
739 $ins_sth->execute( @param )
740 or return $ins_sth->errstr;
742 #next unless keys %{ $child_tables{$child_table} };
743 next unless $sequence;
745 #another section of that laziness
746 my $seq_sql = "SELECT currval('$sequence')";
747 my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
748 $seq_sth->execute or return $seq_sth->errstr;
749 my $insertid = $seq_sth->fetchrow_arrayref->[0];
751 # don't drink soap! recurse! recurse! okay!
753 _copy_skel( $child_table_def,
754 $row->{$child_pkey}, #sourceid
756 %{ $child_tables{$child_table_def} },
758 return $error if $error;
768 =item order_pkg HASHREF | OPTION => VALUE ...
770 Orders a single package.
772 Options may be passed as a list of key/value pairs or as a hash reference.
783 Optional FS::cust_location object
787 Optional arryaref of FS::svc_* service objects.
791 If this option is set to a job queue jobnum (see L<FS::queue>), all provisioning
792 jobs will have a dependancy on the supplied job (they will not run until the
793 specific job completes). This can be used to defer provisioning until some
794 action completes (such as running the customer's credit card successfully).
798 Optional subject for a ticket created and attached to this customer
802 Optional queue name for ticket additions
810 my $opt = ref($_[0]) ? shift : { @_ };
812 warn "$me order_pkg called with options ".
813 join(', ', map { "$_: $opt->{$_}" } keys %$opt ). "\n"
816 my $cust_pkg = $opt->{'cust_pkg'};
817 my $svcs = $opt->{'svcs'} || [];
819 my %svc_options = ();
820 $svc_options{'depend_jobnum'} = $opt->{'depend_jobnum'}
821 if exists($opt->{'depend_jobnum'}) && $opt->{'depend_jobnum'};
823 my %insert_params = map { $opt->{$_} ? ( $_ => $opt->{$_} ) : () }
824 qw( ticket_subject ticket_queue );
826 local $SIG{HUP} = 'IGNORE';
827 local $SIG{INT} = 'IGNORE';
828 local $SIG{QUIT} = 'IGNORE';
829 local $SIG{TERM} = 'IGNORE';
830 local $SIG{TSTP} = 'IGNORE';
831 local $SIG{PIPE} = 'IGNORE';
833 my $oldAutoCommit = $FS::UID::AutoCommit;
834 local $FS::UID::AutoCommit = 0;
837 if ( $opt->{'cust_location'} &&
838 ( ! $cust_pkg->locationnum || $cust_pkg->locationnum == -1 ) ) {
839 my $error = $opt->{'cust_location'}->insert;
841 $dbh->rollback if $oldAutoCommit;
842 return "inserting cust_location (transaction rolled back): $error";
844 $cust_pkg->locationnum($opt->{'cust_location'}->locationnum);
847 $cust_pkg->custnum( $self->custnum );
849 my $error = $cust_pkg->insert( %insert_params );
851 $dbh->rollback if $oldAutoCommit;
852 return "inserting cust_pkg (transaction rolled back): $error";
855 foreach my $svc_something ( @{ $opt->{'svcs'} } ) {
856 if ( $svc_something->svcnum ) {
857 my $old_cust_svc = $svc_something->cust_svc;
858 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
859 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
860 $error = $new_cust_svc->replace($old_cust_svc);
862 $svc_something->pkgnum( $cust_pkg->pkgnum );
863 if ( $svc_something->isa('FS::svc_acct') ) {
864 foreach ( grep { $opt->{$_.'_ref'} && ${ $opt->{$_.'_ref'} } }
865 qw( seconds upbytes downbytes totalbytes ) ) {
866 $svc_something->$_( $svc_something->$_() + ${ $opt->{$_.'_ref'} } );
867 ${ $opt->{$_.'_ref'} } = 0;
870 $error = $svc_something->insert(%svc_options);
873 $dbh->rollback if $oldAutoCommit;
874 return "inserting svc_ (transaction rolled back): $error";
878 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
883 #deprecated #=item order_pkgs HASHREF [ , SECONDSREF ] [ , OPTION => VALUE ... ]
884 =item order_pkgs HASHREF [ , OPTION => VALUE ... ]
886 Like the insert method on an existing record, this method orders multiple
887 packages and included services atomicaly. Pass a Tie::RefHash data structure
888 to this method containing FS::cust_pkg and FS::svc_I<tablename> objects.
889 There should be a better explanation of this, but until then, here's an
893 tie %hash, 'Tie::RefHash'; #this part is important
895 $cust_pkg => [ $svc_acct ],
898 $cust_main->order_pkgs( \%hash, 'noexport'=>1 );
900 Services can be new, in which case they are inserted, or existing unaudited
901 services, in which case they are linked to the newly-created package.
903 Currently available options are: I<depend_jobnum>, I<noexport>, I<seconds_ref>,
904 I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.
906 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
907 on the supplied jobnum (they will not run until the specific job completes).
908 This can be used to defer provisioning until some action completes (such
909 as running the customer's credit card successfully).
911 The I<noexport> option is deprecated. If I<noexport> is set true, no
912 provisioning jobs (exports) are scheduled. (You can schedule them later with
913 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
914 on the cust_main object is not recommended, as existing services will also be
917 If I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, or I<totalbytes_ref> is
918 provided, the scalars (provided by references) will be incremented by the
919 values of the prepaid card.`
925 my $cust_pkgs = shift;
926 my $seconds_ref = ref($_[0]) ? shift : ''; #deprecated
928 $seconds_ref ||= $options{'seconds_ref'};
930 warn "$me order_pkgs called with options ".
931 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
934 local $SIG{HUP} = 'IGNORE';
935 local $SIG{INT} = 'IGNORE';
936 local $SIG{QUIT} = 'IGNORE';
937 local $SIG{TERM} = 'IGNORE';
938 local $SIG{TSTP} = 'IGNORE';
939 local $SIG{PIPE} = 'IGNORE';
941 my $oldAutoCommit = $FS::UID::AutoCommit;
942 local $FS::UID::AutoCommit = 0;
945 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
947 foreach my $cust_pkg ( keys %$cust_pkgs ) {
949 my $error = $self->order_pkg(
950 'cust_pkg' => $cust_pkg,
951 'svcs' => $cust_pkgs->{$cust_pkg},
952 'seconds_ref' => $seconds_ref,
953 map { $_ => $options{$_} } qw( upbytes_ref downbytes_ref totalbytes_ref
958 $dbh->rollback if $oldAutoCommit;
964 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
968 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
970 Recharges this (existing) customer with the specified prepaid card (see
971 L<FS::prepay_credit>), specified either by I<identifier> or as an
972 FS::prepay_credit object. If there is an error, returns the error, otherwise
975 Optionally, five scalar references can be passed as well. They will have their
976 values filled in with the amount, number of seconds, and number of upload,
977 download, and total bytes applied by this prepaid card.
981 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
982 #the only place that uses these args
983 sub recharge_prepay {
984 my( $self, $prepay_credit, $amountref, $secondsref,
985 $upbytesref, $downbytesref, $totalbytesref ) = @_;
987 local $SIG{HUP} = 'IGNORE';
988 local $SIG{INT} = 'IGNORE';
989 local $SIG{QUIT} = 'IGNORE';
990 local $SIG{TERM} = 'IGNORE';
991 local $SIG{TSTP} = 'IGNORE';
992 local $SIG{PIPE} = 'IGNORE';
994 my $oldAutoCommit = $FS::UID::AutoCommit;
995 local $FS::UID::AutoCommit = 0;
998 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
1000 my $error = $self->get_prepay( $prepay_credit,
1001 'amount_ref' => \$amount,
1002 'seconds_ref' => \$seconds,
1003 'upbytes_ref' => \$upbytes,
1004 'downbytes_ref' => \$downbytes,
1005 'totalbytes_ref' => \$totalbytes,
1007 || $self->increment_seconds($seconds)
1008 || $self->increment_upbytes($upbytes)
1009 || $self->increment_downbytes($downbytes)
1010 || $self->increment_totalbytes($totalbytes)
1011 || $self->insert_cust_pay_prepay( $amount,
1013 ? $prepay_credit->identifier
1018 $dbh->rollback if $oldAutoCommit;
1022 if ( defined($amountref) ) { $$amountref = $amount; }
1023 if ( defined($secondsref) ) { $$secondsref = $seconds; }
1024 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
1025 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
1026 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
1028 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1033 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
1035 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
1036 specified either by I<identifier> or as an FS::prepay_credit object.
1038 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
1039 incremented by the values of the prepaid card.
1041 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
1042 check or set this customer's I<agentnum>.
1044 If there is an error, returns the error, otherwise returns false.
1050 my( $self, $prepay_credit, %opt ) = @_;
1052 local $SIG{HUP} = 'IGNORE';
1053 local $SIG{INT} = 'IGNORE';
1054 local $SIG{QUIT} = 'IGNORE';
1055 local $SIG{TERM} = 'IGNORE';
1056 local $SIG{TSTP} = 'IGNORE';
1057 local $SIG{PIPE} = 'IGNORE';
1059 my $oldAutoCommit = $FS::UID::AutoCommit;
1060 local $FS::UID::AutoCommit = 0;
1063 unless ( ref($prepay_credit) ) {
1065 my $identifier = $prepay_credit;
1067 $prepay_credit = qsearchs(
1069 { 'identifier' => $prepay_credit },
1074 unless ( $prepay_credit ) {
1075 $dbh->rollback if $oldAutoCommit;
1076 return "Invalid prepaid card: ". $identifier;
1081 if ( $prepay_credit->agentnum ) {
1082 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
1083 $dbh->rollback if $oldAutoCommit;
1084 return "prepaid card not valid for agent ". $self->agentnum;
1086 $self->agentnum($prepay_credit->agentnum);
1089 my $error = $prepay_credit->delete;
1091 $dbh->rollback if $oldAutoCommit;
1092 return "removing prepay_credit (transaction rolled back): $error";
1095 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
1096 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
1098 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1103 =item increment_upbytes SECONDS
1105 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1106 the specified number of upbytes. If there is an error, returns the error,
1107 otherwise returns false.
1111 sub increment_upbytes {
1112 _increment_column( shift, 'upbytes', @_);
1115 =item increment_downbytes SECONDS
1117 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1118 the specified number of downbytes. If there is an error, returns the error,
1119 otherwise returns false.
1123 sub increment_downbytes {
1124 _increment_column( shift, 'downbytes', @_);
1127 =item increment_totalbytes SECONDS
1129 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1130 the specified number of totalbytes. If there is an error, returns the error,
1131 otherwise returns false.
1135 sub increment_totalbytes {
1136 _increment_column( shift, 'totalbytes', @_);
1139 =item increment_seconds SECONDS
1141 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1142 the specified number of seconds. If there is an error, returns the error,
1143 otherwise returns false.
1147 sub increment_seconds {
1148 _increment_column( shift, 'seconds', @_);
1151 =item _increment_column AMOUNT
1153 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1154 the specified number of seconds or bytes. If there is an error, returns
1155 the error, otherwise returns false.
1159 sub _increment_column {
1160 my( $self, $column, $amount ) = @_;
1161 warn "$me increment_column called: $column, $amount\n"
1164 return '' unless $amount;
1166 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1167 $self->ncancelled_pkgs;
1169 if ( ! @cust_pkg ) {
1170 return 'No packages with primary or single services found'.
1171 ' to apply pre-paid time';
1172 } elsif ( scalar(@cust_pkg) > 1 ) {
1173 #maybe have a way to specify the package/account?
1174 return 'Multiple packages found to apply pre-paid time';
1177 my $cust_pkg = $cust_pkg[0];
1178 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1182 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1184 if ( ! @cust_svc ) {
1185 return 'No account found to apply pre-paid time';
1186 } elsif ( scalar(@cust_svc) > 1 ) {
1187 return 'Multiple accounts found to apply pre-paid time';
1190 my $svc_acct = $cust_svc[0]->svc_x;
1191 warn " found service svcnum ". $svc_acct->pkgnum.
1192 ' ('. $svc_acct->email. ")\n"
1195 $column = "increment_$column";
1196 $svc_acct->$column($amount);
1200 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1202 Inserts a prepayment in the specified amount for this customer. An optional
1203 second argument can specify the prepayment identifier for tracking purposes.
1204 If there is an error, returns the error, otherwise returns false.
1208 sub insert_cust_pay_prepay {
1209 shift->insert_cust_pay('PREP', @_);
1212 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1214 Inserts a cash payment in the specified amount for this customer. An optional
1215 second argument can specify the payment identifier for tracking purposes.
1216 If there is an error, returns the error, otherwise returns false.
1220 sub insert_cust_pay_cash {
1221 shift->insert_cust_pay('CASH', @_);
1224 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1226 Inserts a Western Union payment in the specified amount for this customer. An
1227 optional second argument can specify the prepayment identifier for tracking
1228 purposes. If there is an error, returns the error, otherwise returns false.
1232 sub insert_cust_pay_west {
1233 shift->insert_cust_pay('WEST', @_);
1236 sub insert_cust_pay {
1237 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1238 my $payinfo = scalar(@_) ? shift : '';
1240 my $cust_pay = new FS::cust_pay {
1241 'custnum' => $self->custnum,
1242 'paid' => sprintf('%.2f', $amount),
1243 #'_date' => #date the prepaid card was purchased???
1245 'payinfo' => $payinfo,
1253 This method is deprecated. See the I<depend_jobnum> option to the insert and
1254 order_pkgs methods for a better way to defer provisioning.
1256 Re-schedules all exports by calling the B<reexport> method of all associated
1257 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1258 otherwise returns false.
1265 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1266 "use the depend_jobnum option to insert or order_pkgs to delay export";
1268 local $SIG{HUP} = 'IGNORE';
1269 local $SIG{INT} = 'IGNORE';
1270 local $SIG{QUIT} = 'IGNORE';
1271 local $SIG{TERM} = 'IGNORE';
1272 local $SIG{TSTP} = 'IGNORE';
1273 local $SIG{PIPE} = 'IGNORE';
1275 my $oldAutoCommit = $FS::UID::AutoCommit;
1276 local $FS::UID::AutoCommit = 0;
1279 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1280 my $error = $cust_pkg->reexport;
1282 $dbh->rollback if $oldAutoCommit;
1287 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1292 =item delete [ OPTION => VALUE ... ]
1294 This deletes the customer. If there is an error, returns the error, otherwise
1297 This will completely remove all traces of the customer record. This is not
1298 what you want when a customer cancels service; for that, cancel all of the
1299 customer's packages (see L</cancel>).
1301 If the customer has any uncancelled packages, you need to pass a new (valid)
1302 customer number for those packages to be transferred to, as the "new_customer"
1303 option. Cancelled packages will be deleted. Did I mention that this is NOT
1304 what you want when a customer cancels service and that you really should be
1305 looking at L<FS::cust_pkg/cancel>?
1307 You can't delete a customer with invoices (see L<FS::cust_bill>),
1308 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1309 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1310 set the "delete_financials" option to a true value.
1315 my( $self, %opt ) = @_;
1317 local $SIG{HUP} = 'IGNORE';
1318 local $SIG{INT} = 'IGNORE';
1319 local $SIG{QUIT} = 'IGNORE';
1320 local $SIG{TERM} = 'IGNORE';
1321 local $SIG{TSTP} = 'IGNORE';
1322 local $SIG{PIPE} = 'IGNORE';
1324 my $oldAutoCommit = $FS::UID::AutoCommit;
1325 local $FS::UID::AutoCommit = 0;
1328 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1329 $dbh->rollback if $oldAutoCommit;
1330 return "Can't delete a master agent customer";
1333 #use FS::access_user
1334 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1335 $dbh->rollback if $oldAutoCommit;
1336 return "Can't delete a master employee customer";
1339 tie my %financial_tables, 'Tie::IxHash',
1340 'cust_bill' => 'invoices',
1341 'cust_statement' => 'statements',
1342 'cust_credit' => 'credits',
1343 'cust_pay' => 'payments',
1344 'cust_refund' => 'refunds',
1347 foreach my $table ( keys %financial_tables ) {
1349 my @records = $self->$table();
1351 if ( @records && ! $opt{'delete_financials'} ) {
1352 $dbh->rollback if $oldAutoCommit;
1353 return "Can't delete a customer with ". $financial_tables{$table};
1356 foreach my $record ( @records ) {
1357 my $error = $record->delete;
1359 $dbh->rollback if $oldAutoCommit;
1360 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1366 my @cust_pkg = $self->ncancelled_pkgs;
1368 my $new_custnum = $opt{'new_custnum'};
1369 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1370 $dbh->rollback if $oldAutoCommit;
1371 return "Invalid new customer number: $new_custnum";
1373 foreach my $cust_pkg ( @cust_pkg ) {
1374 my %hash = $cust_pkg->hash;
1375 $hash{'custnum'} = $new_custnum;
1376 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1377 my $error = $new_cust_pkg->replace($cust_pkg,
1378 options => { $cust_pkg->options },
1381 $dbh->rollback if $oldAutoCommit;
1386 my @cancelled_cust_pkg = $self->all_pkgs;
1387 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1388 my $error = $cust_pkg->delete;
1390 $dbh->rollback if $oldAutoCommit;
1395 #cust_tax_adjustment in financials?
1396 #cust_pay_pending? ouch
1398 foreach my $table (qw(
1399 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1400 cust_location cust_main_note cust_tax_adjustment
1401 cust_pay_void cust_pay_batch queue cust_tax_exempt
1403 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1404 my $error = $record->delete;
1406 $dbh->rollback if $oldAutoCommit;
1412 my $sth = $dbh->prepare(
1413 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1415 my $errstr = $dbh->errstr;
1416 $dbh->rollback if $oldAutoCommit;
1419 $sth->execute($self->custnum) or do {
1420 my $errstr = $sth->errstr;
1421 $dbh->rollback if $oldAutoCommit;
1427 my $ticket_dbh = '';
1428 if ($conf->config('ticket_system') eq 'RT_Internal') {
1430 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1431 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1432 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1433 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1436 if ( $ticket_dbh ) {
1438 my $ticket_sth = $ticket_dbh->prepare(
1439 'DELETE FROM Links WHERE Target = ?'
1441 my $errstr = $ticket_dbh->errstr;
1442 $dbh->rollback if $oldAutoCommit;
1445 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1447 my $errstr = $ticket_sth->errstr;
1448 $dbh->rollback if $oldAutoCommit;
1452 #check and see if the customer is the only link on the ticket, and
1453 #if so, set the ticket to deleted status in RT?
1454 #maybe someday, for now this will at least fix tickets not displaying
1458 #delete the customer record
1460 my $error = $self->SUPER::delete;
1462 $dbh->rollback if $oldAutoCommit;
1466 # cust_main exports!
1468 #my $export_args = $options{'export_args'} || [];
1471 map qsearch( 'part_export', {exportnum=>$_} ),
1472 $conf->config('cust_main-exports'); #, $agentnum
1474 foreach my $part_export ( @part_export ) {
1475 my $error = $part_export->export_delete( $self ); #, @$export_args);
1477 $dbh->rollback if $oldAutoCommit;
1478 return "exporting to ". $part_export->exporttype.
1479 " (transaction rolled back): $error";
1483 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1488 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1491 Replaces the OLD_RECORD with this one in the database. If there is an error,
1492 returns the error, otherwise returns false.
1494 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1495 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1496 expected and rollback the entire transaction; it is not necessary to call
1497 check_invoicing_list first. Here's an example:
1499 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1501 Currently available options are: I<tax_exemption>.
1503 The I<tax_exemption> option can be set to an arrayref of tax names.
1504 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1511 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1513 : $self->replace_old;
1517 warn "$me replace called\n"
1520 my $curuser = $FS::CurrentUser::CurrentUser;
1521 if ( $self->payby eq 'COMP'
1522 && $self->payby ne $old->payby
1523 && ! $curuser->access_right('Complimentary customer')
1526 return "You are not permitted to create complimentary accounts.";
1529 local($ignore_expired_card) = 1
1530 if $old->payby =~ /^(CARD|DCRD)$/
1531 && $self->payby =~ /^(CARD|DCRD)$/
1532 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1534 local $SIG{HUP} = 'IGNORE';
1535 local $SIG{INT} = 'IGNORE';
1536 local $SIG{QUIT} = 'IGNORE';
1537 local $SIG{TERM} = 'IGNORE';
1538 local $SIG{TSTP} = 'IGNORE';
1539 local $SIG{PIPE} = 'IGNORE';
1541 my $oldAutoCommit = $FS::UID::AutoCommit;
1542 local $FS::UID::AutoCommit = 0;
1545 my $error = $self->SUPER::replace($old);
1548 $dbh->rollback if $oldAutoCommit;
1552 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1553 my $invoicing_list = shift @param;
1554 $error = $self->check_invoicing_list( $invoicing_list );
1556 $dbh->rollback if $oldAutoCommit;
1559 $self->invoicing_list( $invoicing_list );
1562 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1564 #this could be more efficient than deleting and re-inserting, if it matters
1565 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1566 my $error = $cust_tag->delete;
1568 $dbh->rollback if $oldAutoCommit;
1572 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1573 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1574 'custnum' => $self->custnum };
1575 my $error = $cust_tag->insert;
1577 $dbh->rollback if $oldAutoCommit;
1584 my %options = @param;
1586 my $tax_exemption = delete $options{'tax_exemption'};
1587 if ( $tax_exemption ) {
1589 my %cust_main_exemption =
1590 map { $_->taxname => $_ }
1591 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1593 foreach my $taxname ( @$tax_exemption ) {
1595 next if delete $cust_main_exemption{$taxname};
1597 my $cust_main_exemption = new FS::cust_main_exemption {
1598 'custnum' => $self->custnum,
1599 'taxname' => $taxname,
1601 my $error = $cust_main_exemption->insert;
1603 $dbh->rollback if $oldAutoCommit;
1604 return "inserting cust_main_exemption (transaction rolled back): $error";
1608 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1609 my $error = $cust_main_exemption->delete;
1611 $dbh->rollback if $oldAutoCommit;
1612 return "deleting cust_main_exemption (transaction rolled back): $error";
1618 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1619 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1620 && $self->get('payinfo') !~ /^99\d{14}$/
1622 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1627 # card/check/lec info has changed, want to retry realtime_ invoice events
1628 my $error = $self->retry_realtime;
1630 $dbh->rollback if $oldAutoCommit;
1635 unless ( $import || $skip_fuzzyfiles ) {
1636 $error = $self->queue_fuzzyfiles_update;
1638 $dbh->rollback if $oldAutoCommit;
1639 return "updating fuzzy search cache: $error";
1643 # cust_main exports!
1645 my $export_args = $options{'export_args'} || [];
1648 map qsearch( 'part_export', {exportnum=>$_} ),
1649 $conf->config('cust_main-exports'); #, $agentnum
1651 foreach my $part_export ( @part_export ) {
1652 my $error = $part_export->export_replace( $self, $old, @$export_args);
1654 $dbh->rollback if $oldAutoCommit;
1655 return "exporting to ". $part_export->exporttype.
1656 " (transaction rolled back): $error";
1660 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1665 =item queue_fuzzyfiles_update
1667 Used by insert & replace to update the fuzzy search cache
1671 sub queue_fuzzyfiles_update {
1674 local $SIG{HUP} = 'IGNORE';
1675 local $SIG{INT} = 'IGNORE';
1676 local $SIG{QUIT} = 'IGNORE';
1677 local $SIG{TERM} = 'IGNORE';
1678 local $SIG{TSTP} = 'IGNORE';
1679 local $SIG{PIPE} = 'IGNORE';
1681 my $oldAutoCommit = $FS::UID::AutoCommit;
1682 local $FS::UID::AutoCommit = 0;
1685 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1686 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1688 $dbh->rollback if $oldAutoCommit;
1689 return "queueing job (transaction rolled back): $error";
1692 if ( $self->ship_last ) {
1693 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1694 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1696 $dbh->rollback if $oldAutoCommit;
1697 return "queueing job (transaction rolled back): $error";
1701 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1708 Checks all fields to make sure this is a valid customer record. If there is
1709 an error, returns the error, otherwise returns false. Called by the insert
1710 and replace methods.
1717 warn "$me check BEFORE: \n". $self->_dump
1721 $self->ut_numbern('custnum')
1722 || $self->ut_number('agentnum')
1723 || $self->ut_textn('agent_custid')
1724 || $self->ut_number('refnum')
1725 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1726 || $self->ut_textn('custbatch')
1727 || $self->ut_name('last')
1728 || $self->ut_name('first')
1729 || $self->ut_snumbern('birthdate')
1730 || $self->ut_snumbern('signupdate')
1731 || $self->ut_textn('company')
1732 || $self->ut_text('address1')
1733 || $self->ut_textn('address2')
1734 || $self->ut_text('city')
1735 || $self->ut_textn('county')
1736 || $self->ut_textn('state')
1737 || $self->ut_country('country')
1738 || $self->ut_anything('comments')
1739 || $self->ut_numbern('referral_custnum')
1740 || $self->ut_textn('stateid')
1741 || $self->ut_textn('stateid_state')
1742 || $self->ut_textn('invoice_terms')
1743 || $self->ut_alphan('geocode')
1744 || $self->ut_floatn('cdr_termination_percentage')
1747 #barf. need message catalogs. i18n. etc.
1748 $error .= "Please select an advertising source."
1749 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1750 return $error if $error;
1752 return "Unknown agent"
1753 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1755 return "Unknown refnum"
1756 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1758 return "Unknown referring custnum: ". $self->referral_custnum
1759 unless ! $self->referral_custnum
1760 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1762 if ( $self->censustract ne '' ) {
1763 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1764 or return "Illegal census tract: ". $self->censustract;
1766 $self->censustract("$1.$2");
1769 if ( $self->ss eq '' ) {
1774 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1775 or return "Illegal social security number: ". $self->ss;
1776 $self->ss("$1-$2-$3");
1780 # bad idea to disable, causes billing to fail because of no tax rates later
1781 # except we don't fail any more
1782 unless ( $import ) {
1783 unless ( qsearch('cust_main_county', {
1784 'country' => $self->country,
1787 return "Unknown state/county/country: ".
1788 $self->state. "/". $self->county. "/". $self->country
1789 unless qsearch('cust_main_county',{
1790 'state' => $self->state,
1791 'county' => $self->county,
1792 'country' => $self->country,
1798 $self->ut_phonen('daytime', $self->country)
1799 || $self->ut_phonen('night', $self->country)
1800 || $self->ut_phonen('fax', $self->country)
1802 return $error if $error;
1804 unless ( $ignore_illegal_zip ) {
1805 $error = $self->ut_zip('zip', $self->country);
1806 return $error if $error;
1809 if ( $conf->exists('cust_main-require_phone')
1810 && ! length($self->daytime) && ! length($self->night)
1813 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1815 : FS::Msgcat::_gettext('daytime');
1816 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1818 : FS::Msgcat::_gettext('night');
1820 return "$daytime_label or $night_label is required"
1824 if ( $self->has_ship_address
1825 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1826 $self->addr_fields )
1830 $self->ut_name('ship_last')
1831 || $self->ut_name('ship_first')
1832 || $self->ut_textn('ship_company')
1833 || $self->ut_text('ship_address1')
1834 || $self->ut_textn('ship_address2')
1835 || $self->ut_text('ship_city')
1836 || $self->ut_textn('ship_county')
1837 || $self->ut_textn('ship_state')
1838 || $self->ut_country('ship_country')
1840 return $error if $error;
1842 #false laziness with above
1843 unless ( qsearchs('cust_main_county', {
1844 'country' => $self->ship_country,
1847 return "Unknown ship_state/ship_county/ship_country: ".
1848 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1849 unless qsearch('cust_main_county',{
1850 'state' => $self->ship_state,
1851 'county' => $self->ship_county,
1852 'country' => $self->ship_country,
1858 $self->ut_phonen('ship_daytime', $self->ship_country)
1859 || $self->ut_phonen('ship_night', $self->ship_country)
1860 || $self->ut_phonen('ship_fax', $self->ship_country)
1862 return $error if $error;
1864 unless ( $ignore_illegal_zip ) {
1865 $error = $self->ut_zip('ship_zip', $self->ship_country);
1866 return $error if $error;
1868 return "Unit # is required."
1869 if $self->ship_address2 =~ /^\s*$/
1870 && $conf->exists('cust_main-require_address2');
1872 } else { # ship_ info eq billing info, so don't store dup info in database
1874 $self->setfield("ship_$_", '')
1875 foreach $self->addr_fields;
1877 return "Unit # is required."
1878 if $self->address2 =~ /^\s*$/
1879 && $conf->exists('cust_main-require_address2');
1883 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1884 # or return "Illegal payby: ". $self->payby;
1886 FS::payby->can_payby($self->table, $self->payby)
1887 or return "Illegal payby: ". $self->payby;
1889 $error = $self->ut_numbern('paystart_month')
1890 || $self->ut_numbern('paystart_year')
1891 || $self->ut_numbern('payissue')
1892 || $self->ut_textn('paytype')
1894 return $error if $error;
1896 if ( $self->payip eq '' ) {
1899 $error = $self->ut_ip('payip');
1900 return $error if $error;
1903 # If it is encrypted and the private key is not availaible then we can't
1904 # check the credit card.
1905 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1907 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1909 my $payinfo = $self->payinfo;
1910 $payinfo =~ s/\D//g;
1911 $payinfo =~ /^(\d{13,16})$/
1912 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1914 $self->payinfo($payinfo);
1916 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1918 return gettext('unknown_card_type')
1919 if $self->payinfo !~ /^99\d{14}$/ #token
1920 && cardtype($self->payinfo) eq "Unknown";
1922 unless ( $ignore_banned_card ) {
1923 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1925 return 'Banned credit card: banned on '.
1926 time2str('%a %h %o at %r', $ban->_date).
1927 ' by '. $ban->otaker.
1928 ' (ban# '. $ban->bannum. ')';
1932 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1933 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1934 $self->paycvv =~ /^(\d{4})$/
1935 or return "CVV2 (CID) for American Express cards is four digits.";
1938 $self->paycvv =~ /^(\d{3})$/
1939 or return "CVV2 (CVC2/CID) is three digits.";
1946 my $cardtype = cardtype($payinfo);
1947 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1949 return "Start date or issue number is required for $cardtype cards"
1950 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1952 return "Start month must be between 1 and 12"
1953 if $self->paystart_month
1954 and $self->paystart_month < 1 || $self->paystart_month > 12;
1956 return "Start year must be 1990 or later"
1957 if $self->paystart_year
1958 and $self->paystart_year < 1990;
1960 return "Issue number must be beween 1 and 99"
1962 and $self->payissue < 1 || $self->payissue > 99;
1965 $self->paystart_month('');
1966 $self->paystart_year('');
1967 $self->payissue('');
1970 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1972 my $payinfo = $self->payinfo;
1973 $payinfo =~ s/[^\d\@]//g;
1974 if ( $conf->exists('echeck-nonus') ) {
1975 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1976 $payinfo = "$1\@$2";
1978 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1979 $payinfo = "$1\@$2";
1981 $self->payinfo($payinfo);
1984 my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1986 return 'Banned ACH account: banned on '.
1987 time2str('%a %h %o at %r', $ban->_date).
1988 ' by '. $ban->otaker.
1989 ' (ban# '. $ban->bannum. ')';
1992 } elsif ( $self->payby eq 'LECB' ) {
1994 my $payinfo = $self->payinfo;
1995 $payinfo =~ s/\D//g;
1996 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1998 $self->payinfo($payinfo);
2001 } elsif ( $self->payby eq 'BILL' ) {
2003 $error = $self->ut_textn('payinfo');
2004 return "Illegal P.O. number: ". $self->payinfo if $error;
2007 } elsif ( $self->payby eq 'COMP' ) {
2009 my $curuser = $FS::CurrentUser::CurrentUser;
2010 if ( ! $self->custnum
2011 && ! $curuser->access_right('Complimentary customer')
2014 return "You are not permitted to create complimentary accounts."
2017 $error = $self->ut_textn('payinfo');
2018 return "Illegal comp account issuer: ". $self->payinfo if $error;
2021 } elsif ( $self->payby eq 'PREPAY' ) {
2023 my $payinfo = $self->payinfo;
2024 $payinfo =~ s/\W//g; #anything else would just confuse things
2025 $self->payinfo($payinfo);
2026 $error = $self->ut_alpha('payinfo');
2027 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2028 return "Unknown prepayment identifier"
2029 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2034 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2035 return "Expiration date required"
2036 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2040 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2041 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2042 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2043 ( $m, $y ) = ( $2, "19$1" );
2044 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2045 ( $m, $y ) = ( $3, "20$2" );
2047 return "Illegal expiration date: ". $self->paydate;
2049 $self->paydate("$y-$m-01");
2050 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2051 return gettext('expired_card')
2053 && !$ignore_expired_card
2054 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2057 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2058 ( ! $conf->exists('require_cardname')
2059 || $self->payby !~ /^(CARD|DCRD)$/ )
2061 $self->payname( $self->first. " ". $self->getfield('last') );
2063 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2064 or return gettext('illegal_name'). " payname: ". $self->payname;
2068 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2069 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2073 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2075 warn "$me check AFTER: \n". $self->_dump
2078 $self->SUPER::check;
2083 Returns a list of fields which have ship_ duplicates.
2088 qw( last first company
2089 address1 address2 city county state zip country
2094 =item has_ship_address
2096 Returns true if this customer record has a separate shipping address.
2100 sub has_ship_address {
2102 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2107 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2108 city, county, state, zip, country. The shipping address is used if present.
2112 #geocode? dependent on tax-ship_address config, not available in cust_location
2113 #mostly. not yet then.
2117 my $prefix = $self->has_ship_address ? 'ship_' : '';
2119 map { $_ => $self->get($prefix.$_) }
2120 qw( address1 address2 city county state zip country geocode );
2121 #fields that cust_location has
2124 =item all_pkgs [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
2126 Returns all packages (see L<FS::cust_pkg>) for this customer.
2132 my $extra_qsearch = ref($_[0]) ? shift : { @_ };
2134 return $self->num_pkgs unless wantarray || keys %$extra_qsearch;
2137 if ( $self->{'_pkgnum'} && ! keys %$extra_qsearch ) {
2138 @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
2140 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2143 map { $_ } sort sort_packages @cust_pkg;
2148 Synonym for B<all_pkgs>.
2153 shift->all_pkgs(@_);
2158 Returns all locations (see L<FS::cust_location>) for this customer.
2164 qsearch('cust_location', { 'custnum' => $self->custnum } );
2167 =item location_label [ OPTION => VALUE ... ]
2169 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
2177 used to separate the address elements (defaults to ', ')
2179 =item escape_function
2181 a callback used for escaping the text of the address elements
2187 # false laziness with FS::cust_location::line
2189 sub location_label {
2193 my $separator = $opt{join_string} || ', ';
2194 my $escape = $opt{escape_function} || sub{ shift };
2196 my $cydefault = FS::conf->new->config('countrydefault') || 'US';
2197 my $prefix = length($self->ship_last) ? 'ship_' : '';
2200 foreach (qw ( address1 address2 ) ) {
2201 my $method = "$prefix$_";
2202 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
2207 foreach (qw ( city county state zip ) ) {
2208 my $method = "$prefix$_";
2209 if ( $self->$method ) {
2210 $line .= ' (' if $method eq 'county';
2211 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
2212 $line .= ' )' if $method eq 'county';
2216 $line .= $separator. &$escape(code2country($self->country))
2217 if $self->country ne $cydefault;
2222 =item ncancelled_pkgs [ EXTRA_QSEARCH_PARAMS_HASHREF ]
2224 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
2228 sub ncancelled_pkgs {
2230 my $extra_qsearch = ref($_[0]) ? shift : {};
2232 return $self->num_ncancelled_pkgs unless wantarray;
2235 if ( $self->{'_pkgnum'} ) {
2237 warn "$me ncancelled_pkgs: returning cached objects"
2240 @cust_pkg = grep { ! $_->getfield('cancel') }
2241 values %{ $self->{'_pkgnum'}->cache };
2245 warn "$me ncancelled_pkgs: searching for packages with custnum ".
2246 $self->custnum. "\n"
2249 $extra_qsearch->{'extra_sql'} .= ' AND ( cancel IS NULL OR cancel = 0 ) ';
2251 @cust_pkg = $self->_cust_pkg($extra_qsearch);
2255 sort sort_packages @cust_pkg;
2261 my $extra_qsearch = ref($_[0]) ? shift : {};
2263 $extra_qsearch->{'select'} ||= '*';
2264 $extra_qsearch->{'select'} .=
2265 ',( SELECT COUNT(*) FROM cust_svc WHERE cust_pkg.pkgnum = cust_svc.pkgnum )
2269 $_->{'_num_cust_svc'} = $_->get('_num_cust_svc');
2274 'table' => 'cust_pkg',
2275 'hashref' => { 'custnum' => $self->custnum },
2280 # This should be generalized to use config options to determine order.
2283 my $locationsort = ( $a->locationnum || 0 ) <=> ( $b->locationnum || 0 );
2284 return $locationsort if $locationsort;
2286 if ( $a->get('cancel') xor $b->get('cancel') ) {
2287 return -1 if $b->get('cancel');
2288 return 1 if $a->get('cancel');
2289 #shouldn't get here...
2292 my $a_num_cust_svc = $a->num_cust_svc;
2293 my $b_num_cust_svc = $b->num_cust_svc;
2294 return 0 if !$a_num_cust_svc && !$b_num_cust_svc;
2295 return -1 if $a_num_cust_svc && !$b_num_cust_svc;
2296 return 1 if !$a_num_cust_svc && $b_num_cust_svc;
2297 my @a_cust_svc = $a->cust_svc;
2298 my @b_cust_svc = $b->cust_svc;
2299 return 0 if !scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2300 return -1 if scalar(@a_cust_svc) && !scalar(@b_cust_svc);
2301 return 1 if !scalar(@a_cust_svc) && scalar(@b_cust_svc);
2302 $a_cust_svc[0]->svc_x->label cmp $b_cust_svc[0]->svc_x->label;
2307 =item suspended_pkgs
2309 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
2313 sub suspended_pkgs {
2315 grep { $_->susp } $self->ncancelled_pkgs;
2318 =item unflagged_suspended_pkgs
2320 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
2321 customer (thouse packages without the `manual_flag' set).
2325 sub unflagged_suspended_pkgs {
2327 return $self->suspended_pkgs
2328 unless dbdef->table('cust_pkg')->column('manual_flag');
2329 grep { ! $_->manual_flag } $self->suspended_pkgs;
2332 =item unsuspended_pkgs
2334 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
2339 sub unsuspended_pkgs {
2341 grep { ! $_->susp } $self->ncancelled_pkgs;
2344 =item next_bill_date
2346 Returns the next date this customer will be billed, as a UNIX timestamp, or
2347 undef if no active package has a next bill date.
2351 sub next_bill_date {
2353 min( map $_->get('bill'), grep $_->get('bill'), $self->unsuspended_pkgs );
2356 =item num_cancelled_pkgs
2358 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
2363 sub num_cancelled_pkgs {
2364 shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
2367 sub num_ncancelled_pkgs {
2368 shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
2372 my( $self ) = shift;
2373 my $sql = scalar(@_) ? shift : '';
2374 $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
2375 my $sth = dbh->prepare(
2376 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
2377 ) or die dbh->errstr;
2378 $sth->execute($self->custnum) or die $sth->errstr;
2379 $sth->fetchrow_arrayref->[0];
2384 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2385 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2386 on success or a list of errors.
2392 grep { $_->unsuspend } $self->suspended_pkgs;
2397 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2399 Returns a list: an empty list on success or a list of errors.
2405 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2408 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2410 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2411 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2412 of a list of pkgparts; the hashref has the following keys:
2416 =item pkgparts - listref of pkgparts
2418 =item (other options are passed to the suspend method)
2423 Returns a list: an empty list on success or a list of errors.
2427 sub suspend_if_pkgpart {
2429 my (@pkgparts, %opt);
2430 if (ref($_[0]) eq 'HASH'){
2431 @pkgparts = @{$_[0]{pkgparts}};
2436 grep { $_->suspend(%opt) }
2437 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2438 $self->unsuspended_pkgs;
2441 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2443 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2444 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2445 instead of a list of pkgparts; the hashref has the following keys:
2449 =item pkgparts - listref of pkgparts
2451 =item (other options are passed to the suspend method)
2455 Returns a list: an empty list on success or a list of errors.
2459 sub suspend_unless_pkgpart {
2461 my (@pkgparts, %opt);
2462 if (ref($_[0]) eq 'HASH'){
2463 @pkgparts = @{$_[0]{pkgparts}};
2468 grep { $_->suspend(%opt) }
2469 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2470 $self->unsuspended_pkgs;
2473 =item cancel [ OPTION => VALUE ... ]
2475 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2477 Available options are:
2481 =item quiet - can be set true to supress email cancellation notices.
2483 =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.
2485 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2487 =item nobill - can be set true to skip billing if it might otherwise be done.
2491 Always returns a list: an empty list on success or a list of errors.
2495 # nb that dates are not specified as valid options to this method
2498 my( $self, %opt ) = @_;
2500 warn "$me cancel called on customer ". $self->custnum. " with options ".
2501 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2504 return ( 'access denied' )
2505 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2507 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2509 #should try decryption (we might have the private key)
2510 # and if not maybe queue a job for the server that does?
2511 return ( "Can't (yet) ban encrypted credit cards" )
2512 if $self->is_encrypted($self->payinfo);
2514 my $ban = new FS::banned_pay $self->_banned_pay_hashref;
2515 my $error = $ban->insert;
2516 return ( $error ) if $error;
2520 my @pkgs = $self->ncancelled_pkgs;
2522 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2524 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2525 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2529 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2530 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2533 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2536 sub _banned_pay_hashref {
2547 'payby' => $payby2ban{$self->payby},
2548 'payinfo' => md5_base64($self->payinfo),
2549 #don't ever *search* on reason! #'reason' =>
2555 Returns all notes (see L<FS::cust_main_note>) for this customer.
2562 qsearch( 'cust_main_note',
2563 { 'custnum' => $self->custnum },
2565 'ORDER BY _DATE DESC'
2571 Returns the agent (see L<FS::agent>) for this customer.
2577 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2582 Returns the agent name (see L<FS::agent>) for this customer.
2588 $self->agent->agent;
2593 Returns any tags associated with this customer, as FS::cust_tag objects,
2594 or an empty list if there are no tags.
2600 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2605 Returns any tags associated with this customer, as FS::part_tag objects,
2606 or an empty list if there are no tags.
2612 map $_->part_tag, $self->cust_tag;
2618 Returns the customer class, as an FS::cust_class object, or the empty string
2619 if there is no customer class.
2625 if ( $self->classnum ) {
2626 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2634 Returns the customer category name, or the empty string if there is no customer
2641 my $cust_class = $self->cust_class;
2643 ? $cust_class->categoryname
2649 Returns the customer class name, or the empty string if there is no customer
2656 my $cust_class = $self->cust_class;
2658 ? $cust_class->classname
2662 =item BILLING METHODS
2664 Documentation on billing methods has been moved to
2665 L<FS::cust_main::Billing>.
2667 =item REALTIME BILLING METHODS
2669 Documentation on realtime billing methods has been moved to
2670 L<FS::cust_main::Billing_Realtime>.
2674 Removes the I<paycvv> field from the database directly.
2676 If there is an error, returns the error, otherwise returns false.
2682 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2683 or return dbh->errstr;
2684 $sth->execute($self->custnum)
2685 or return $sth->errstr;
2690 =item batch_card OPTION => VALUE...
2692 Adds a payment for this invoice to the pending credit card batch (see
2693 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2694 runs the payment using a realtime gateway.
2699 my ($self, %options) = @_;
2702 if (exists($options{amount})) {
2703 $amount = $options{amount};
2705 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2707 return '' unless $amount > 0;
2709 my $invnum = delete $options{invnum};
2710 my $payby = $options{invnum} || $self->payby; #dubious
2712 if ($options{'realtime'}) {
2713 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2719 my $oldAutoCommit = $FS::UID::AutoCommit;
2720 local $FS::UID::AutoCommit = 0;
2723 #this needs to handle mysql as well as Pg, like svc_acct.pm
2724 #(make it into a common function if folks need to do batching with mysql)
2725 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2726 or return "Cannot lock pay_batch: " . $dbh->errstr;
2730 'payby' => FS::payby->payby2payment($payby),
2733 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2735 unless ( $pay_batch ) {
2736 $pay_batch = new FS::pay_batch \%pay_batch;
2737 my $error = $pay_batch->insert;
2739 $dbh->rollback if $oldAutoCommit;
2740 die "error creating new batch: $error\n";
2744 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2745 'batchnum' => $pay_batch->batchnum,
2746 'custnum' => $self->custnum,
2749 foreach (qw( address1 address2 city state zip country payby payinfo paydate
2751 $options{$_} = '' unless exists($options{$_});
2754 my $cust_pay_batch = new FS::cust_pay_batch ( {
2755 'batchnum' => $pay_batch->batchnum,
2756 'invnum' => $invnum || 0, # is there a better value?
2757 # this field should be
2759 # cust_bill_pay_batch now
2760 'custnum' => $self->custnum,
2761 'last' => $self->getfield('last'),
2762 'first' => $self->getfield('first'),
2763 'address1' => $options{address1} || $self->address1,
2764 'address2' => $options{address2} || $self->address2,
2765 'city' => $options{city} || $self->city,
2766 'state' => $options{state} || $self->state,
2767 'zip' => $options{zip} || $self->zip,
2768 'country' => $options{country} || $self->country,
2769 'payby' => $options{payby} || $self->payby,
2770 'payinfo' => $options{payinfo} || $self->payinfo,
2771 'exp' => $options{paydate} || $self->paydate,
2772 'payname' => $options{payname} || $self->payname,
2773 'amount' => $amount, # consolidating
2776 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2777 if $old_cust_pay_batch;
2780 if ($old_cust_pay_batch) {
2781 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2783 $error = $cust_pay_batch->insert;
2787 $dbh->rollback if $oldAutoCommit;
2791 my $unapplied = $self->total_unapplied_credits
2792 + $self->total_unapplied_payments
2793 + $self->in_transit_payments;
2794 foreach my $cust_bill ($self->open_cust_bill) {
2795 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2796 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2797 'invnum' => $cust_bill->invnum,
2798 'paybatchnum' => $cust_pay_batch->paybatchnum,
2799 'amount' => $cust_bill->owed,
2802 if ($unapplied >= $cust_bill_pay_batch->amount){
2803 $unapplied -= $cust_bill_pay_batch->amount;
2806 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2807 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2809 $error = $cust_bill_pay_batch->insert;
2811 $dbh->rollback if $oldAutoCommit;
2816 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2822 Returns the total owed for this customer on all invoices
2823 (see L<FS::cust_bill/owed>).
2829 $self->total_owed_date(2145859200); #12/31/2037
2832 =item total_owed_date TIME
2834 Returns the total owed for this customer on all invoices with date earlier than
2835 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2836 see L<Time::Local> and L<Date::Parse> for conversion functions.
2840 sub total_owed_date {
2844 my $custnum = $self->custnum;
2846 my $owed_sql = FS::cust_bill->owed_sql;
2849 SELECT SUM($owed_sql) FROM cust_bill
2850 WHERE custnum = $custnum
2854 sprintf( "%.2f", $self->scalar_sql($sql) );
2858 =item total_owed_pkgnum PKGNUM
2860 Returns the total owed on all invoices for this customer's specific package
2861 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2865 sub total_owed_pkgnum {
2866 my( $self, $pkgnum ) = @_;
2867 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2870 =item total_owed_date_pkgnum TIME PKGNUM
2872 Returns the total owed for this customer's specific package when using
2873 experimental package balances on all invoices with date earlier than
2874 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2875 see L<Time::Local> and L<Date::Parse> for conversion functions.
2879 sub total_owed_date_pkgnum {
2880 my( $self, $time, $pkgnum ) = @_;
2883 foreach my $cust_bill (
2884 grep { $_->_date <= $time }
2885 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2887 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2889 sprintf( "%.2f", $total_bill );
2895 Returns the total amount of all payments.
2902 $total += $_->paid foreach $self->cust_pay;
2903 sprintf( "%.2f", $total );
2906 =item total_unapplied_credits
2908 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2909 customer. See L<FS::cust_credit/credited>.
2911 =item total_credited
2913 Old name for total_unapplied_credits. Don't use.
2917 sub total_credited {
2918 #carp "total_credited deprecated, use total_unapplied_credits";
2919 shift->total_unapplied_credits(@_);
2922 sub total_unapplied_credits {
2925 my $custnum = $self->custnum;
2927 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2930 SELECT SUM($unapplied_sql) FROM cust_credit
2931 WHERE custnum = $custnum
2934 sprintf( "%.2f", $self->scalar_sql($sql) );
2938 =item total_unapplied_credits_pkgnum PKGNUM
2940 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2941 customer. See L<FS::cust_credit/credited>.
2945 sub total_unapplied_credits_pkgnum {
2946 my( $self, $pkgnum ) = @_;
2947 my $total_credit = 0;
2948 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2949 sprintf( "%.2f", $total_credit );
2953 =item total_unapplied_payments
2955 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2956 See L<FS::cust_pay/unapplied>.
2960 sub total_unapplied_payments {
2963 my $custnum = $self->custnum;
2965 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2968 SELECT SUM($unapplied_sql) FROM cust_pay
2969 WHERE custnum = $custnum
2972 sprintf( "%.2f", $self->scalar_sql($sql) );
2976 =item total_unapplied_payments_pkgnum PKGNUM
2978 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2979 specific package when using experimental package balances. See
2980 L<FS::cust_pay/unapplied>.
2984 sub total_unapplied_payments_pkgnum {
2985 my( $self, $pkgnum ) = @_;
2986 my $total_unapplied = 0;
2987 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2988 sprintf( "%.2f", $total_unapplied );
2992 =item total_unapplied_refunds
2994 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2995 customer. See L<FS::cust_refund/unapplied>.
2999 sub total_unapplied_refunds {
3001 my $custnum = $self->custnum;
3003 my $unapplied_sql = FS::cust_refund->unapplied_sql;
3006 SELECT SUM($unapplied_sql) FROM cust_refund
3007 WHERE custnum = $custnum
3010 sprintf( "%.2f", $self->scalar_sql($sql) );
3016 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3017 total_unapplied_credits minus total_unapplied_payments).
3023 $self->balance_date_range;
3026 =item balance_date TIME
3028 Returns the balance for this customer, only considering invoices with date
3029 earlier than TIME (total_owed_date minus total_credited minus
3030 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3031 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3038 $self->balance_date_range(shift);
3041 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
3043 Returns the balance for this customer, optionally considering invoices with
3044 date earlier than START_TIME, and not later than END_TIME
3045 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
3047 Times are specified as SQL fragments or numeric
3048 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
3049 L<Date::Parse> for conversion functions. The empty string can be passed
3050 to disable that time constraint completely.
3052 Available options are:
3056 =item unapplied_date
3058 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)
3064 sub balance_date_range {
3066 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
3067 ') FROM cust_main WHERE custnum='. $self->custnum;
3068 sprintf( '%.2f', $self->scalar_sql($sql) );
3071 =item balance_pkgnum PKGNUM
3073 Returns the balance for this customer's specific package when using
3074 experimental package balances (total_owed plus total_unrefunded, minus
3075 total_unapplied_credits minus total_unapplied_payments)
3079 sub balance_pkgnum {
3080 my( $self, $pkgnum ) = @_;
3083 $self->total_owed_pkgnum($pkgnum)
3084 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
3085 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
3086 - $self->total_unapplied_credits_pkgnum($pkgnum)
3087 - $self->total_unapplied_payments_pkgnum($pkgnum)
3091 =item in_transit_payments
3093 Returns the total of requests for payments for this customer pending in
3094 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3098 sub in_transit_payments {
3100 my $in_transit_payments = 0;
3101 foreach my $pay_batch ( qsearch('pay_batch', {
3104 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3105 'batchnum' => $pay_batch->batchnum,
3106 'custnum' => $self->custnum,
3108 $in_transit_payments += $cust_pay_batch->amount;
3111 sprintf( "%.2f", $in_transit_payments );
3116 Returns a hash of useful information for making a payment.
3126 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3127 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3128 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3132 For credit card transactions:
3144 For electronic check transactions:
3159 $return{balance} = $self->balance;
3161 $return{payname} = $self->payname
3162 || ( $self->first. ' '. $self->get('last') );
3164 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
3166 $return{payby} = $self->payby;
3167 $return{stateid_state} = $self->stateid_state;
3169 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3170 $return{card_type} = cardtype($self->payinfo);
3171 $return{payinfo} = $self->paymask;
3173 @return{'month', 'year'} = $self->paydate_monthyear;
3177 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3178 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3179 $return{payinfo1} = $payinfo1;
3180 $return{payinfo2} = $payinfo2;
3181 $return{paytype} = $self->paytype;
3182 $return{paystate} = $self->paystate;
3186 #doubleclick protection
3188 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3194 =item paydate_monthyear
3196 Returns a two-element list consisting of the month and year of this customer's
3197 paydate (credit card expiration date for CARD customers)
3201 sub paydate_monthyear {
3203 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3205 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3212 =item tax_exemption TAXNAME
3217 my( $self, $taxname ) = @_;
3219 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3220 'taxname' => $taxname,
3225 =item cust_main_exemption
3229 sub cust_main_exemption {
3231 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3234 =item invoicing_list [ ARRAYREF ]
3236 If an arguement is given, sets these email addresses as invoice recipients
3237 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3238 (except as warnings), so use check_invoicing_list first.
3240 Returns a list of email addresses (with svcnum entries expanded).
3242 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3243 check it without disturbing anything by passing nothing.
3245 This interface may change in the future.
3249 sub invoicing_list {
3250 my( $self, $arrayref ) = @_;
3253 my @cust_main_invoice;
3254 if ( $self->custnum ) {
3255 @cust_main_invoice =
3256 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3258 @cust_main_invoice = ();
3260 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3261 #warn $cust_main_invoice->destnum;
3262 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3263 #warn $cust_main_invoice->destnum;
3264 my $error = $cust_main_invoice->delete;
3265 warn $error if $error;
3268 if ( $self->custnum ) {
3269 @cust_main_invoice =
3270 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3272 @cust_main_invoice = ();
3274 my %seen = map { $_->address => 1 } @cust_main_invoice;
3275 foreach my $address ( @{$arrayref} ) {
3276 next if exists $seen{$address} && $seen{$address};
3277 $seen{$address} = 1;
3278 my $cust_main_invoice = new FS::cust_main_invoice ( {
3279 'custnum' => $self->custnum,
3282 my $error = $cust_main_invoice->insert;
3283 warn $error if $error;
3287 if ( $self->custnum ) {
3289 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3296 =item check_invoicing_list ARRAYREF
3298 Checks these arguements as valid input for the invoicing_list method. If there
3299 is an error, returns the error, otherwise returns false.
3303 sub check_invoicing_list {
3304 my( $self, $arrayref ) = @_;
3306 foreach my $address ( @$arrayref ) {
3308 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3309 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3312 my $cust_main_invoice = new FS::cust_main_invoice ( {
3313 'custnum' => $self->custnum,
3316 my $error = $self->custnum
3317 ? $cust_main_invoice->check
3318 : $cust_main_invoice->checkdest
3320 return $error if $error;
3324 return "Email address required"
3325 if $conf->exists('cust_main-require_invoicing_list_email')
3326 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3331 =item set_default_invoicing_list
3333 Sets the invoicing list to all accounts associated with this customer,
3334 overwriting any previous invoicing list.
3338 sub set_default_invoicing_list {
3340 $self->invoicing_list($self->all_emails);
3345 Returns the email addresses of all accounts provisioned for this customer.
3352 foreach my $cust_pkg ( $self->all_pkgs ) {
3353 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3355 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3356 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3358 $list{$_}=1 foreach map { $_->email } @svc_acct;
3363 =item invoicing_list_addpost
3365 Adds postal invoicing to this customer. If this customer is already configured
3366 to receive postal invoices, does nothing.
3370 sub invoicing_list_addpost {
3372 return if grep { $_ eq 'POST' } $self->invoicing_list;
3373 my @invoicing_list = $self->invoicing_list;
3374 push @invoicing_list, 'POST';
3375 $self->invoicing_list(\@invoicing_list);
3378 =item invoicing_list_emailonly
3380 Returns the list of email invoice recipients (invoicing_list without non-email
3381 destinations such as POST and FAX).
3385 sub invoicing_list_emailonly {
3387 warn "$me invoicing_list_emailonly called"
3389 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3392 =item invoicing_list_emailonly_scalar
3394 Returns the list of email invoice recipients (invoicing_list without non-email
3395 destinations such as POST and FAX) as a comma-separated scalar.
3399 sub invoicing_list_emailonly_scalar {
3401 warn "$me invoicing_list_emailonly_scalar called"
3403 join(', ', $self->invoicing_list_emailonly);
3406 =item referral_custnum_cust_main
3408 Returns the customer who referred this customer (or the empty string, if
3409 this customer was not referred).
3411 Note the difference with referral_cust_main method: This method,
3412 referral_custnum_cust_main returns the single customer (if any) who referred
3413 this customer, while referral_cust_main returns an array of customers referred
3418 sub referral_custnum_cust_main {
3420 return '' unless $self->referral_custnum;
3421 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3424 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3426 Returns an array of customers referred by this customer (referral_custnum set
3427 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3428 customers referred by customers referred by this customer and so on, inclusive.
3429 The default behavior is DEPTH 1 (no recursion).
3431 Note the difference with referral_custnum_cust_main method: This method,
3432 referral_cust_main, returns an array of customers referred BY this customer,
3433 while referral_custnum_cust_main returns the single customer (if any) who
3434 referred this customer.
3438 sub referral_cust_main {
3440 my $depth = @_ ? shift : 1;
3441 my $exclude = @_ ? shift : {};
3444 map { $exclude->{$_->custnum}++; $_; }
3445 grep { ! $exclude->{ $_->custnum } }
3446 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3450 map { $_->referral_cust_main($depth-1, $exclude) }
3457 =item referral_cust_main_ncancelled
3459 Same as referral_cust_main, except only returns customers with uncancelled
3464 sub referral_cust_main_ncancelled {
3466 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3469 =item referral_cust_pkg [ DEPTH ]
3471 Like referral_cust_main, except returns a flat list of all unsuspended (and
3472 uncancelled) packages for each customer. The number of items in this list may
3473 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3477 sub referral_cust_pkg {
3479 my $depth = @_ ? shift : 1;
3481 map { $_->unsuspended_pkgs }
3482 grep { $_->unsuspended_pkgs }
3483 $self->referral_cust_main($depth);
3486 =item referring_cust_main
3488 Returns the single cust_main record for the customer who referred this customer
3489 (referral_custnum), or false.
3493 sub referring_cust_main {
3495 return '' unless $self->referral_custnum;
3496 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3499 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3501 Applies a credit to this customer. If there is an error, returns the error,
3502 otherwise returns false.
3504 REASON can be a text string, an FS::reason object, or a scalar reference to
3505 a reasonnum. If a text string, it will be automatically inserted as a new
3506 reason, and a 'reason_type' option must be passed to indicate the
3507 FS::reason_type for the new reason.
3509 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3511 Any other options are passed to FS::cust_credit::insert.
3516 my( $self, $amount, $reason, %options ) = @_;
3518 my $cust_credit = new FS::cust_credit {
3519 'custnum' => $self->custnum,
3520 'amount' => $amount,
3523 if ( ref($reason) ) {
3525 if ( ref($reason) eq 'SCALAR' ) {
3526 $cust_credit->reasonnum( $$reason );
3528 $cust_credit->reasonnum( $reason->reasonnum );
3532 $cust_credit->set('reason', $reason)
3535 for (qw( addlinfo eventnum )) {
3536 $cust_credit->$_( delete $options{$_} )
3537 if exists($options{$_});
3540 $cust_credit->insert(%options);
3544 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3546 Creates a one-time charge for this customer. If there is an error, returns
3547 the error, otherwise returns false.
3549 New-style, with a hashref of options:
3551 my $error = $cust_main->charge(
3555 'start_date' => str2time('7/4/2009'),
3556 'pkg' => 'Description',
3557 'comment' => 'Comment',
3558 'additional' => [], #extra invoice detail
3559 'classnum' => 1, #pkg_class
3561 'setuptax' => '', # or 'Y' for tax exempt
3564 'taxclass' => 'Tax class',
3567 'taxproduct' => 2, #part_pkg_taxproduct
3568 'override' => {}, #XXX describe
3570 #will be filled in with the new object
3571 'cust_pkg_ref' => \$cust_pkg,
3573 #generate an invoice immediately
3575 'invoice_terms' => '', #with these terms
3581 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3587 my ( $amount, $quantity, $start_date, $classnum );
3588 my ( $pkg, $comment, $additional );
3589 my ( $setuptax, $taxclass ); #internal taxes
3590 my ( $taxproduct, $override ); #vendor (CCH) taxes
3592 my $cust_pkg_ref = '';
3593 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3594 if ( ref( $_[0] ) ) {
3595 $amount = $_[0]->{amount};
3596 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3597 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3598 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3599 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3600 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3601 : '$'. sprintf("%.2f",$amount);
3602 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3603 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3604 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3605 $additional = $_[0]->{additional} || [];
3606 $taxproduct = $_[0]->{taxproductnum};
3607 $override = { '' => $_[0]->{tax_override} };
3608 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3609 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3610 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3615 $pkg = @_ ? shift : 'One-time charge';
3616 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3618 $taxclass = @_ ? shift : '';
3622 local $SIG{HUP} = 'IGNORE';
3623 local $SIG{INT} = 'IGNORE';
3624 local $SIG{QUIT} = 'IGNORE';
3625 local $SIG{TERM} = 'IGNORE';
3626 local $SIG{TSTP} = 'IGNORE';
3627 local $SIG{PIPE} = 'IGNORE';
3629 my $oldAutoCommit = $FS::UID::AutoCommit;
3630 local $FS::UID::AutoCommit = 0;
3633 my $part_pkg = new FS::part_pkg ( {
3635 'comment' => $comment,
3639 'classnum' => ( $classnum ? $classnum : '' ),
3640 'setuptax' => $setuptax,
3641 'taxclass' => $taxclass,
3642 'taxproductnum' => $taxproduct,
3645 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3646 ( 0 .. @$additional - 1 )
3648 'additional_count' => scalar(@$additional),
3649 'setup_fee' => $amount,
3652 my $error = $part_pkg->insert( options => \%options,
3653 tax_overrides => $override,
3656 $dbh->rollback if $oldAutoCommit;
3660 my $pkgpart = $part_pkg->pkgpart;
3661 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3662 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3663 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3664 $error = $type_pkgs->insert;
3666 $dbh->rollback if $oldAutoCommit;
3671 my $cust_pkg = new FS::cust_pkg ( {
3672 'custnum' => $self->custnum,
3673 'pkgpart' => $pkgpart,
3674 'quantity' => $quantity,
3675 'start_date' => $start_date,
3676 'no_auto' => $no_auto,
3679 $error = $cust_pkg->insert;
3681 $dbh->rollback if $oldAutoCommit;
3683 } elsif ( $cust_pkg_ref ) {
3684 ${$cust_pkg_ref} = $cust_pkg;
3688 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3689 'pkg_list' => [ $cust_pkg ],
3692 $dbh->rollback if $oldAutoCommit;
3697 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3702 #=item charge_postal_fee
3704 #Applies a one time charge this customer. If there is an error,
3705 #returns the error, returns the cust_pkg charge object or false
3706 #if there was no charge.
3710 # This should be a customer event. For that to work requires that bill
3711 # also be a customer event.
3713 sub charge_postal_fee {
3716 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
3717 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3719 my $cust_pkg = new FS::cust_pkg ( {
3720 'custnum' => $self->custnum,
3721 'pkgpart' => $pkgpart,
3725 my $error = $cust_pkg->insert;
3726 $error ? $error : $cust_pkg;
3729 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3731 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3733 Optionally, a list or hashref of additional arguments to the qsearch call can
3740 my $opt = ref($_[0]) ? shift : { @_ };
3742 #return $self->num_cust_bill unless wantarray || keys %$opt;
3744 $opt->{'table'} = 'cust_bill';
3745 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3746 $opt->{'hashref'}{'custnum'} = $self->custnum;
3747 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3749 map { $_ } #behavior of sort undefined in scalar context
3750 sort { $a->_date <=> $b->_date }
3754 =item open_cust_bill
3756 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3761 sub open_cust_bill {
3765 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3771 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3773 Returns all the statements (see L<FS::cust_statement>) for this customer.
3775 Optionally, a list or hashref of additional arguments to the qsearch call can
3780 sub cust_statement {
3782 my $opt = ref($_[0]) ? shift : { @_ };
3784 #return $self->num_cust_statement unless wantarray || keys %$opt;
3786 $opt->{'table'} = 'cust_statement';
3787 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3788 $opt->{'hashref'}{'custnum'} = $self->custnum;
3789 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3791 map { $_ } #behavior of sort undefined in scalar context
3792 sort { $a->_date <=> $b->_date }
3798 Returns all the credits (see L<FS::cust_credit>) for this customer.
3804 map { $_ } #return $self->num_cust_credit unless wantarray;
3805 sort { $a->_date <=> $b->_date }
3806 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3809 =item cust_credit_pkgnum
3811 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3812 package when using experimental package balances.
3816 sub cust_credit_pkgnum {
3817 my( $self, $pkgnum ) = @_;
3818 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3819 sort { $a->_date <=> $b->_date }
3820 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3821 'pkgnum' => $pkgnum,
3828 Returns all the payments (see L<FS::cust_pay>) for this customer.
3834 return $self->num_cust_pay unless wantarray;
3835 sort { $a->_date <=> $b->_date }
3836 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3841 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3842 called automatically when the cust_pay method is used in a scalar context.
3848 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3849 my $sth = dbh->prepare($sql) or die dbh->errstr;
3850 $sth->execute($self->custnum) or die $sth->errstr;
3851 $sth->fetchrow_arrayref->[0];
3854 =item cust_pay_pkgnum
3856 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3857 package when using experimental package balances.
3861 sub cust_pay_pkgnum {
3862 my( $self, $pkgnum ) = @_;
3863 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3864 sort { $a->_date <=> $b->_date }
3865 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3866 'pkgnum' => $pkgnum,
3873 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3879 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3880 sort { $a->_date <=> $b->_date }
3881 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3884 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3886 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3888 Optionally, a list or hashref of additional arguments to the qsearch call can
3893 sub cust_pay_batch {
3895 my $opt = ref($_[0]) ? shift : { @_ };
3897 #return $self->num_cust_statement unless wantarray || keys %$opt;
3899 $opt->{'table'} = 'cust_pay_batch';
3900 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3901 $opt->{'hashref'}{'custnum'} = $self->custnum;
3902 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3904 map { $_ } #behavior of sort undefined in scalar context
3905 sort { $a->paybatchnum <=> $b->paybatchnum }
3909 =item cust_pay_pending
3911 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3912 (without status "done").
3916 sub cust_pay_pending {
3918 return $self->num_cust_pay_pending unless wantarray;
3919 sort { $a->_date <=> $b->_date }
3920 qsearch( 'cust_pay_pending', {
3921 'custnum' => $self->custnum,
3922 'status' => { op=>'!=', value=>'done' },
3927 =item cust_pay_pending_attempt
3929 Returns all payment attempts / declined payments for this customer, as pending
3930 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3931 a corresponding payment (see L<FS::cust_pay>).
3935 sub cust_pay_pending_attempt {
3937 return $self->num_cust_pay_pending_attempt unless wantarray;
3938 sort { $a->_date <=> $b->_date }
3939 qsearch( 'cust_pay_pending', {
3940 'custnum' => $self->custnum,
3947 =item num_cust_pay_pending
3949 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3950 customer (without status "done"). Also called automatically when the
3951 cust_pay_pending method is used in a scalar context.
3955 sub num_cust_pay_pending {
3958 " SELECT COUNT(*) FROM cust_pay_pending ".
3959 " WHERE custnum = ? AND status != 'done' ",
3964 =item num_cust_pay_pending_attempt
3966 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3967 customer, with status "done" but without a corresp. Also called automatically when the
3968 cust_pay_pending method is used in a scalar context.
3972 sub num_cust_pay_pending_attempt {
3975 " SELECT COUNT(*) FROM cust_pay_pending ".
3976 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3983 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3989 map { $_ } #return $self->num_cust_refund unless wantarray;
3990 sort { $a->_date <=> $b->_date }
3991 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3994 =item display_custnum
3996 Returns the displayed customer number for this customer: agent_custid if
3997 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4001 sub display_custnum {
4003 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
4004 return $self->agent_custid;
4006 return $self->custnum;
4012 Returns a name string for this customer, either "Company (Last, First)" or
4019 my $name = $self->contact;
4020 $name = $self->company. " ($name)" if $self->company;
4026 Returns a name string for this (service/shipping) contact, either
4027 "Company (Last, First)" or "Last, First".
4033 if ( $self->get('ship_last') ) {
4034 my $name = $self->ship_contact;
4035 $name = $self->ship_company. " ($name)" if $self->ship_company;
4044 Returns a name string for this customer, either "Company" or "First Last".
4050 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4053 =item ship_name_short
4055 Returns a name string for this (service/shipping) contact, either "Company"
4060 sub ship_name_short {
4062 if ( $self->get('ship_last') ) {
4063 $self->ship_company !~ /^\s*$/
4064 ? $self->ship_company
4065 : $self->ship_contact_firstlast;
4067 $self->name_company_or_firstlast;
4073 Returns this customer's full (billing) contact name only, "Last, First"
4079 $self->get('last'). ', '. $self->first;
4084 Returns this customer's full (shipping) contact name only, "Last, First"
4090 $self->get('ship_last')
4091 ? $self->get('ship_last'). ', '. $self->ship_first
4095 =item contact_firstlast
4097 Returns this customers full (billing) contact name only, "First Last".
4101 sub contact_firstlast {
4103 $self->first. ' '. $self->get('last');
4106 =item ship_contact_firstlast
4108 Returns this customer's full (shipping) contact name only, "First Last".
4112 sub ship_contact_firstlast {
4114 $self->get('ship_last')
4115 ? $self->first. ' '. $self->get('ship_last')
4116 : $self->contact_firstlast;
4121 Returns this customer's full country name
4127 code2country($self->country);
4130 =item geocode DATA_VENDOR
4132 Returns a value for the customer location as encoded by DATA_VENDOR.
4133 Currently this only makes sense for "CCH" as DATA_VENDOR.
4138 my ($self, $data_vendor) = (shift, shift); #always cch for now
4140 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
4141 return $geocode if $geocode;
4143 my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
4147 my($zip,$plus4) = split /-/, $self->get("${prefix}zip")
4148 if $self->country eq 'US';
4152 #CCH specific location stuff
4153 my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
4155 my @cust_tax_location =
4157 'table' => 'cust_tax_location',
4158 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
4159 'extra_sql' => $extra_sql,
4160 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
4163 $geocode = $cust_tax_location[0]->geocode
4164 if scalar(@cust_tax_location);
4173 Returns a status string for this customer, currently:
4177 =item prospect - No packages have ever been ordered
4179 =item ordered - Recurring packages all are new (not yet billed).
4181 =item active - One or more recurring packages is active
4183 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4185 =item suspended - All non-cancelled recurring packages are suspended
4187 =item cancelled - All recurring packages are cancelled
4193 sub status { shift->cust_status(@_); }
4197 # prospect ordered active inactive suspended cancelled
4198 for my $status ( FS::cust_main->statuses() ) {
4199 my $method = $status.'_sql';
4200 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4201 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4202 $sth->execute( ($self->custnum) x $numnum )
4203 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4204 return $status if $sth->fetchrow_arrayref->[0];
4208 =item ucfirst_cust_status
4210 =item ucfirst_status
4212 Returns the status with the first character capitalized.
4216 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4218 sub ucfirst_cust_status {
4220 ucfirst($self->cust_status);
4225 Returns a hex triplet color string for this customer's status.
4229 use vars qw(%statuscolor);
4230 tie %statuscolor, 'Tie::IxHash',
4231 'prospect' => '7e0079', #'000000', #black? naw, purple
4232 'active' => '00CC00', #green
4233 'ordered' => '009999', #teal? cyan?
4234 'inactive' => '0000CC', #blue
4235 'suspended' => 'FF9900', #yellow
4236 'cancelled' => 'FF0000', #red
4239 sub statuscolor { shift->cust_statuscolor(@_); }
4241 sub cust_statuscolor {
4243 $statuscolor{$self->cust_status};
4248 Returns an array of hashes representing the customer's RT tickets.
4255 my $num = $conf->config('cust_main-max_tickets') || 10;
4258 if ( $conf->config('ticket_system') ) {
4259 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4261 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4265 foreach my $priority (
4266 $conf->config('ticket_system-custom_priority_field-values'), ''
4268 last if scalar(@tickets) >= $num;
4270 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4271 $num - scalar(@tickets),
4281 # Return services representing svc_accts in customer support packages
4282 sub support_services {
4284 my %packages = map { $_ => 1 } $conf->config('support_packages');
4286 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4287 grep { $_->part_svc->svcdb eq 'svc_acct' }
4288 map { $_->cust_svc }
4289 grep { exists $packages{ $_->pkgpart } }
4290 $self->ncancelled_pkgs;
4294 # Return a list of latitude/longitude for one of the services (if any)
4295 sub service_coordinates {
4299 grep { $_->latitude && $_->longitude }
4301 map { $_->cust_svc }
4302 $self->ncancelled_pkgs;
4304 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4309 Returns a masked version of the named field
4314 my ($self,$field) = @_;
4318 'x'x(length($self->getfield($field))-4).
4319 substr($self->getfield($field), (length($self->getfield($field))-4));
4325 =head1 CLASS METHODS
4331 Class method that returns the list of possible status strings for customers
4332 (see L<the status method|/status>). For example:
4334 @statuses = FS::cust_main->statuses();
4339 #my $self = shift; #could be class...
4345 Returns an SQL expression identifying prospective cust_main records (customers
4346 with no packages ever ordered)
4350 use vars qw($select_count_pkgs);
4351 $select_count_pkgs =
4352 "SELECT COUNT(*) FROM cust_pkg
4353 WHERE cust_pkg.custnum = cust_main.custnum";
4355 sub select_count_pkgs_sql {
4360 " 0 = ( $select_count_pkgs ) ";
4365 Returns an SQL expression identifying ordered cust_main records (customers with
4366 recurring packages not yet setup).
4371 FS::cust_main->none_active_sql.
4372 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->ordered_sql. " ) ";
4377 Returns an SQL expression identifying active cust_main records (customers with
4378 active recurring packages).
4383 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4386 =item none_active_sql
4388 Returns an SQL expression identifying cust_main records with no active
4389 recurring packages. This includes customers of status prospect, ordered,
4390 inactive, and suspended.
4394 sub none_active_sql {
4395 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4400 Returns an SQL expression identifying inactive cust_main records (customers with
4401 no active recurring packages, but otherwise unsuspended/uncancelled).
4406 FS::cust_main->none_active_sql.
4407 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4413 Returns an SQL expression identifying suspended cust_main records.
4418 sub suspended_sql { susp_sql(@_); }
4420 FS::cust_main->none_active_sql.
4421 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4427 Returns an SQL expression identifying cancelled cust_main records.
4431 sub cancelled_sql { cancel_sql(@_); }
4434 my $recurring_sql = FS::cust_pkg->recurring_sql;
4435 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
4438 0 < ( $select_count_pkgs )
4439 AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql )
4440 AND 0 = ( $select_count_pkgs AND $recurring_sql
4441 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4443 AND 0 = ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4449 =item uncancelled_sql
4451 Returns an SQL expression identifying un-cancelled cust_main records.
4455 sub uncancelled_sql { uncancel_sql(@_); }
4456 sub uncancel_sql { "
4457 ( 0 < ( $select_count_pkgs
4458 AND ( cust_pkg.cancel IS NULL
4459 OR cust_pkg.cancel = 0
4462 OR 0 = ( $select_count_pkgs )
4468 Returns an SQL fragment to retreive the balance.
4473 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4474 WHERE cust_bill.custnum = cust_main.custnum )
4475 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4476 WHERE cust_pay.custnum = cust_main.custnum )
4477 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4478 WHERE cust_credit.custnum = cust_main.custnum )
4479 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4480 WHERE cust_refund.custnum = cust_main.custnum )
4483 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4485 Returns an SQL fragment to retreive the balance for this customer, optionally
4486 considering invoices with date earlier than START_TIME, and not
4487 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4488 total_unapplied_payments).
4490 Times are specified as SQL fragments or numeric
4491 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4492 L<Date::Parse> for conversion functions. The empty string can be passed
4493 to disable that time constraint completely.
4495 Available options are:
4499 =item unapplied_date
4501 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)
4506 set to true to remove all customer comparison clauses, for totals
4511 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4516 JOIN clause (typically used with the total option)
4520 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4521 time will be ignored. Note that START_TIME and END_TIME only limit the date
4522 range for invoices and I<unapplied> payments, credits, and refunds.
4528 sub balance_date_sql {
4529 my( $class, $start, $end, %opt ) = @_;
4531 my $cutoff = $opt{'cutoff'};
4533 my $owed = FS::cust_bill->owed_sql($cutoff);
4534 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4535 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4536 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4538 my $j = $opt{'join'} || '';
4540 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4541 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4542 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4543 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4545 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4546 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4547 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4548 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4553 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4555 Returns an SQL fragment to retreive the total unapplied payments for this
4556 customer, only considering invoices with date earlier than START_TIME, and
4557 optionally not later than END_TIME.
4559 Times are specified as SQL fragments or numeric
4560 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4561 L<Date::Parse> for conversion functions. The empty string can be passed
4562 to disable that time constraint completely.
4564 Available options are:
4568 sub unapplied_payments_date_sql {
4569 my( $class, $start, $end, %opt ) = @_;
4571 my $cutoff = $opt{'cutoff'};
4573 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4575 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4576 'unapplied_date'=>1 );
4578 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4581 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4583 Helper method for balance_date_sql; name (and usage) subject to change
4584 (suggestions welcome).
4586 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4587 cust_refund, cust_credit or cust_pay).
4589 If TABLE is "cust_bill" or the unapplied_date option is true, only
4590 considers records with date earlier than START_TIME, and optionally not
4591 later than END_TIME .
4595 sub _money_table_where {
4596 my( $class, $table, $start, $end, %opt ) = @_;
4599 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4600 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4601 push @where, "$table._date <= $start" if defined($start) && length($start);
4602 push @where, "$table._date > $end" if defined($end) && length($end);
4604 push @where, @{$opt{'where'}} if $opt{'where'};
4605 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4611 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4612 use FS::cust_main::Search;
4615 FS::cust_main::Search->search(@_);
4624 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4628 use FS::cust_main::Search;
4629 sub append_fuzzyfiles {
4630 #my( $first, $last, $company ) = @_;
4632 FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4634 use Fcntl qw(:flock);
4636 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4638 foreach my $field (@fuzzyfields) {
4643 open(CACHE,">>$dir/cust_main.$field")
4644 or die "can't open $dir/cust_main.$field: $!";
4645 flock(CACHE,LOCK_EX)
4646 or die "can't lock $dir/cust_main.$field: $!";
4648 print CACHE "$value\n";
4650 flock(CACHE,LOCK_UN)
4651 or die "can't unlock $dir/cust_main.$field: $!";
4666 #warn join('-',keys %$param);
4667 my $fh = $param->{filehandle};
4668 my $agentnum = $param->{agentnum};
4669 my $format = $param->{format};
4671 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4674 if ( $format eq 'simple' ) {
4675 @fields = qw( custnum agent_custid amount pkg );
4677 die "unknown format $format";
4680 eval "use Text::CSV_XS;";
4683 my $csv = new Text::CSV_XS;
4690 local $SIG{HUP} = 'IGNORE';
4691 local $SIG{INT} = 'IGNORE';
4692 local $SIG{QUIT} = 'IGNORE';
4693 local $SIG{TERM} = 'IGNORE';
4694 local $SIG{TSTP} = 'IGNORE';
4695 local $SIG{PIPE} = 'IGNORE';
4697 my $oldAutoCommit = $FS::UID::AutoCommit;
4698 local $FS::UID::AutoCommit = 0;
4701 #while ( $columns = $csv->getline($fh) ) {
4703 while ( defined($line=<$fh>) ) {
4705 $csv->parse($line) or do {
4706 $dbh->rollback if $oldAutoCommit;
4707 return "can't parse: ". $csv->error_input();
4710 my @columns = $csv->fields();
4711 #warn join('-',@columns);
4714 foreach my $field ( @fields ) {
4715 $row{$field} = shift @columns;
4718 if ( $row{custnum} && $row{agent_custid} ) {
4719 dbh->rollback if $oldAutoCommit;
4720 return "can't specify custnum with agent_custid $row{agent_custid}";
4724 if ( $row{agent_custid} && $agentnum ) {
4725 %hash = ( 'agent_custid' => $row{agent_custid},
4726 'agentnum' => $agentnum,
4730 if ( $row{custnum} ) {
4731 %hash = ( 'custnum' => $row{custnum} );
4734 unless ( scalar(keys %hash) ) {
4735 $dbh->rollback if $oldAutoCommit;
4736 return "can't find customer without custnum or agent_custid and agentnum";
4739 my $cust_main = qsearchs('cust_main', { %hash } );
4740 unless ( $cust_main ) {
4741 $dbh->rollback if $oldAutoCommit;
4742 my $custnum = $row{custnum} || $row{agent_custid};
4743 return "unknown custnum $custnum";
4746 if ( $row{'amount'} > 0 ) {
4747 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4749 $dbh->rollback if $oldAutoCommit;
4753 } elsif ( $row{'amount'} < 0 ) {
4754 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4757 $dbh->rollback if $oldAutoCommit;
4767 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4769 return "Empty file!" unless $imported;
4775 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4777 Deprecated. Use event notification and message templates
4778 (L<FS::msg_template>) instead.
4780 Sends a templated email notification to the customer (see L<Text::Template>).
4782 OPTIONS is a hash and may include
4784 I<from> - the email sender (default is invoice_from)
4786 I<to> - comma-separated scalar or arrayref of recipients
4787 (default is invoicing_list)
4789 I<subject> - The subject line of the sent email notification
4790 (default is "Notice from company_name")
4792 I<extra_fields> - a hashref of name/value pairs which will be substituted
4795 The following variables are vavailable in the template.
4797 I<$first> - the customer first name
4798 I<$last> - the customer last name
4799 I<$company> - the customer company
4800 I<$payby> - a description of the method of payment for the customer
4801 # would be nice to use FS::payby::shortname
4802 I<$payinfo> - the account information used to collect for this customer
4803 I<$expdate> - the expiration of the customer payment in seconds from epoch
4808 my ($self, $template, %options) = @_;
4810 return unless $conf->exists($template);
4812 my $from = $conf->config('invoice_from', $self->agentnum)
4813 if $conf->exists('invoice_from', $self->agentnum);
4814 $from = $options{from} if exists($options{from});
4816 my $to = join(',', $self->invoicing_list_emailonly);
4817 $to = $options{to} if exists($options{to});
4819 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4820 if $conf->exists('company_name', $self->agentnum);
4821 $subject = $options{subject} if exists($options{subject});
4823 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4824 SOURCE => [ map "$_\n",
4825 $conf->config($template)]
4827 or die "can't create new Text::Template object: Text::Template::ERROR";
4828 $notify_template->compile()
4829 or die "can't compile template: Text::Template::ERROR";
4831 $FS::notify_template::_template::company_name =
4832 $conf->config('company_name', $self->agentnum);
4833 $FS::notify_template::_template::company_address =
4834 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4836 my $paydate = $self->paydate || '2037-12-31';
4837 $FS::notify_template::_template::first = $self->first;
4838 $FS::notify_template::_template::last = $self->last;
4839 $FS::notify_template::_template::company = $self->company;
4840 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4841 my $payby = $self->payby;
4842 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4843 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4845 #credit cards expire at the end of the month/year of their exp date
4846 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4847 $FS::notify_template::_template::payby = 'credit card';
4848 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4849 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4851 }elsif ($payby eq 'COMP') {
4852 $FS::notify_template::_template::payby = 'complimentary account';
4854 $FS::notify_template::_template::payby = 'current method';
4856 $FS::notify_template::_template::expdate = $expire_time;
4858 for (keys %{$options{extra_fields}}){
4860 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4863 send_email(from => $from,
4865 subject => $subject,
4866 body => $notify_template->fill_in( PACKAGE =>
4867 'FS::notify_template::_template' ),
4872 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4874 Generates a templated notification to the customer (see L<Text::Template>).
4876 OPTIONS is a hash and may include
4878 I<extra_fields> - a hashref of name/value pairs which will be substituted
4879 into the template. These values may override values mentioned below
4880 and those from the customer record.
4882 The following variables are available in the template instead of or in addition
4883 to the fields of the customer record.
4885 I<$payby> - a description of the method of payment for the customer
4886 # would be nice to use FS::payby::shortname
4887 I<$payinfo> - the masked account information used to collect for this customer
4888 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4889 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4893 # a lot like cust_bill::print_latex
4894 sub generate_letter {
4895 my ($self, $template, %options) = @_;
4897 return unless $conf->exists($template);
4899 my $letter_template = new Text::Template
4901 SOURCE => [ map "$_\n", $conf->config($template)],
4902 DELIMITERS => [ '[@--', '--@]' ],
4904 or die "can't create new Text::Template object: Text::Template::ERROR";
4906 $letter_template->compile()
4907 or die "can't compile template: Text::Template::ERROR";
4909 my %letter_data = map { $_ => $self->$_ } $self->fields;
4910 $letter_data{payinfo} = $self->mask_payinfo;
4912 #my $paydate = $self->paydate || '2037-12-31';
4913 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4915 my $payby = $self->payby;
4916 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4917 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4919 #credit cards expire at the end of the month/year of their exp date
4920 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4921 $letter_data{payby} = 'credit card';
4922 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4923 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4925 }elsif ($payby eq 'COMP') {
4926 $letter_data{payby} = 'complimentary account';
4928 $letter_data{payby} = 'current method';
4930 $letter_data{expdate} = $expire_time;
4932 for (keys %{$options{extra_fields}}){
4933 $letter_data{$_} = $options{extra_fields}->{$_};
4936 unless(exists($letter_data{returnaddress})){
4937 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4938 $self->agent_template)
4940 if ( length($retadd) ) {
4941 $letter_data{returnaddress} = $retadd;
4942 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4943 $letter_data{returnaddress} =
4944 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4948 ( $conf->config('company_name', $self->agentnum),
4949 $conf->config('company_address', $self->agentnum),
4953 $letter_data{returnaddress} = '~';
4957 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4959 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4961 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4963 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4967 ) or die "can't open temp file: $!\n";
4968 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4969 or die "can't write temp file: $!\n";
4971 $letter_data{'logo_file'} = $lh->filename;
4973 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4977 ) or die "can't open temp file: $!\n";
4979 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4981 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4982 return ($1, $letter_data{'logo_file'});
4986 =item print_ps TEMPLATE
4988 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4994 my($file, $lfile) = $self->generate_letter(@_);
4995 my $ps = FS::Misc::generate_ps($file);
4996 unlink($file.'.tex');
5002 =item print TEMPLATE
5004 Prints the filled in template.
5006 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5010 sub queueable_print {
5013 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5014 or die "invalid customer number: " . $opt{custvnum};
5016 my $error = $self->print( $opt{template} );
5017 die $error if $error;
5021 my ($self, $template) = (shift, shift);
5022 do_print [ $self->print_ps($template) ];
5025 #these three subs should just go away once agent stuff is all config overrides
5027 sub agent_template {
5029 $self->_agent_plandata('agent_templatename');
5032 sub agent_invoice_from {
5034 $self->_agent_plandata('agent_invoice_from');
5037 sub _agent_plandata {
5038 my( $self, $option ) = @_;
5040 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5041 #agent-specific Conf
5043 use FS::part_event::Condition;
5045 my $agentnum = $self->agentnum;
5047 my $regexp = regexp_sql();
5049 my $part_event_option =
5051 'select' => 'part_event_option.*',
5052 'table' => 'part_event_option',
5054 LEFT JOIN part_event USING ( eventpart )
5055 LEFT JOIN part_event_option AS peo_agentnum
5056 ON ( part_event.eventpart = peo_agentnum.eventpart
5057 AND peo_agentnum.optionname = 'agentnum'
5058 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5060 LEFT JOIN part_event_condition
5061 ON ( part_event.eventpart = part_event_condition.eventpart
5062 AND part_event_condition.conditionname = 'cust_bill_age'
5064 LEFT JOIN part_event_condition_option
5065 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5066 AND part_event_condition_option.optionname = 'age'
5069 #'hashref' => { 'optionname' => $option },
5070 #'hashref' => { 'part_event_option.optionname' => $option },
5072 " WHERE part_event_option.optionname = ". dbh->quote($option).
5073 " AND action = 'cust_bill_send_agent' ".
5074 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5075 " AND peo_agentnum.optionname = 'agentnum' ".
5076 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5078 CASE WHEN part_event_condition_option.optionname IS NULL
5080 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5082 , part_event.weight".
5086 unless ( $part_event_option ) {
5087 return $self->agent->invoice_template || ''
5088 if $option eq 'agent_templatename';
5092 $part_event_option->optionvalue;
5096 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5098 Subroutine (not a method), designed to be called from the queue.
5100 Takes a list of options and values.
5102 Pulls up the customer record via the custnum option and calls bill_and_collect.
5107 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5109 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5110 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5112 $cust_main->bill_and_collect( %args );
5115 sub process_bill_and_collect {
5117 my $param = thaw(decode_base64(shift));
5118 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5119 or die "custnum '$param->{custnum}' not found!\n";
5120 $param->{'job'} = $job;
5121 $param->{'fatal'} = 1; # runs from job queue, will be caught
5122 $param->{'retry'} = 1;
5124 $cust_main->bill_and_collect( %$param );
5127 sub _upgrade_data { #class method
5128 my ($class, %opts) = @_;
5130 my $sql = 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL';
5131 my $sth = dbh->prepare($sql) or die dbh->errstr;
5132 $sth->execute or die $sth->errstr;
5134 local($ignore_expired_card) = 1;
5135 local($ignore_illegal_zip) = 1;
5136 local($ignore_banned_card) = 1;
5137 local($skip_fuzzyfiles) = 1;
5138 $class->_upgrade_otaker(%opts);
5148 The delete method should possibly take an FS::cust_main object reference
5149 instead of a scalar customer number.
5151 Bill and collect options should probably be passed as references instead of a
5154 There should probably be a configuration file with a list of allowed credit
5157 No multiple currency support (probably a larger project than just this module).
5159 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5161 Birthdates rely on negative epoch values.
5163 The payby for card/check batches is broken. With mixed batching, bad
5166 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5170 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5171 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5172 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.