5 #FS::cust_main:_Marketgear when they're ready to move to 2.1
6 use base qw( FS::cust_main::Packages FS::cust_main::Status
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 use vars qw( $DEBUG $me $conf
16 $ignore_expired_card $ignore_illegal_zip $ignore_banned_card
21 use Scalar::Util qw( blessed );
22 use Time::Local qw(timelocal);
23 use Storable qw(thaw);
27 use Digest::MD5 qw(md5_base64);
30 use File::Temp; #qw( tempfile );
31 use Business::CreditCard 0.28;
33 use FS::UID qw( getotaker dbh driver_name );
34 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
35 use FS::Misc qw( generate_email send_email generate_ps do_print );
36 use FS::Msgcat qw(gettext);
43 use FS::legacy_cust_bill;
45 use FS::cust_pay_pending;
46 use FS::cust_pay_void;
47 use FS::cust_pay_batch;
50 use FS::part_referral;
51 use FS::cust_main_county;
52 use FS::cust_location;
54 use FS::cust_main_exemption;
55 use FS::cust_tax_adjustment;
56 use FS::cust_tax_location;
58 use FS::cust_main_invoice;
60 use FS::prepay_credit;
66 use FS::payment_gateway;
67 use FS::agent_payment_gateway;
69 use FS::cust_main_note;
70 use FS::cust_attachment;
73 use FS::upgrade_journal;
75 # 1 is mostly method/subroutine entry and options
76 # 2 traces progress of some operations
77 # 3 is even more information including possibly sensitive data
79 $me = '[FS::cust_main]';
82 $ignore_expired_card = 0;
83 $ignore_illegal_zip = 0;
84 $ignore_banned_card = 0;
88 @encrypted_fields = ('payinfo', 'paycvv');
89 sub nohistory_fields { ('payinfo', 'paycvv'); }
91 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
93 #ask FS::UID to run this stuff for us later
94 #$FS::UID::callback{'FS::cust_main'} = sub {
95 install_callback FS::UID sub {
97 #yes, need it for stuff below (prolly should be cached)
102 my ( $hashref, $cache ) = @_;
103 if ( exists $hashref->{'pkgnum'} ) {
104 #@{ $self->{'_pkgnum'} } = ();
105 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
106 $self->{'_pkgnum'} = $subcache;
107 #push @{ $self->{'_pkgnum'} },
108 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
114 FS::cust_main - Object methods for cust_main records
120 $record = new FS::cust_main \%hash;
121 $record = new FS::cust_main { 'column' => 'value' };
123 $error = $record->insert;
125 $error = $new_record->replace($old_record);
127 $error = $record->delete;
129 $error = $record->check;
131 @cust_pkg = $record->all_pkgs;
133 @cust_pkg = $record->ncancelled_pkgs;
135 @cust_pkg = $record->suspended_pkgs;
137 $error = $record->bill;
138 $error = $record->bill %options;
139 $error = $record->bill 'time' => $time;
141 $error = $record->collect;
142 $error = $record->collect %options;
143 $error = $record->collect 'invoice_time' => $time,
148 An FS::cust_main object represents a customer. FS::cust_main inherits from
149 FS::Record. The following fields are currently supported:
155 Primary key (assigned automatically for new customers)
159 Agent (see L<FS::agent>)
163 Advertising source (see L<FS::part_referral>)
175 Cocial security number (optional)
191 (optional, see L<FS::cust_main_county>)
195 (see L<FS::cust_main_county>)
201 (see L<FS::cust_main_county>)
241 (optional, see L<FS::cust_main_county>)
245 (see L<FS::cust_main_county>)
251 (see L<FS::cust_main_county>)
271 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
275 Payment Information (See L<FS::payinfo_Mixin> for data format)
279 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
283 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
287 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
291 Start date month (maestro/solo cards only)
295 Start date year (maestro/solo cards only)
299 Issue number (maestro/solo cards only)
303 Name on card or billing name
307 IP address from which payment information was received
311 Tax exempt, empty or `Y'
315 Order taker (see L<FS::access_user>)
321 =item referral_custnum
323 Referring customer number
327 Enable individual CDR spooling, empty or `Y'
331 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
335 Discourage individual CDR printing, empty or `Y'
339 Allow self-service editing of ticket subjects, empty or 'Y'
341 =item calling_list_exempt
343 Do not call, empty or 'Y'
353 Creates a new customer. To add the customer to the database, see L<"insert">.
355 Note that this stores the hash reference, not a distinct copy of the hash it
356 points to. You can ask the object for a copy with the I<hash> method.
360 sub table { 'cust_main'; }
362 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
364 Adds this customer to the database. If there is an error, returns the error,
365 otherwise returns false.
367 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
368 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
369 are inserted atomicly, or the transaction is rolled back. Passing an empty
370 hash reference is equivalent to not supplying this parameter. There should be
371 a better explanation of this, but until then, here's an example:
374 tie %hash, 'Tie::RefHash'; #this part is important
376 $cust_pkg => [ $svc_acct ],
379 $cust_main->insert( \%hash );
381 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
382 be set as the invoicing list (see L<"invoicing_list">). Errors return as
383 expected and rollback the entire transaction; it is not necessary to call
384 check_invoicing_list first. The invoicing_list is set after the records in the
385 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
386 invoicing_list destination to the newly-created svc_acct. Here's an example:
388 $cust_main->insert( {}, [ $email, 'POST' ] );
390 Currently available options are: I<depend_jobnum>, I<noexport>,
391 I<tax_exemption> and I<prospectnum>.
393 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
394 on the supplied jobnum (they will not run until the specific job completes).
395 This can be used to defer provisioning until some action completes (such
396 as running the customer's credit card successfully).
398 The I<noexport> option is deprecated. If I<noexport> is set true, no
399 provisioning jobs (exports) are scheduled. (You can schedule them later with
400 the B<reexport> method.)
402 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
403 of tax names and exemption numbers. FS::cust_main_exemption records will be
404 created and inserted.
406 If I<prospectnum> is set, moves contacts and locations from that prospect.
412 my $cust_pkgs = @_ ? shift : {};
413 my $invoicing_list = @_ ? shift : '';
415 warn "$me insert called with options ".
416 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
419 local $SIG{HUP} = 'IGNORE';
420 local $SIG{INT} = 'IGNORE';
421 local $SIG{QUIT} = 'IGNORE';
422 local $SIG{TERM} = 'IGNORE';
423 local $SIG{TSTP} = 'IGNORE';
424 local $SIG{PIPE} = 'IGNORE';
426 my $oldAutoCommit = $FS::UID::AutoCommit;
427 local $FS::UID::AutoCommit = 0;
430 my $prepay_identifier = '';
431 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
433 if ( $self->payby eq 'PREPAY' ) {
435 $self->payby('BILL');
436 $prepay_identifier = $self->payinfo;
439 warn " looking up prepaid card $prepay_identifier\n"
442 my $error = $self->get_prepay( $prepay_identifier,
443 'amount_ref' => \$amount,
444 'seconds_ref' => \$seconds,
445 'upbytes_ref' => \$upbytes,
446 'downbytes_ref' => \$downbytes,
447 'totalbytes_ref' => \$totalbytes,
450 $dbh->rollback if $oldAutoCommit;
451 #return "error applying prepaid card (transaction rolled back): $error";
455 $payby = 'PREP' if $amount;
457 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
460 $self->payby('BILL');
461 $amount = $self->paid;
465 warn " inserting $self\n"
468 $self->signupdate(time) unless $self->signupdate;
470 $self->censusyear($conf->config('census_year')||'2012') if $self->censustract;
472 $self->auto_agent_custid()
473 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
475 my $error = $self->SUPER::insert;
477 $dbh->rollback if $oldAutoCommit;
478 #return "inserting cust_main record (transaction rolled back): $error";
482 warn " setting invoicing list\n"
485 if ( $invoicing_list ) {
486 $error = $self->check_invoicing_list( $invoicing_list );
488 $dbh->rollback if $oldAutoCommit;
489 #return "checking invoicing_list (transaction rolled back): $error";
492 $self->invoicing_list( $invoicing_list );
495 warn " setting customer tags\n"
498 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
499 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
500 'custnum' => $self->custnum };
501 my $error = $cust_tag->insert;
503 $dbh->rollback if $oldAutoCommit;
508 my $prospectnum = delete $options{'prospectnum'};
509 if ( $prospectnum ) {
511 warn " moving contacts and locations from prospect $prospectnum\n"
515 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
516 unless ( $prospect_main ) {
517 $dbh->rollback if $oldAutoCommit;
518 return "Unknown prospectnum $prospectnum";
520 $prospect_main->custnum($self->custnum);
521 $prospect_main->disabled('Y');
522 my $error = $prospect_main->replace;
524 $dbh->rollback if $oldAutoCommit;
528 my @contact = $prospect_main->contact;
529 my @cust_location = $prospect_main->cust_location;
530 my @qual = $prospect_main->qual;
532 foreach my $r ( @contact, @cust_location, @qual ) {
534 $r->custnum($self->custnum);
535 my $error = $r->replace;
537 $dbh->rollback if $oldAutoCommit;
544 warn " setting cust_main_exemption\n"
547 my $tax_exemption = delete $options{'tax_exemption'};
548 if ( $tax_exemption ) {
550 $tax_exemption = { map { $_ => '' } @$tax_exemption }
551 if ref($tax_exemption) eq 'ARRAY';
553 foreach my $taxname ( keys %$tax_exemption ) {
554 my $cust_main_exemption = new FS::cust_main_exemption {
555 'custnum' => $self->custnum,
556 'taxname' => $taxname,
557 'exempt_number' => $tax_exemption->{$taxname},
559 my $error = $cust_main_exemption->insert;
561 $dbh->rollback if $oldAutoCommit;
562 return "inserting cust_main_exemption (transaction rolled back): $error";
567 if ( $self->can('start_copy_skel') ) {
568 my $error = $self->start_copy_skel;
570 $dbh->rollback if $oldAutoCommit;
575 warn " ordering packages\n"
578 $error = $self->order_pkgs( $cust_pkgs,
580 'seconds_ref' => \$seconds,
581 'upbytes_ref' => \$upbytes,
582 'downbytes_ref' => \$downbytes,
583 'totalbytes_ref' => \$totalbytes,
586 $dbh->rollback if $oldAutoCommit;
591 $dbh->rollback if $oldAutoCommit;
592 return "No svc_acct record to apply pre-paid time";
594 if ( $upbytes || $downbytes || $totalbytes ) {
595 $dbh->rollback if $oldAutoCommit;
596 return "No svc_acct record to apply pre-paid data";
600 warn " inserting initial $payby payment of $amount\n"
602 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
604 $dbh->rollback if $oldAutoCommit;
605 return "inserting payment (transaction rolled back): $error";
609 unless ( $import || $skip_fuzzyfiles ) {
610 warn " queueing fuzzyfiles update\n"
612 $error = $self->queue_fuzzyfiles_update;
614 $dbh->rollback if $oldAutoCommit;
615 return "updating fuzzy search cache: $error";
619 # FS::geocode_Mixin::after_insert or something?
620 if ( $conf->config('tax_district_method') and !$import ) {
621 # if anything non-empty, try to look it up
622 my $queue = new FS::queue {
623 'job' => 'FS::geocode_Mixin::process_district_update',
624 'custnum' => $self->custnum,
626 my $error = $queue->insert( ref($self), $self->custnum );
628 $dbh->rollback if $oldAutoCommit;
629 return "queueing tax district update: $error";
634 warn " exporting\n" if $DEBUG > 1;
636 my $export_args = $options{'export_args'} || [];
639 map qsearch( 'part_export', {exportnum=>$_} ),
640 $conf->config('cust_main-exports'); #, $agentnum
642 foreach my $part_export ( @part_export ) {
643 my $error = $part_export->export_insert($self, @$export_args);
645 $dbh->rollback if $oldAutoCommit;
646 return "exporting to ". $part_export->exporttype.
647 " (transaction rolled back): $error";
651 #foreach my $depend_jobnum ( @$depend_jobnums ) {
652 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
654 # foreach my $jobnum ( @jobnums ) {
655 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
656 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
658 # my $error = $queue->depend_insert($depend_jobnum);
660 # $dbh->rollback if $oldAutoCommit;
661 # return "error queuing job dependancy: $error";
668 #if ( exists $options{'jobnums'} ) {
669 # push @{ $options{'jobnums'} }, @jobnums;
672 warn " insert complete; committing transaction\n"
675 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
680 use File::CounterFile;
681 sub auto_agent_custid {
684 my $format = $conf->config('cust_main-auto_agent_custid');
686 if ( $format eq '1YMMXXXXXXXX' ) {
688 my $counter = new File::CounterFile 'cust_main.agent_custid';
691 my $ym = 100000000000 + time2str('%y%m00000000', time);
692 if ( $ym > $counter->value ) {
693 $counter->{'value'} = $agent_custid = $ym;
694 $counter->{'updated'} = 1;
696 $agent_custid = $counter->inc;
702 die "Unknown cust_main-auto_agent_custid format: $format";
705 $self->agent_custid($agent_custid);
709 =item PACKAGE METHODS
711 Documentation on customer package methods has been moved to
712 L<FS::cust_main::Packages>.
714 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
716 Recharges this (existing) customer with the specified prepaid card (see
717 L<FS::prepay_credit>), specified either by I<identifier> or as an
718 FS::prepay_credit object. If there is an error, returns the error, otherwise
721 Optionally, five scalar references can be passed as well. They will have their
722 values filled in with the amount, number of seconds, and number of upload,
723 download, and total bytes applied by this prepaid card.
727 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
728 #the only place that uses these args
729 sub recharge_prepay {
730 my( $self, $prepay_credit, $amountref, $secondsref,
731 $upbytesref, $downbytesref, $totalbytesref ) = @_;
733 local $SIG{HUP} = 'IGNORE';
734 local $SIG{INT} = 'IGNORE';
735 local $SIG{QUIT} = 'IGNORE';
736 local $SIG{TERM} = 'IGNORE';
737 local $SIG{TSTP} = 'IGNORE';
738 local $SIG{PIPE} = 'IGNORE';
740 my $oldAutoCommit = $FS::UID::AutoCommit;
741 local $FS::UID::AutoCommit = 0;
744 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
746 my $error = $self->get_prepay( $prepay_credit,
747 'amount_ref' => \$amount,
748 'seconds_ref' => \$seconds,
749 'upbytes_ref' => \$upbytes,
750 'downbytes_ref' => \$downbytes,
751 'totalbytes_ref' => \$totalbytes,
753 || $self->increment_seconds($seconds)
754 || $self->increment_upbytes($upbytes)
755 || $self->increment_downbytes($downbytes)
756 || $self->increment_totalbytes($totalbytes)
757 || $self->insert_cust_pay_prepay( $amount,
759 ? $prepay_credit->identifier
764 $dbh->rollback if $oldAutoCommit;
768 if ( defined($amountref) ) { $$amountref = $amount; }
769 if ( defined($secondsref) ) { $$secondsref = $seconds; }
770 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
771 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
772 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
774 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
779 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
781 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
782 specified either by I<identifier> or as an FS::prepay_credit object.
784 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
785 incremented by the values of the prepaid card.
787 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
788 check or set this customer's I<agentnum>.
790 If there is an error, returns the error, otherwise returns false.
796 my( $self, $prepay_credit, %opt ) = @_;
798 local $SIG{HUP} = 'IGNORE';
799 local $SIG{INT} = 'IGNORE';
800 local $SIG{QUIT} = 'IGNORE';
801 local $SIG{TERM} = 'IGNORE';
802 local $SIG{TSTP} = 'IGNORE';
803 local $SIG{PIPE} = 'IGNORE';
805 my $oldAutoCommit = $FS::UID::AutoCommit;
806 local $FS::UID::AutoCommit = 0;
809 unless ( ref($prepay_credit) ) {
811 my $identifier = $prepay_credit;
813 $prepay_credit = qsearchs(
815 { 'identifier' => $identifier },
820 unless ( $prepay_credit ) {
821 $dbh->rollback if $oldAutoCommit;
822 return "Invalid prepaid card: ". $identifier;
827 if ( $prepay_credit->agentnum ) {
828 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
829 $dbh->rollback if $oldAutoCommit;
830 return "prepaid card not valid for agent ". $self->agentnum;
832 $self->agentnum($prepay_credit->agentnum);
835 my $error = $prepay_credit->delete;
837 $dbh->rollback if $oldAutoCommit;
838 return "removing prepay_credit (transaction rolled back): $error";
841 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
842 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
844 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
849 =item increment_upbytes SECONDS
851 Updates this customer's single or primary account (see L<FS::svc_acct>) by
852 the specified number of upbytes. If there is an error, returns the error,
853 otherwise returns false.
857 sub increment_upbytes {
858 _increment_column( shift, 'upbytes', @_);
861 =item increment_downbytes SECONDS
863 Updates this customer's single or primary account (see L<FS::svc_acct>) by
864 the specified number of downbytes. If there is an error, returns the error,
865 otherwise returns false.
869 sub increment_downbytes {
870 _increment_column( shift, 'downbytes', @_);
873 =item increment_totalbytes SECONDS
875 Updates this customer's single or primary account (see L<FS::svc_acct>) by
876 the specified number of totalbytes. If there is an error, returns the error,
877 otherwise returns false.
881 sub increment_totalbytes {
882 _increment_column( shift, 'totalbytes', @_);
885 =item increment_seconds SECONDS
887 Updates this customer's single or primary account (see L<FS::svc_acct>) by
888 the specified number of seconds. If there is an error, returns the error,
889 otherwise returns false.
893 sub increment_seconds {
894 _increment_column( shift, 'seconds', @_);
897 =item _increment_column AMOUNT
899 Updates this customer's single or primary account (see L<FS::svc_acct>) by
900 the specified number of seconds or bytes. If there is an error, returns
901 the error, otherwise returns false.
905 sub _increment_column {
906 my( $self, $column, $amount ) = @_;
907 warn "$me increment_column called: $column, $amount\n"
910 return '' unless $amount;
912 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
913 $self->ncancelled_pkgs;
916 return 'No packages with primary or single services found'.
917 ' to apply pre-paid time';
918 } elsif ( scalar(@cust_pkg) > 1 ) {
919 #maybe have a way to specify the package/account?
920 return 'Multiple packages found to apply pre-paid time';
923 my $cust_pkg = $cust_pkg[0];
924 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
928 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
931 return 'No account found to apply pre-paid time';
932 } elsif ( scalar(@cust_svc) > 1 ) {
933 return 'Multiple accounts found to apply pre-paid time';
936 my $svc_acct = $cust_svc[0]->svc_x;
937 warn " found service svcnum ". $svc_acct->pkgnum.
938 ' ('. $svc_acct->email. ")\n"
941 $column = "increment_$column";
942 $svc_acct->$column($amount);
946 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
948 Inserts a prepayment in the specified amount for this customer. An optional
949 second argument can specify the prepayment identifier for tracking purposes.
950 If there is an error, returns the error, otherwise returns false.
954 sub insert_cust_pay_prepay {
955 shift->insert_cust_pay('PREP', @_);
958 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
960 Inserts a cash payment in the specified amount for this customer. An optional
961 second argument can specify the payment identifier for tracking purposes.
962 If there is an error, returns the error, otherwise returns false.
966 sub insert_cust_pay_cash {
967 shift->insert_cust_pay('CASH', @_);
970 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
972 Inserts a Western Union payment in the specified amount for this customer. An
973 optional second argument can specify the prepayment identifier for tracking
974 purposes. If there is an error, returns the error, otherwise returns false.
978 sub insert_cust_pay_west {
979 shift->insert_cust_pay('WEST', @_);
982 sub insert_cust_pay {
983 my( $self, $payby, $amount ) = splice(@_, 0, 3);
984 my $payinfo = scalar(@_) ? shift : '';
986 my $cust_pay = new FS::cust_pay {
987 'custnum' => $self->custnum,
988 'paid' => sprintf('%.2f', $amount),
989 #'_date' => #date the prepaid card was purchased???
991 'payinfo' => $payinfo,
999 This method is deprecated. See the I<depend_jobnum> option to the insert and
1000 order_pkgs methods for a better way to defer provisioning.
1002 Re-schedules all exports by calling the B<reexport> method of all associated
1003 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1004 otherwise returns false.
1011 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1012 "use the depend_jobnum option to insert or order_pkgs to delay export";
1014 local $SIG{HUP} = 'IGNORE';
1015 local $SIG{INT} = 'IGNORE';
1016 local $SIG{QUIT} = 'IGNORE';
1017 local $SIG{TERM} = 'IGNORE';
1018 local $SIG{TSTP} = 'IGNORE';
1019 local $SIG{PIPE} = 'IGNORE';
1021 my $oldAutoCommit = $FS::UID::AutoCommit;
1022 local $FS::UID::AutoCommit = 0;
1025 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1026 my $error = $cust_pkg->reexport;
1028 $dbh->rollback if $oldAutoCommit;
1033 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1038 =item delete [ OPTION => VALUE ... ]
1040 This deletes the customer. If there is an error, returns the error, otherwise
1043 This will completely remove all traces of the customer record. This is not
1044 what you want when a customer cancels service; for that, cancel all of the
1045 customer's packages (see L</cancel>).
1047 If the customer has any uncancelled packages, you need to pass a new (valid)
1048 customer number for those packages to be transferred to, as the "new_customer"
1049 option. Cancelled packages will be deleted. Did I mention that this is NOT
1050 what you want when a customer cancels service and that you really should be
1051 looking at L<FS::cust_pkg/cancel>?
1053 You can't delete a customer with invoices (see L<FS::cust_bill>),
1054 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1055 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1056 set the "delete_financials" option to a true value.
1061 my( $self, %opt ) = @_;
1063 local $SIG{HUP} = 'IGNORE';
1064 local $SIG{INT} = 'IGNORE';
1065 local $SIG{QUIT} = 'IGNORE';
1066 local $SIG{TERM} = 'IGNORE';
1067 local $SIG{TSTP} = 'IGNORE';
1068 local $SIG{PIPE} = 'IGNORE';
1070 my $oldAutoCommit = $FS::UID::AutoCommit;
1071 local $FS::UID::AutoCommit = 0;
1074 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1075 $dbh->rollback if $oldAutoCommit;
1076 return "Can't delete a master agent customer";
1079 #use FS::access_user
1080 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1081 $dbh->rollback if $oldAutoCommit;
1082 return "Can't delete a master employee customer";
1085 tie my %financial_tables, 'Tie::IxHash',
1086 'cust_bill' => 'invoices',
1087 'cust_statement' => 'statements',
1088 'cust_credit' => 'credits',
1089 'cust_pay' => 'payments',
1090 'cust_refund' => 'refunds',
1093 foreach my $table ( keys %financial_tables ) {
1095 my @records = $self->$table();
1097 if ( @records && ! $opt{'delete_financials'} ) {
1098 $dbh->rollback if $oldAutoCommit;
1099 return "Can't delete a customer with ". $financial_tables{$table};
1102 foreach my $record ( @records ) {
1103 my $error = $record->delete;
1105 $dbh->rollback if $oldAutoCommit;
1106 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1112 my @cust_pkg = $self->ncancelled_pkgs;
1114 my $new_custnum = $opt{'new_custnum'};
1115 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1116 $dbh->rollback if $oldAutoCommit;
1117 return "Invalid new customer number: $new_custnum";
1119 foreach my $cust_pkg ( @cust_pkg ) {
1120 my %hash = $cust_pkg->hash;
1121 $hash{'custnum'} = $new_custnum;
1122 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1123 my $error = $new_cust_pkg->replace($cust_pkg,
1124 options => { $cust_pkg->options },
1127 $dbh->rollback if $oldAutoCommit;
1132 my @cancelled_cust_pkg = $self->all_pkgs;
1133 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1134 my $error = $cust_pkg->delete;
1136 $dbh->rollback if $oldAutoCommit;
1141 #cust_tax_adjustment in financials?
1142 #cust_pay_pending? ouch
1144 foreach my $table (qw(
1145 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1146 cust_location cust_main_note cust_tax_adjustment
1147 cust_pay_void cust_pay_batch queue cust_tax_exempt
1149 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1150 my $error = $record->delete;
1152 $dbh->rollback if $oldAutoCommit;
1158 my $sth = $dbh->prepare(
1159 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1161 my $errstr = $dbh->errstr;
1162 $dbh->rollback if $oldAutoCommit;
1165 $sth->execute($self->custnum) or do {
1166 my $errstr = $sth->errstr;
1167 $dbh->rollback if $oldAutoCommit;
1173 my $ticket_dbh = '';
1174 if ($conf->config('ticket_system') eq 'RT_Internal') {
1176 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1177 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1178 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1179 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1182 if ( $ticket_dbh ) {
1184 my $ticket_sth = $ticket_dbh->prepare(
1185 'DELETE FROM Links WHERE Target = ?'
1187 my $errstr = $ticket_dbh->errstr;
1188 $dbh->rollback if $oldAutoCommit;
1191 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1193 my $errstr = $ticket_sth->errstr;
1194 $dbh->rollback if $oldAutoCommit;
1198 #check and see if the customer is the only link on the ticket, and
1199 #if so, set the ticket to deleted status in RT?
1200 #maybe someday, for now this will at least fix tickets not displaying
1204 #delete the customer record
1206 my $error = $self->SUPER::delete;
1208 $dbh->rollback if $oldAutoCommit;
1212 # cust_main exports!
1214 #my $export_args = $options{'export_args'} || [];
1217 map qsearch( 'part_export', {exportnum=>$_} ),
1218 $conf->config('cust_main-exports'); #, $agentnum
1220 foreach my $part_export ( @part_export ) {
1221 my $error = $part_export->export_delete( $self ); #, @$export_args);
1223 $dbh->rollback if $oldAutoCommit;
1224 return "exporting to ". $part_export->exporttype.
1225 " (transaction rolled back): $error";
1229 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1234 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1236 This merges this customer into the provided new custnum, and then deletes the
1237 customer. If there is an error, returns the error, otherwise returns false.
1239 The source customer's name, company name, phone numbers, agent,
1240 referring customer, customer class, advertising source, order taker, and
1241 billing information (except balance) are discarded.
1243 All packages are moved to the target customer. Packages with package locations
1244 are preserved. Packages without package locations are moved to a new package
1245 location with the source customer's service/shipping address.
1247 All invoices, statements, payments, credits and refunds are moved to the target
1248 customer. The source customer's balance is added to the target customer.
1250 All notes, attachments, tickets and customer tags are moved to the target
1253 Change history is not currently moved.
1258 my( $self, $new_custnum, %opt ) = @_;
1260 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1262 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1263 return "Invalid new customer number: $new_custnum";
1266 local $SIG{HUP} = 'IGNORE';
1267 local $SIG{INT} = 'IGNORE';
1268 local $SIG{QUIT} = 'IGNORE';
1269 local $SIG{TERM} = 'IGNORE';
1270 local $SIG{TSTP} = 'IGNORE';
1271 local $SIG{PIPE} = 'IGNORE';
1273 my $oldAutoCommit = $FS::UID::AutoCommit;
1274 local $FS::UID::AutoCommit = 0;
1277 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1278 $dbh->rollback if $oldAutoCommit;
1279 return "Can't merge a master agent customer";
1282 #use FS::access_user
1283 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1284 $dbh->rollback if $oldAutoCommit;
1285 return "Can't merge a master employee customer";
1288 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1289 'status' => { op=>'!=', value=>'done' },
1293 $dbh->rollback if $oldAutoCommit;
1294 return "Can't merge a customer with pending payments";
1297 tie my %financial_tables, 'Tie::IxHash',
1298 'cust_bill' => 'invoices',
1299 'cust_statement' => 'statements',
1300 'cust_credit' => 'credits',
1301 'cust_pay' => 'payments',
1302 'cust_pay_void' => 'voided payments',
1303 'cust_refund' => 'refunds',
1306 foreach my $table ( keys %financial_tables ) {
1308 my @records = $self->$table();
1310 foreach my $record ( @records ) {
1311 $record->custnum($new_custnum);
1312 my $error = $record->replace;
1314 $dbh->rollback if $oldAutoCommit;
1315 return "Error merging ". $financial_tables{$table}. ": $error\n";
1321 my $name = $self->ship_name;
1323 my $locationnum = '';
1324 foreach my $cust_pkg ( $self->all_pkgs ) {
1325 $cust_pkg->custnum($new_custnum);
1327 unless ( $cust_pkg->locationnum ) {
1328 unless ( $locationnum ) {
1329 my $cust_location = new FS::cust_location {
1330 $self->location_hash,
1331 'custnum' => $new_custnum,
1333 my $error = $cust_location->insert;
1335 $dbh->rollback if $oldAutoCommit;
1338 $locationnum = $cust_location->locationnum;
1340 $cust_pkg->locationnum($locationnum);
1343 my $error = $cust_pkg->replace;
1345 $dbh->rollback if $oldAutoCommit;
1349 # add customer (ship) name to svc_phone.phone_name if blank
1350 my @cust_svc = $cust_pkg->cust_svc;
1351 foreach my $cust_svc (@cust_svc) {
1352 my($label, $value, $svcdb) = $cust_svc->label;
1353 next unless $svcdb eq 'svc_phone';
1354 my $svc_phone = $cust_svc->svc_x;
1355 next if $svc_phone->phone_name;
1356 $svc_phone->phone_name($name);
1357 my $error = $svc_phone->replace;
1359 $dbh->rollback if $oldAutoCommit;
1367 # cust_tax_exempt (texas tax exemptions)
1368 # cust_recon (some sort of not-well understood thing for OnPac)
1370 #these are moved over
1371 foreach my $table (qw(
1372 cust_tag cust_location contact cust_attachment cust_main_note
1373 cust_tax_adjustment cust_pay_batch queue
1375 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1376 $record->custnum($new_custnum);
1377 my $error = $record->replace;
1379 $dbh->rollback if $oldAutoCommit;
1385 #these aren't preserved
1386 foreach my $table (qw(
1387 cust_main_exemption cust_main_invoice
1389 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1390 my $error = $record->delete;
1392 $dbh->rollback if $oldAutoCommit;
1399 my $sth = $dbh->prepare(
1400 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1402 my $errstr = $dbh->errstr;
1403 $dbh->rollback if $oldAutoCommit;
1406 $sth->execute($new_custnum, $self->custnum) or do {
1407 my $errstr = $sth->errstr;
1408 $dbh->rollback if $oldAutoCommit;
1414 my $ticket_dbh = '';
1415 if ($conf->config('ticket_system') eq 'RT_Internal') {
1417 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1418 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1419 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1420 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1423 if ( $ticket_dbh ) {
1425 my $ticket_sth = $ticket_dbh->prepare(
1426 'UPDATE Links SET Target = ? WHERE Target = ?'
1428 my $errstr = $ticket_dbh->errstr;
1429 $dbh->rollback if $oldAutoCommit;
1432 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1433 'freeside://freeside/cust_main/'.$self->custnum)
1435 my $errstr = $ticket_sth->errstr;
1436 $dbh->rollback if $oldAutoCommit;
1442 #delete the customer record
1444 my $error = $self->delete;
1446 $dbh->rollback if $oldAutoCommit;
1450 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1455 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1458 Replaces the OLD_RECORD with this one in the database. If there is an error,
1459 returns the error, otherwise returns false.
1461 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1462 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1463 expected and rollback the entire transaction; it is not necessary to call
1464 check_invoicing_list first. Here's an example:
1466 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1468 Currently available options are: I<tax_exemption>.
1470 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1471 of tax names and exemption numbers. FS::cust_main_exemption records will be
1472 deleted and inserted as appropriate.
1479 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1481 : $self->replace_old;
1485 warn "$me replace called\n"
1488 my $curuser = $FS::CurrentUser::CurrentUser;
1489 if ( $self->payby eq 'COMP'
1490 && $self->payby ne $old->payby
1491 && ! $curuser->access_right('Complimentary customer')
1494 return "You are not permitted to create complimentary accounts.";
1497 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1498 && $conf->exists('enable_taxproducts')
1501 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1503 $self->set('geocode', '')
1504 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1505 && length($self->get($pre.'zip')) >= 10;
1508 for my $pre ( grep $old->get($_.'coord_auto'), ( '', 'ship_' ) ) {
1510 $self->set($pre.'coord_auto', '') && next
1511 if $self->get($pre.'latitude') && $self->get($pre.'longitude')
1512 && ( $self->get($pre.'latitude') != $old->get($pre.'latitude')
1513 || $self->get($pre.'longitude') != $old->get($pre.'longitude')
1516 $self->set_coord($pre)
1517 if $old->get($pre.'address1') ne $self->get($pre.'address1')
1518 || $old->get($pre.'city') ne $self->get($pre.'city')
1519 || $old->get($pre.'state') ne $self->get($pre.'state')
1520 || $old->get($pre.'country') ne $self->get($pre.'country');
1524 unless ( $import ) {
1526 if ! $self->coord_auto && ! $self->latitude && ! $self->longitude;
1528 $self->set_coord('ship_')
1529 if $self->has_ship_address && ! $self->ship_coord_auto
1530 && ! $self->ship_latitude && ! $self->ship_longitude;
1533 local($ignore_expired_card) = 1
1534 if $old->payby =~ /^(CARD|DCRD)$/
1535 && $self->payby =~ /^(CARD|DCRD)$/
1536 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1538 local($ignore_banned_card) = 1
1539 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1540 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1541 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1543 if ( $self->censustract ne '' and $self->censustract ne $old->censustract ) {
1544 # update censusyear whenever tract code changes
1545 $self->censusyear($conf->config('census_year')||'2012');
1548 return "Invoicing locale is required"
1551 && $conf->exists('cust_main-require_locale');
1553 local $SIG{HUP} = 'IGNORE';
1554 local $SIG{INT} = 'IGNORE';
1555 local $SIG{QUIT} = 'IGNORE';
1556 local $SIG{TERM} = 'IGNORE';
1557 local $SIG{TSTP} = 'IGNORE';
1558 local $SIG{PIPE} = 'IGNORE';
1560 my $oldAutoCommit = $FS::UID::AutoCommit;
1561 local $FS::UID::AutoCommit = 0;
1564 my $error = $self->SUPER::replace($old);
1567 $dbh->rollback if $oldAutoCommit;
1571 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1572 my $invoicing_list = shift @param;
1573 $error = $self->check_invoicing_list( $invoicing_list );
1575 $dbh->rollback if $oldAutoCommit;
1578 $self->invoicing_list( $invoicing_list );
1581 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1583 #this could be more efficient than deleting and re-inserting, if it matters
1584 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1585 my $error = $cust_tag->delete;
1587 $dbh->rollback if $oldAutoCommit;
1591 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1592 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1593 'custnum' => $self->custnum };
1594 my $error = $cust_tag->insert;
1596 $dbh->rollback if $oldAutoCommit;
1603 my %options = @param;
1605 my $tax_exemption = delete $options{'tax_exemption'};
1606 if ( $tax_exemption ) {
1608 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1609 if ref($tax_exemption) eq 'ARRAY';
1611 my %cust_main_exemption =
1612 map { $_->taxname => $_ }
1613 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1615 foreach my $taxname ( keys %$tax_exemption ) {
1617 if ( $cust_main_exemption{$taxname} &&
1618 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1621 delete $cust_main_exemption{$taxname};
1625 my $cust_main_exemption = new FS::cust_main_exemption {
1626 'custnum' => $self->custnum,
1627 'taxname' => $taxname,
1628 'exempt_number' => $tax_exemption->{$taxname},
1630 my $error = $cust_main_exemption->insert;
1632 $dbh->rollback if $oldAutoCommit;
1633 return "inserting cust_main_exemption (transaction rolled back): $error";
1637 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1638 my $error = $cust_main_exemption->delete;
1640 $dbh->rollback if $oldAutoCommit;
1641 return "deleting cust_main_exemption (transaction rolled back): $error";
1647 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1648 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1649 && $self->get('payinfo') !~ /^99\d{14}$/
1651 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1656 # card/check/lec info has changed, want to retry realtime_ invoice events
1657 my $error = $self->retry_realtime;
1659 $dbh->rollback if $oldAutoCommit;
1664 unless ( $import || $skip_fuzzyfiles ) {
1665 $error = $self->queue_fuzzyfiles_update;
1667 $dbh->rollback if $oldAutoCommit;
1668 return "updating fuzzy search cache: $error";
1672 # FS::geocode_Mixin::after_replace ?
1673 # though this will go away anyway once we move customer bill/service
1674 # locations into cust_location
1675 # We can trigger this on any address change--just have to make sure
1676 # not to trigger it on itself.
1677 if ( $conf->config('tax_district_method') and !$import
1678 and ( $self->get('ship_address1') ne $old->get('ship_address1')
1679 or $self->get('address1') ne $old->get('address1') ) ) {
1680 my $queue = new FS::queue {
1681 'job' => 'FS::geocode_Mixin::process_district_update',
1682 'custnum' => $self->custnum,
1684 my $error = $queue->insert( ref($self), $self->custnum );
1686 $dbh->rollback if $oldAutoCommit;
1687 return "queueing tax district update: $error";
1691 # cust_main exports!
1693 my $export_args = $options{'export_args'} || [];
1696 map qsearch( 'part_export', {exportnum=>$_} ),
1697 $conf->config('cust_main-exports'); #, $agentnum
1699 foreach my $part_export ( @part_export ) {
1700 my $error = $part_export->export_replace( $self, $old, @$export_args);
1702 $dbh->rollback if $oldAutoCommit;
1703 return "exporting to ". $part_export->exporttype.
1704 " (transaction rolled back): $error";
1708 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1713 =item queue_fuzzyfiles_update
1715 Used by insert & replace to update the fuzzy search cache
1719 use FS::cust_main::Search;
1720 sub queue_fuzzyfiles_update {
1723 local $SIG{HUP} = 'IGNORE';
1724 local $SIG{INT} = 'IGNORE';
1725 local $SIG{QUIT} = 'IGNORE';
1726 local $SIG{TERM} = 'IGNORE';
1727 local $SIG{TSTP} = 'IGNORE';
1728 local $SIG{PIPE} = 'IGNORE';
1730 my $oldAutoCommit = $FS::UID::AutoCommit;
1731 local $FS::UID::AutoCommit = 0;
1734 my $queue = new FS::queue { 'job' => 'FS::cust_main::Search::append_fuzzyfiles' };
1735 my $error = $queue->insert( map $self->getfield($_), @FS::cust_main::Search::fuzzyfields );
1737 $dbh->rollback if $oldAutoCommit;
1738 return "queueing job (transaction rolled back): $error";
1741 if ( $self->ship_last ) {
1742 $queue = new FS::queue { 'job' => 'FS::cust_main::Search::append_fuzzyfiles' };
1743 $error = $queue->insert( map $self->getfield("ship_$_"), @FS::cust_main::Search::fuzzyfields );
1745 $dbh->rollback if $oldAutoCommit;
1746 return "queueing job (transaction rolled back): $error";
1750 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1757 Checks all fields to make sure this is a valid customer record. If there is
1758 an error, returns the error, otherwise returns false. Called by the insert
1759 and replace methods.
1766 warn "$me check BEFORE: \n". $self->_dump
1770 $self->ut_numbern('custnum')
1771 || $self->ut_number('agentnum')
1772 || $self->ut_textn('agent_custid')
1773 || $self->ut_number('refnum')
1774 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1775 || $self->ut_textn('custbatch')
1776 || $self->ut_name('last')
1777 || $self->ut_name('first')
1778 || $self->ut_snumbern('signupdate')
1779 || $self->ut_snumbern('birthdate')
1780 || $self->ut_snumbern('spouse_birthdate')
1781 || $self->ut_snumbern('anniversary_date')
1782 || $self->ut_textn('company')
1783 || $self->ut_text('address1')
1784 || $self->ut_textn('address2')
1785 || $self->ut_text('city')
1786 || $self->ut_textn('county')
1787 || $self->ut_textn('state')
1788 || $self->ut_country('country')
1789 || $self->ut_coordn('latitude')
1790 || $self->ut_coordn('longitude')
1791 || $self->ut_enum('coord_auto', [ '', 'Y' ])
1792 || $self->ut_numbern('censusyear')
1793 || $self->ut_anything('comments')
1794 || $self->ut_numbern('referral_custnum')
1795 || $self->ut_textn('stateid')
1796 || $self->ut_textn('stateid_state')
1797 || $self->ut_textn('invoice_terms')
1798 || $self->ut_alphan('geocode')
1799 || $self->ut_alphan('district')
1800 || $self->ut_floatn('cdr_termination_percentage')
1801 || $self->ut_floatn('credit_limit')
1802 || $self->ut_numbern('billday')
1803 || $self->ut_numbern('prorate_day')
1804 || $self->ut_enum('edit_subject', [ '', 'Y' ] )
1805 || $self->ut_enum('calling_list_exempt', [ '', 'Y' ] )
1806 || $self->ut_enum('invoice_noemail', [ '', 'Y' ] )
1807 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1811 unless $import || ($self->latitude && $self->longitude);
1813 #barf. need message catalogs. i18n. etc.
1814 $error .= "Please select an advertising source."
1815 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1816 return $error if $error;
1818 return "Unknown agent"
1819 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1821 return "Unknown refnum"
1822 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1824 return "Unknown referring custnum: ". $self->referral_custnum
1825 unless ! $self->referral_custnum
1826 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1828 if ( $self->censustract ne '' ) {
1829 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1830 or return "Illegal census tract: ". $self->censustract;
1832 $self->censustract("$1.$2");
1835 if ( $self->ss eq '' ) {
1840 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1841 or return "Illegal social security number: ". $self->ss;
1842 $self->ss("$1-$2-$3");
1846 # bad idea to disable, causes billing to fail because of no tax rates later
1847 # except we don't fail any more
1848 unless ( $import ) {
1849 unless ( qsearch('cust_main_county', {
1850 'country' => $self->country,
1853 return "Unknown state/county/country: ".
1854 $self->state. "/". $self->county. "/". $self->country
1855 unless qsearch('cust_main_county',{
1856 'state' => $self->state,
1857 'county' => $self->county,
1858 'country' => $self->country,
1864 $self->ut_phonen('daytime', $self->country)
1865 || $self->ut_phonen('night', $self->country)
1866 || $self->ut_phonen('fax', $self->country)
1867 || $self->ut_phonen('mobile', $self->country)
1869 return $error if $error;
1871 unless ( $ignore_illegal_zip ) {
1872 $error = $self->ut_zip('zip', $self->country);
1873 return $error if $error;
1876 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1877 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1880 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1882 : FS::Msgcat::_gettext('daytime');
1883 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1885 : FS::Msgcat::_gettext('night');
1887 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1889 : FS::Msgcat::_gettext('mobile');
1891 return "$daytime_label, $night_label or $mobile_label is required"
1895 if ( $self->has_ship_address
1896 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1897 $self->addr_fields )
1901 $self->ut_name('ship_last')
1902 || $self->ut_name('ship_first')
1903 || $self->ut_textn('ship_company')
1904 || $self->ut_text('ship_address1')
1905 || $self->ut_textn('ship_address2')
1906 || $self->ut_text('ship_city')
1907 || $self->ut_textn('ship_county')
1908 || $self->ut_textn('ship_state')
1909 || $self->ut_country('ship_country')
1910 || $self->ut_coordn('ship_latitude')
1911 || $self->ut_coordn('ship_longitude')
1912 || $self->ut_enum('ship_coord_auto', [ '', 'Y' ] )
1914 return $error if $error;
1916 $self->set_coord('ship_')
1917 unless $import || ($self->ship_latitude && $self->ship_longitude);
1919 #false laziness with above
1920 unless ( qsearchs('cust_main_county', {
1921 'country' => $self->ship_country,
1924 return "Unknown ship_state/ship_county/ship_country: ".
1925 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1926 unless qsearch('cust_main_county',{
1927 'state' => $self->ship_state,
1928 'county' => $self->ship_county,
1929 'country' => $self->ship_country,
1935 $self->ut_phonen('ship_daytime', $self->ship_country)
1936 || $self->ut_phonen('ship_night', $self->ship_country)
1937 || $self->ut_phonen('ship_fax', $self->ship_country)
1938 || $self->ut_phonen('ship_mobile', $self->ship_country)
1940 return $error if $error;
1942 unless ( $ignore_illegal_zip ) {
1943 $error = $self->ut_zip('ship_zip', $self->ship_country);
1944 return $error if $error;
1946 return "Unit # is required."
1947 if $self->ship_address2 =~ /^\s*$/
1948 && $conf->exists('cust_main-require_address2');
1950 } else { # ship_ info eq billing info, so don't store dup info in database
1952 $self->setfield("ship_$_", '')
1953 foreach $self->addr_fields;
1955 return "Unit # is required."
1956 if $self->address2 =~ /^\s*$/
1957 && $conf->exists('cust_main-require_address2');
1961 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1962 # or return "Illegal payby: ". $self->payby;
1964 FS::payby->can_payby($self->table, $self->payby)
1965 or return "Illegal payby: ". $self->payby;
1967 $error = $self->ut_numbern('paystart_month')
1968 || $self->ut_numbern('paystart_year')
1969 || $self->ut_numbern('payissue')
1970 || $self->ut_textn('paytype')
1972 return $error if $error;
1974 if ( $self->payip eq '' ) {
1977 $error = $self->ut_ip('payip');
1978 return $error if $error;
1981 # If it is encrypted and the private key is not availaible then we can't
1982 # check the credit card.
1983 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1985 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1987 my $payinfo = $self->payinfo;
1988 $payinfo =~ s/\D//g;
1989 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1990 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1992 $self->payinfo($payinfo);
1994 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1996 return gettext('unknown_card_type')
1997 if $self->payinfo !~ /^99\d{14}$/ #token
1998 && cardtype($self->payinfo) eq "Unknown";
2000 unless ( $ignore_banned_card ) {
2001 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2003 if ( $ban->bantype eq 'warn' ) {
2004 #or others depending on value of $ban->reason ?
2005 return '_duplicate_card'.
2006 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
2007 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
2008 ' (ban# '. $ban->bannum. ')'
2009 unless $self->override_ban_warn;
2011 return 'Banned credit card: banned on '.
2012 time2str('%a %h %o at %r', $ban->_date).
2013 ' by '. $ban->otaker.
2014 ' (ban# '. $ban->bannum. ')';
2019 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
2020 if ( cardtype($self->payinfo) eq 'American Express card' ) {
2021 $self->paycvv =~ /^(\d{4})$/
2022 or return "CVV2 (CID) for American Express cards is four digits.";
2025 $self->paycvv =~ /^(\d{3})$/
2026 or return "CVV2 (CVC2/CID) is three digits.";
2033 my $cardtype = cardtype($payinfo);
2034 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
2036 return "Start date or issue number is required for $cardtype cards"
2037 unless $self->paystart_month && $self->paystart_year or $self->payissue;
2039 return "Start month must be between 1 and 12"
2040 if $self->paystart_month
2041 and $self->paystart_month < 1 || $self->paystart_month > 12;
2043 return "Start year must be 1990 or later"
2044 if $self->paystart_year
2045 and $self->paystart_year < 1990;
2047 return "Issue number must be beween 1 and 99"
2049 and $self->payissue < 1 || $self->payissue > 99;
2052 $self->paystart_month('');
2053 $self->paystart_year('');
2054 $self->payissue('');
2057 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
2059 my $payinfo = $self->payinfo;
2060 $payinfo =~ s/[^\d\@\.]//g;
2061 if ( $conf->config('echeck-country') eq 'CA' ) {
2062 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
2063 or return 'invalid echeck account@branch.bank';
2064 $payinfo = "$1\@$2.$3";
2065 } elsif ( $conf->config('echeck-country') eq 'US' ) {
2066 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
2067 $payinfo = "$1\@$2";
2069 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2070 $payinfo = "$1\@$2";
2072 $self->payinfo($payinfo);
2075 unless ( $ignore_banned_card ) {
2076 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2078 if ( $ban->bantype eq 'warn' ) {
2079 #or others depending on value of $ban->reason ?
2080 return '_duplicate_ach' unless $self->override_ban_warn;
2082 return 'Banned ACH account: banned on '.
2083 time2str('%a %h %o at %r', $ban->_date).
2084 ' by '. $ban->otaker.
2085 ' (ban# '. $ban->bannum. ')';
2090 } elsif ( $self->payby eq 'LECB' ) {
2092 my $payinfo = $self->payinfo;
2093 $payinfo =~ s/\D//g;
2094 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2096 $self->payinfo($payinfo);
2099 } elsif ( $self->payby eq 'BILL' ) {
2101 $error = $self->ut_textn('payinfo');
2102 return "Illegal P.O. number: ". $self->payinfo if $error;
2105 } elsif ( $self->payby eq 'COMP' ) {
2107 my $curuser = $FS::CurrentUser::CurrentUser;
2108 if ( ! $self->custnum
2109 && ! $curuser->access_right('Complimentary customer')
2112 return "You are not permitted to create complimentary accounts."
2115 $error = $self->ut_textn('payinfo');
2116 return "Illegal comp account issuer: ". $self->payinfo if $error;
2119 } elsif ( $self->payby eq 'PREPAY' ) {
2121 my $payinfo = $self->payinfo;
2122 $payinfo =~ s/\W//g; #anything else would just confuse things
2123 $self->payinfo($payinfo);
2124 $error = $self->ut_alpha('payinfo');
2125 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2126 return "Unknown prepayment identifier"
2127 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2132 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2133 return "Expiration date required"
2134 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2138 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2139 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2140 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2141 ( $m, $y ) = ( $2, "19$1" );
2142 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2143 ( $m, $y ) = ( $3, "20$2" );
2145 return "Illegal expiration date: ". $self->paydate;
2147 $m = sprintf('%02d',$m);
2148 $self->paydate("$y-$m-01");
2149 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2150 return gettext('expired_card')
2152 && !$ignore_expired_card
2153 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2156 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2157 ( ! $conf->exists('require_cardname')
2158 || $self->payby !~ /^(CARD|DCRD)$/ )
2160 $self->payname( $self->first. " ". $self->getfield('last') );
2162 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2163 or return gettext('illegal_name'). " payname: ". $self->payname;
2167 return "Please select an invoicing locale"
2170 && $conf->exists('cust_main-require_locale');
2172 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2173 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2177 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2179 warn "$me check AFTER: \n". $self->_dump
2182 $self->SUPER::check;
2187 Returns a list of fields which have ship_ duplicates.
2192 qw( last first company
2193 address1 address2 city county state zip country
2195 daytime night fax mobile
2199 =item has_ship_address
2201 Returns true if this customer record has a separate shipping address.
2205 sub has_ship_address {
2207 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2212 Returns a list of key/value pairs, with the following keys: address1,
2213 adddress2, city, county, state, zip, country, district, and geocode. The
2214 shipping address is used if present.
2220 Returns all locations (see L<FS::cust_location>) for this customer.
2226 qsearch('cust_location', { 'custnum' => $self->custnum } );
2231 Returns all contacts (see L<FS::contact>) for this customer.
2235 #already used :/ sub contact {
2238 qsearch('contact', { 'custnum' => $self->custnum } );
2243 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2244 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2245 on success or a list of errors.
2251 grep { $_->unsuspend } $self->suspended_pkgs;
2256 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2258 Returns a list: an empty list on success or a list of errors.
2264 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2267 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2269 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2270 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2271 of a list of pkgparts; the hashref has the following keys:
2275 =item pkgparts - listref of pkgparts
2277 =item (other options are passed to the suspend method)
2282 Returns a list: an empty list on success or a list of errors.
2286 sub suspend_if_pkgpart {
2288 my (@pkgparts, %opt);
2289 if (ref($_[0]) eq 'HASH'){
2290 @pkgparts = @{$_[0]{pkgparts}};
2295 grep { $_->suspend(%opt) }
2296 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2297 $self->unsuspended_pkgs;
2300 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2302 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2303 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2304 instead of a list of pkgparts; the hashref has the following keys:
2308 =item pkgparts - listref of pkgparts
2310 =item (other options are passed to the suspend method)
2314 Returns a list: an empty list on success or a list of errors.
2318 sub suspend_unless_pkgpart {
2320 my (@pkgparts, %opt);
2321 if (ref($_[0]) eq 'HASH'){
2322 @pkgparts = @{$_[0]{pkgparts}};
2327 grep { $_->suspend(%opt) }
2328 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2329 $self->unsuspended_pkgs;
2332 =item cancel [ OPTION => VALUE ... ]
2334 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2336 Available options are:
2340 =item quiet - can be set true to supress email cancellation notices.
2342 =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.
2344 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2346 =item nobill - can be set true to skip billing if it might otherwise be done.
2350 Always returns a list: an empty list on success or a list of errors.
2354 # nb that dates are not specified as valid options to this method
2357 my( $self, %opt ) = @_;
2359 warn "$me cancel called on customer ". $self->custnum. " with options ".
2360 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2363 return ( 'access denied' )
2364 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2366 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2368 #should try decryption (we might have the private key)
2369 # and if not maybe queue a job for the server that does?
2370 return ( "Can't (yet) ban encrypted credit cards" )
2371 if $self->is_encrypted($self->payinfo);
2373 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2374 my $error = $ban->insert;
2375 return ( $error ) if $error;
2379 my @pkgs = $self->ncancelled_pkgs;
2381 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2383 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2384 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2388 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2389 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2392 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2395 sub _banned_pay_hashref {
2406 'payby' => $payby2ban{$self->payby},
2407 'payinfo' => $self->payinfo,
2408 #don't ever *search* on reason! #'reason' =>
2412 sub _new_banned_pay_hashref {
2414 my $hr = $self->_banned_pay_hashref;
2415 $hr->{payinfo} = md5_base64($hr->{payinfo});
2421 Returns all notes (see L<FS::cust_main_note>) for this customer.
2426 my($self,$orderby_classnum) = (shift,shift);
2427 my $orderby = "_DATE DESC";
2428 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2429 qsearch( 'cust_main_note',
2430 { 'custnum' => $self->custnum },
2432 "ORDER BY $orderby",
2438 Returns the agent (see L<FS::agent>) for this customer.
2444 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2449 Returns the agent name (see L<FS::agent>) for this customer.
2455 $self->agent->agent;
2460 Returns any tags associated with this customer, as FS::cust_tag objects,
2461 or an empty list if there are no tags.
2467 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2472 Returns any tags associated with this customer, as FS::part_tag objects,
2473 or an empty list if there are no tags.
2479 map $_->part_tag, $self->cust_tag;
2485 Returns the customer class, as an FS::cust_class object, or the empty string
2486 if there is no customer class.
2492 if ( $self->classnum ) {
2493 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2501 Returns the customer category name, or the empty string if there is no customer
2508 my $cust_class = $self->cust_class;
2510 ? $cust_class->categoryname
2516 Returns the customer class name, or the empty string if there is no customer
2523 my $cust_class = $self->cust_class;
2525 ? $cust_class->classname
2529 =item BILLING METHODS
2531 Documentation on billing methods has been moved to
2532 L<FS::cust_main::Billing>.
2534 =item REALTIME BILLING METHODS
2536 Documentation on realtime billing methods has been moved to
2537 L<FS::cust_main::Billing_Realtime>.
2541 Removes the I<paycvv> field from the database directly.
2543 If there is an error, returns the error, otherwise returns false.
2549 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2550 or return dbh->errstr;
2551 $sth->execute($self->custnum)
2552 or return $sth->errstr;
2557 =item batch_card OPTION => VALUE...
2559 Adds a payment for this invoice to the pending credit card batch (see
2560 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2561 runs the payment using a realtime gateway.
2566 my ($self, %options) = @_;
2569 if (exists($options{amount})) {
2570 $amount = $options{amount};
2572 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2574 return '' unless $amount > 0;
2576 my $invnum = delete $options{invnum};
2577 my $payby = $options{payby} || $self->payby; #still dubious
2579 if ($options{'realtime'}) {
2580 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2586 my $oldAutoCommit = $FS::UID::AutoCommit;
2587 local $FS::UID::AutoCommit = 0;
2590 #this needs to handle mysql as well as Pg, like svc_acct.pm
2591 #(make it into a common function if folks need to do batching with mysql)
2592 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2593 or return "Cannot lock pay_batch: " . $dbh->errstr;
2597 'payby' => FS::payby->payby2payment($payby),
2599 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2601 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2603 unless ( $pay_batch ) {
2604 $pay_batch = new FS::pay_batch \%pay_batch;
2605 my $error = $pay_batch->insert;
2607 $dbh->rollback if $oldAutoCommit;
2608 die "error creating new batch: $error\n";
2612 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2613 'batchnum' => $pay_batch->batchnum,
2614 'custnum' => $self->custnum,
2617 foreach (qw( address1 address2 city state zip country latitude longitude
2618 payby payinfo paydate payname ))
2620 $options{$_} = '' unless exists($options{$_});
2623 my $cust_pay_batch = new FS::cust_pay_batch ( {
2624 'batchnum' => $pay_batch->batchnum,
2625 'invnum' => $invnum || 0, # is there a better value?
2626 # this field should be
2628 # cust_bill_pay_batch now
2629 'custnum' => $self->custnum,
2630 'last' => $self->getfield('last'),
2631 'first' => $self->getfield('first'),
2632 'address1' => $options{address1} || $self->address1,
2633 'address2' => $options{address2} || $self->address2,
2634 'city' => $options{city} || $self->city,
2635 'state' => $options{state} || $self->state,
2636 'zip' => $options{zip} || $self->zip,
2637 'country' => $options{country} || $self->country,
2638 'payby' => $options{payby} || $self->payby,
2639 'payinfo' => $options{payinfo} || $self->payinfo,
2640 'exp' => $options{paydate} || $self->paydate,
2641 'payname' => $options{payname} || $self->payname,
2642 'amount' => $amount, # consolidating
2645 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2646 if $old_cust_pay_batch;
2649 if ($old_cust_pay_batch) {
2650 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2652 $error = $cust_pay_batch->insert;
2656 $dbh->rollback if $oldAutoCommit;
2660 my $unapplied = $self->total_unapplied_credits
2661 + $self->total_unapplied_payments
2662 + $self->in_transit_payments;
2663 foreach my $cust_bill ($self->open_cust_bill) {
2664 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2665 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2666 'invnum' => $cust_bill->invnum,
2667 'paybatchnum' => $cust_pay_batch->paybatchnum,
2668 'amount' => $cust_bill->owed,
2671 if ($unapplied >= $cust_bill_pay_batch->amount){
2672 $unapplied -= $cust_bill_pay_batch->amount;
2675 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2676 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2678 $error = $cust_bill_pay_batch->insert;
2680 $dbh->rollback if $oldAutoCommit;
2685 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2691 Returns the total owed for this customer on all invoices
2692 (see L<FS::cust_bill/owed>).
2698 $self->total_owed_date(2145859200); #12/31/2037
2701 =item total_owed_date TIME
2703 Returns the total owed for this customer on all invoices with date earlier than
2704 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2705 see L<Time::Local> and L<Date::Parse> for conversion functions.
2709 sub total_owed_date {
2713 my $custnum = $self->custnum;
2715 my $owed_sql = FS::cust_bill->owed_sql;
2718 SELECT SUM($owed_sql) FROM cust_bill
2719 WHERE custnum = $custnum
2723 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2727 =item total_owed_pkgnum PKGNUM
2729 Returns the total owed on all invoices for this customer's specific package
2730 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2734 sub total_owed_pkgnum {
2735 my( $self, $pkgnum ) = @_;
2736 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2739 =item total_owed_date_pkgnum TIME PKGNUM
2741 Returns the total owed for this customer's specific package when using
2742 experimental package balances on all invoices with date earlier than
2743 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2744 see L<Time::Local> and L<Date::Parse> for conversion functions.
2748 sub total_owed_date_pkgnum {
2749 my( $self, $time, $pkgnum ) = @_;
2752 foreach my $cust_bill (
2753 grep { $_->_date <= $time }
2754 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2756 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2758 sprintf( "%.2f", $total_bill );
2764 Returns the total amount of all payments.
2771 $total += $_->paid foreach $self->cust_pay;
2772 sprintf( "%.2f", $total );
2775 =item total_unapplied_credits
2777 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2778 customer. See L<FS::cust_credit/credited>.
2780 =item total_credited
2782 Old name for total_unapplied_credits. Don't use.
2786 sub total_credited {
2787 #carp "total_credited deprecated, use total_unapplied_credits";
2788 shift->total_unapplied_credits(@_);
2791 sub total_unapplied_credits {
2794 my $custnum = $self->custnum;
2796 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2799 SELECT SUM($unapplied_sql) FROM cust_credit
2800 WHERE custnum = $custnum
2803 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2807 =item total_unapplied_credits_pkgnum PKGNUM
2809 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2810 customer. See L<FS::cust_credit/credited>.
2814 sub total_unapplied_credits_pkgnum {
2815 my( $self, $pkgnum ) = @_;
2816 my $total_credit = 0;
2817 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2818 sprintf( "%.2f", $total_credit );
2822 =item total_unapplied_payments
2824 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2825 See L<FS::cust_pay/unapplied>.
2829 sub total_unapplied_payments {
2832 my $custnum = $self->custnum;
2834 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2837 SELECT SUM($unapplied_sql) FROM cust_pay
2838 WHERE custnum = $custnum
2841 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2845 =item total_unapplied_payments_pkgnum PKGNUM
2847 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2848 specific package when using experimental package balances. See
2849 L<FS::cust_pay/unapplied>.
2853 sub total_unapplied_payments_pkgnum {
2854 my( $self, $pkgnum ) = @_;
2855 my $total_unapplied = 0;
2856 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2857 sprintf( "%.2f", $total_unapplied );
2861 =item total_unapplied_refunds
2863 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2864 customer. See L<FS::cust_refund/unapplied>.
2868 sub total_unapplied_refunds {
2870 my $custnum = $self->custnum;
2872 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2875 SELECT SUM($unapplied_sql) FROM cust_refund
2876 WHERE custnum = $custnum
2879 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2885 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2886 total_unapplied_credits minus total_unapplied_payments).
2892 $self->balance_date_range;
2895 =item balance_date TIME
2897 Returns the balance for this customer, only considering invoices with date
2898 earlier than TIME (total_owed_date minus total_credited minus
2899 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2900 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2907 $self->balance_date_range(shift);
2910 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2912 Returns the balance for this customer, optionally considering invoices with
2913 date earlier than START_TIME, and not later than END_TIME
2914 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2916 Times are specified as SQL fragments or numeric
2917 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2918 L<Date::Parse> for conversion functions. The empty string can be passed
2919 to disable that time constraint completely.
2921 Available options are:
2925 =item unapplied_date
2927 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)
2933 sub balance_date_range {
2935 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2936 ') FROM cust_main WHERE custnum='. $self->custnum;
2937 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2940 =item balance_pkgnum PKGNUM
2942 Returns the balance for this customer's specific package when using
2943 experimental package balances (total_owed plus total_unrefunded, minus
2944 total_unapplied_credits minus total_unapplied_payments)
2948 sub balance_pkgnum {
2949 my( $self, $pkgnum ) = @_;
2952 $self->total_owed_pkgnum($pkgnum)
2953 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2954 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2955 - $self->total_unapplied_credits_pkgnum($pkgnum)
2956 - $self->total_unapplied_payments_pkgnum($pkgnum)
2960 =item in_transit_payments
2962 Returns the total of requests for payments for this customer pending in
2963 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2967 sub in_transit_payments {
2969 my $in_transit_payments = 0;
2970 foreach my $pay_batch ( qsearch('pay_batch', {
2973 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2974 'batchnum' => $pay_batch->batchnum,
2975 'custnum' => $self->custnum,
2977 $in_transit_payments += $cust_pay_batch->amount;
2980 sprintf( "%.2f", $in_transit_payments );
2985 Returns a hash of useful information for making a payment.
2995 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2996 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2997 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3001 For credit card transactions:
3013 For electronic check transactions:
3028 $return{balance} = $self->balance;
3030 $return{payname} = $self->payname
3031 || ( $self->first. ' '. $self->get('last') );
3033 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
3035 $return{payby} = $self->payby;
3036 $return{stateid_state} = $self->stateid_state;
3038 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3039 $return{card_type} = cardtype($self->payinfo);
3040 $return{payinfo} = $self->paymask;
3042 @return{'month', 'year'} = $self->paydate_monthyear;
3046 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3047 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3048 $return{payinfo1} = $payinfo1;
3049 $return{payinfo2} = $payinfo2;
3050 $return{paytype} = $self->paytype;
3051 $return{paystate} = $self->paystate;
3055 #doubleclick protection
3057 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3063 =item paydate_monthyear
3065 Returns a two-element list consisting of the month and year of this customer's
3066 paydate (credit card expiration date for CARD customers)
3070 sub paydate_monthyear {
3072 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3074 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3083 Returns the exact time in seconds corresponding to the payment method
3084 expiration date. For CARD/DCRD customers this is the end of the month;
3085 for others (COMP is the only other payby that uses paydate) it's the start.
3086 Returns 0 if the paydate is empty or set to the far future.
3092 my ($month, $year) = $self->paydate_monthyear;
3093 return 0 if !$year or $year >= 2037;
3094 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3096 if ( $month == 13 ) {
3100 return timelocal(0,0,0,1,$month-1,$year) - 1;
3103 return timelocal(0,0,0,1,$month-1,$year);
3107 =item paydate_epoch_sql
3109 Class method. Returns an SQL expression to obtain the payment expiration date
3110 as a number of seconds.
3114 # Special expiration date behavior for non-CARD/DCRD customers has been
3115 # carefully preserved. Do we really use that?
3116 sub paydate_epoch_sql {
3118 my $table = shift || 'cust_main';
3119 my ($case1, $case2);
3120 if ( driver_name eq 'Pg' ) {
3121 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3122 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3124 elsif ( lc(driver_name) eq 'mysql' ) {
3125 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3126 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3129 return "CASE WHEN $table.payby IN('CARD','DCRD')
3135 =item tax_exemption TAXNAME
3140 my( $self, $taxname ) = @_;
3142 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3143 'taxname' => $taxname,
3148 =item cust_main_exemption
3152 sub cust_main_exemption {
3154 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3157 =item invoicing_list [ ARRAYREF ]
3159 If an arguement is given, sets these email addresses as invoice recipients
3160 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3161 (except as warnings), so use check_invoicing_list first.
3163 Returns a list of email addresses (with svcnum entries expanded).
3165 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3166 check it without disturbing anything by passing nothing.
3168 This interface may change in the future.
3172 sub invoicing_list {
3173 my( $self, $arrayref ) = @_;
3176 my @cust_main_invoice;
3177 if ( $self->custnum ) {
3178 @cust_main_invoice =
3179 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3181 @cust_main_invoice = ();
3183 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3184 #warn $cust_main_invoice->destnum;
3185 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3186 #warn $cust_main_invoice->destnum;
3187 my $error = $cust_main_invoice->delete;
3188 warn $error if $error;
3191 if ( $self->custnum ) {
3192 @cust_main_invoice =
3193 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3195 @cust_main_invoice = ();
3197 my %seen = map { $_->address => 1 } @cust_main_invoice;
3198 foreach my $address ( @{$arrayref} ) {
3199 next if exists $seen{$address} && $seen{$address};
3200 $seen{$address} = 1;
3201 my $cust_main_invoice = new FS::cust_main_invoice ( {
3202 'custnum' => $self->custnum,
3205 my $error = $cust_main_invoice->insert;
3206 warn $error if $error;
3210 if ( $self->custnum ) {
3212 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3219 =item check_invoicing_list ARRAYREF
3221 Checks these arguements as valid input for the invoicing_list method. If there
3222 is an error, returns the error, otherwise returns false.
3226 sub check_invoicing_list {
3227 my( $self, $arrayref ) = @_;
3229 foreach my $address ( @$arrayref ) {
3231 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3232 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3235 my $cust_main_invoice = new FS::cust_main_invoice ( {
3236 'custnum' => $self->custnum,
3239 my $error = $self->custnum
3240 ? $cust_main_invoice->check
3241 : $cust_main_invoice->checkdest
3243 return $error if $error;
3247 return "Email address required"
3248 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3249 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3254 =item set_default_invoicing_list
3256 Sets the invoicing list to all accounts associated with this customer,
3257 overwriting any previous invoicing list.
3261 sub set_default_invoicing_list {
3263 $self->invoicing_list($self->all_emails);
3268 Returns the email addresses of all accounts provisioned for this customer.
3275 foreach my $cust_pkg ( $self->all_pkgs ) {
3276 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3278 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3279 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3281 $list{$_}=1 foreach map { $_->email } @svc_acct;
3286 =item invoicing_list_addpost
3288 Adds postal invoicing to this customer. If this customer is already configured
3289 to receive postal invoices, does nothing.
3293 sub invoicing_list_addpost {
3295 return if grep { $_ eq 'POST' } $self->invoicing_list;
3296 my @invoicing_list = $self->invoicing_list;
3297 push @invoicing_list, 'POST';
3298 $self->invoicing_list(\@invoicing_list);
3301 =item invoicing_list_emailonly
3303 Returns the list of email invoice recipients (invoicing_list without non-email
3304 destinations such as POST and FAX).
3308 sub invoicing_list_emailonly {
3310 warn "$me invoicing_list_emailonly called"
3312 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3315 =item invoicing_list_emailonly_scalar
3317 Returns the list of email invoice recipients (invoicing_list without non-email
3318 destinations such as POST and FAX) as a comma-separated scalar.
3322 sub invoicing_list_emailonly_scalar {
3324 warn "$me invoicing_list_emailonly_scalar called"
3326 join(', ', $self->invoicing_list_emailonly);
3329 =item referral_custnum_cust_main
3331 Returns the customer who referred this customer (or the empty string, if
3332 this customer was not referred).
3334 Note the difference with referral_cust_main method: This method,
3335 referral_custnum_cust_main returns the single customer (if any) who referred
3336 this customer, while referral_cust_main returns an array of customers referred
3341 sub referral_custnum_cust_main {
3343 return '' unless $self->referral_custnum;
3344 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3347 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3349 Returns an array of customers referred by this customer (referral_custnum set
3350 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3351 customers referred by customers referred by this customer and so on, inclusive.
3352 The default behavior is DEPTH 1 (no recursion).
3354 Note the difference with referral_custnum_cust_main method: This method,
3355 referral_cust_main, returns an array of customers referred BY this customer,
3356 while referral_custnum_cust_main returns the single customer (if any) who
3357 referred this customer.
3361 sub referral_cust_main {
3363 my $depth = @_ ? shift : 1;
3364 my $exclude = @_ ? shift : {};
3367 map { $exclude->{$_->custnum}++; $_; }
3368 grep { ! $exclude->{ $_->custnum } }
3369 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3373 map { $_->referral_cust_main($depth-1, $exclude) }
3380 =item referral_cust_main_ncancelled
3382 Same as referral_cust_main, except only returns customers with uncancelled
3387 sub referral_cust_main_ncancelled {
3389 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3392 =item referral_cust_pkg [ DEPTH ]
3394 Like referral_cust_main, except returns a flat list of all unsuspended (and
3395 uncancelled) packages for each customer. The number of items in this list may
3396 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3400 sub referral_cust_pkg {
3402 my $depth = @_ ? shift : 1;
3404 map { $_->unsuspended_pkgs }
3405 grep { $_->unsuspended_pkgs }
3406 $self->referral_cust_main($depth);
3409 =item referring_cust_main
3411 Returns the single cust_main record for the customer who referred this customer
3412 (referral_custnum), or false.
3416 sub referring_cust_main {
3418 return '' unless $self->referral_custnum;
3419 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3422 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3424 Applies a credit to this customer. If there is an error, returns the error,
3425 otherwise returns false.
3427 REASON can be a text string, an FS::reason object, or a scalar reference to
3428 a reasonnum. If a text string, it will be automatically inserted as a new
3429 reason, and a 'reason_type' option must be passed to indicate the
3430 FS::reason_type for the new reason.
3432 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3434 Any other options are passed to FS::cust_credit::insert.
3439 my( $self, $amount, $reason, %options ) = @_;
3441 my $cust_credit = new FS::cust_credit {
3442 'custnum' => $self->custnum,
3443 'amount' => $amount,
3446 if ( ref($reason) ) {
3448 if ( ref($reason) eq 'SCALAR' ) {
3449 $cust_credit->reasonnum( $$reason );
3451 $cust_credit->reasonnum( $reason->reasonnum );
3455 $cust_credit->set('reason', $reason)
3458 for (qw( addlinfo eventnum )) {
3459 $cust_credit->$_( delete $options{$_} )
3460 if exists($options{$_});
3463 $cust_credit->insert(%options);
3467 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3469 Creates a one-time charge for this customer. If there is an error, returns
3470 the error, otherwise returns false.
3472 New-style, with a hashref of options:
3474 my $error = $cust_main->charge(
3478 'start_date' => str2time('7/4/2009'),
3479 'pkg' => 'Description',
3480 'comment' => 'Comment',
3481 'additional' => [], #extra invoice detail
3482 'classnum' => 1, #pkg_class
3484 'setuptax' => '', # or 'Y' for tax exempt
3487 'taxclass' => 'Tax class',
3490 'taxproduct' => 2, #part_pkg_taxproduct
3491 'override' => {}, #XXX describe
3493 #will be filled in with the new object
3494 'cust_pkg_ref' => \$cust_pkg,
3496 #generate an invoice immediately
3498 'invoice_terms' => '', #with these terms
3504 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3510 my ( $amount, $quantity, $start_date, $classnum );
3511 my ( $pkg, $comment, $additional );
3512 my ( $setuptax, $taxclass ); #internal taxes
3513 my ( $taxproduct, $override ); #vendor (CCH) taxes
3515 my $cust_pkg_ref = '';
3516 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3517 if ( ref( $_[0] ) ) {
3518 $amount = $_[0]->{amount};
3519 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3520 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3521 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3522 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3523 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3524 : '$'. sprintf("%.2f",$amount);
3525 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3526 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3527 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3528 $additional = $_[0]->{additional} || [];
3529 $taxproduct = $_[0]->{taxproductnum};
3530 $override = { '' => $_[0]->{tax_override} };
3531 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3532 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3533 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3538 $pkg = @_ ? shift : 'One-time charge';
3539 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3541 $taxclass = @_ ? shift : '';
3545 local $SIG{HUP} = 'IGNORE';
3546 local $SIG{INT} = 'IGNORE';
3547 local $SIG{QUIT} = 'IGNORE';
3548 local $SIG{TERM} = 'IGNORE';
3549 local $SIG{TSTP} = 'IGNORE';
3550 local $SIG{PIPE} = 'IGNORE';
3552 my $oldAutoCommit = $FS::UID::AutoCommit;
3553 local $FS::UID::AutoCommit = 0;
3556 my $part_pkg = new FS::part_pkg ( {
3558 'comment' => $comment,
3562 'classnum' => ( $classnum ? $classnum : '' ),
3563 'setuptax' => $setuptax,
3564 'taxclass' => $taxclass,
3565 'taxproductnum' => $taxproduct,
3568 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3569 ( 0 .. @$additional - 1 )
3571 'additional_count' => scalar(@$additional),
3572 'setup_fee' => $amount,
3575 my $error = $part_pkg->insert( options => \%options,
3576 tax_overrides => $override,
3579 $dbh->rollback if $oldAutoCommit;
3583 my $pkgpart = $part_pkg->pkgpart;
3584 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3585 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3586 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3587 $error = $type_pkgs->insert;
3589 $dbh->rollback if $oldAutoCommit;
3594 my $cust_pkg = new FS::cust_pkg ( {
3595 'custnum' => $self->custnum,
3596 'pkgpart' => $pkgpart,
3597 'quantity' => $quantity,
3598 'start_date' => $start_date,
3599 'no_auto' => $no_auto,
3602 $error = $cust_pkg->insert;
3604 $dbh->rollback if $oldAutoCommit;
3606 } elsif ( $cust_pkg_ref ) {
3607 ${$cust_pkg_ref} = $cust_pkg;
3611 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3612 'pkg_list' => [ $cust_pkg ],
3615 $dbh->rollback if $oldAutoCommit;
3620 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3625 #=item charge_postal_fee
3627 #Applies a one time charge this customer. If there is an error,
3628 #returns the error, returns the cust_pkg charge object or false
3629 #if there was no charge.
3633 # This should be a customer event. For that to work requires that bill
3634 # also be a customer event.
3636 sub charge_postal_fee {
3639 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3640 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3642 my $cust_pkg = new FS::cust_pkg ( {
3643 'custnum' => $self->custnum,
3644 'pkgpart' => $pkgpart,
3648 my $error = $cust_pkg->insert;
3649 $error ? $error : $cust_pkg;
3652 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3654 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3656 Optionally, a list or hashref of additional arguments to the qsearch call can
3663 my $opt = ref($_[0]) ? shift : { @_ };
3665 #return $self->num_cust_bill unless wantarray || keys %$opt;
3667 $opt->{'table'} = 'cust_bill';
3668 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3669 $opt->{'hashref'}{'custnum'} = $self->custnum;
3670 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3672 map { $_ } #behavior of sort undefined in scalar context
3673 sort { $a->_date <=> $b->_date }
3677 =item open_cust_bill
3679 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3684 sub open_cust_bill {
3688 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3694 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3696 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3700 sub legacy_cust_bill {
3703 #return $self->num_legacy_cust_bill unless wantarray;
3705 map { $_ } #behavior of sort undefined in scalar context
3706 sort { $a->_date <=> $b->_date }
3707 qsearch({ 'table' => 'legacy_cust_bill',
3708 'hashref' => { 'custnum' => $self->custnum, },
3709 'order_by' => 'ORDER BY _date ASC',
3713 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3715 Returns all the statements (see L<FS::cust_statement>) for this customer.
3717 Optionally, a list or hashref of additional arguments to the qsearch call can
3722 sub cust_statement {
3724 my $opt = ref($_[0]) ? shift : { @_ };
3726 #return $self->num_cust_statement unless wantarray || keys %$opt;
3728 $opt->{'table'} = 'cust_statement';
3729 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3730 $opt->{'hashref'}{'custnum'} = $self->custnum;
3731 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3733 map { $_ } #behavior of sort undefined in scalar context
3734 sort { $a->_date <=> $b->_date }
3740 Returns all the credits (see L<FS::cust_credit>) for this customer.
3746 map { $_ } #return $self->num_cust_credit unless wantarray;
3747 sort { $a->_date <=> $b->_date }
3748 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3751 =item cust_credit_pkgnum
3753 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3754 package when using experimental package balances.
3758 sub cust_credit_pkgnum {
3759 my( $self, $pkgnum ) = @_;
3760 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3761 sort { $a->_date <=> $b->_date }
3762 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3763 'pkgnum' => $pkgnum,
3770 Returns all the payments (see L<FS::cust_pay>) for this customer.
3776 return $self->num_cust_pay unless wantarray;
3777 sort { $a->_date <=> $b->_date }
3778 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3783 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3784 called automatically when the cust_pay method is used in a scalar context.
3790 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3791 my $sth = dbh->prepare($sql) or die dbh->errstr;
3792 $sth->execute($self->custnum) or die $sth->errstr;
3793 $sth->fetchrow_arrayref->[0];
3796 =item cust_pay_pkgnum
3798 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3799 package when using experimental package balances.
3803 sub cust_pay_pkgnum {
3804 my( $self, $pkgnum ) = @_;
3805 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3806 sort { $a->_date <=> $b->_date }
3807 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3808 'pkgnum' => $pkgnum,
3815 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3821 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3822 sort { $a->_date <=> $b->_date }
3823 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3826 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3828 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3830 Optionally, a list or hashref of additional arguments to the qsearch call can
3835 sub cust_pay_batch {
3837 my $opt = ref($_[0]) ? shift : { @_ };
3839 #return $self->num_cust_statement unless wantarray || keys %$opt;
3841 $opt->{'table'} = 'cust_pay_batch';
3842 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3843 $opt->{'hashref'}{'custnum'} = $self->custnum;
3844 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3846 map { $_ } #behavior of sort undefined in scalar context
3847 sort { $a->paybatchnum <=> $b->paybatchnum }
3851 =item cust_pay_pending
3853 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3854 (without status "done").
3858 sub cust_pay_pending {
3860 return $self->num_cust_pay_pending unless wantarray;
3861 sort { $a->_date <=> $b->_date }
3862 qsearch( 'cust_pay_pending', {
3863 'custnum' => $self->custnum,
3864 'status' => { op=>'!=', value=>'done' },
3869 =item cust_pay_pending_attempt
3871 Returns all payment attempts / declined payments for this customer, as pending
3872 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3873 a corresponding payment (see L<FS::cust_pay>).
3877 sub cust_pay_pending_attempt {
3879 return $self->num_cust_pay_pending_attempt unless wantarray;
3880 sort { $a->_date <=> $b->_date }
3881 qsearch( 'cust_pay_pending', {
3882 'custnum' => $self->custnum,
3889 =item num_cust_pay_pending
3891 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3892 customer (without status "done"). Also called automatically when the
3893 cust_pay_pending method is used in a scalar context.
3897 sub num_cust_pay_pending {
3900 " SELECT COUNT(*) FROM cust_pay_pending ".
3901 " WHERE custnum = ? AND status != 'done' ",
3906 =item num_cust_pay_pending_attempt
3908 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3909 customer, with status "done" but without a corresp. Also called automatically when the
3910 cust_pay_pending method is used in a scalar context.
3914 sub num_cust_pay_pending_attempt {
3917 " SELECT COUNT(*) FROM cust_pay_pending ".
3918 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3925 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3931 map { $_ } #return $self->num_cust_refund unless wantarray;
3932 sort { $a->_date <=> $b->_date }
3933 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3936 =item display_custnum
3938 Returns the displayed customer number for this customer: agent_custid if
3939 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3943 sub display_custnum {
3946 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3947 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3948 if ( $special eq 'CoStAg' ) {
3949 $prefix = uc( join('',
3951 ($self->state =~ /^(..)/),
3952 $prefix || ($self->agent->agent =~ /^(..)/)
3955 elsif ( $special eq 'CoStCl' ) {
3956 $prefix = uc( join('',
3958 ($self->state =~ /^(..)/),
3959 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3962 # add any others here if needed
3965 my $length = $conf->config('cust_main-custnum-display_length');
3966 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3967 return $self->agent_custid;
3968 } elsif ( $prefix ) {
3969 $length = 8 if !defined($length);
3971 sprintf('%0'.$length.'d', $self->custnum)
3972 } elsif ( $length ) {
3973 return sprintf('%0'.$length.'d', $self->custnum);
3975 return $self->custnum;
3981 Returns a name string for this customer, either "Company (Last, First)" or
3988 my $name = $self->contact;
3989 $name = $self->company. " ($name)" if $self->company;
3995 Returns a name string for this (service/shipping) contact, either
3996 "Company (Last, First)" or "Last, First".
4002 if ( $self->get('ship_last') ) {
4003 my $name = $self->ship_contact;
4004 $name = $self->ship_company. " ($name)" if $self->ship_company;
4013 Returns a name string for this customer, either "Company" or "First Last".
4019 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4022 =item ship_name_short
4024 Returns a name string for this (service/shipping) contact, either "Company"
4029 sub ship_name_short {
4031 if ( $self->get('ship_last') ) {
4032 $self->ship_company !~ /^\s*$/
4033 ? $self->ship_company
4034 : $self->ship_contact_firstlast;
4036 $self->name_company_or_firstlast;
4042 Returns this customer's full (billing) contact name only, "Last, First"
4048 $self->get('last'). ', '. $self->first;
4053 Returns this customer's full (shipping) contact name only, "Last, First"
4059 $self->get('ship_last')
4060 ? $self->get('ship_last'). ', '. $self->ship_first
4064 =item contact_firstlast
4066 Returns this customers full (billing) contact name only, "First Last".
4070 sub contact_firstlast {
4072 $self->first. ' '. $self->get('last');
4075 =item ship_contact_firstlast
4077 Returns this customer's full (shipping) contact name only, "First Last".
4081 sub ship_contact_firstlast {
4083 $self->get('ship_last')
4084 ? $self->first. ' '. $self->get('ship_last')
4085 : $self->contact_firstlast;
4090 Returns this customer's full country name
4096 code2country($self->country);
4099 =item geocode DATA_VENDOR
4101 Returns a value for the customer location as encoded by DATA_VENDOR.
4102 Currently this only makes sense for "CCH" as DATA_VENDOR.
4110 Returns a status string for this customer, currently:
4114 =item prospect - No packages have ever been ordered
4116 =item ordered - Recurring packages all are new (not yet billed).
4118 =item active - One or more recurring packages is active
4120 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4122 =item suspended - All non-cancelled recurring packages are suspended
4124 =item cancelled - All recurring packages are cancelled
4128 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4129 cust_main-status_module configuration option.
4133 sub status { shift->cust_status(@_); }
4137 for my $status ( FS::cust_main->statuses() ) {
4138 my $method = $status.'_sql';
4139 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4140 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4141 $sth->execute( ($self->custnum) x $numnum )
4142 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4143 return $status if $sth->fetchrow_arrayref->[0];
4147 =item ucfirst_cust_status
4149 =item ucfirst_status
4151 Returns the status with the first character capitalized.
4155 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4157 sub ucfirst_cust_status {
4159 ucfirst($self->cust_status);
4164 Returns a hex triplet color string for this customer's status.
4168 sub statuscolor { shift->cust_statuscolor(@_); }
4170 sub cust_statuscolor {
4172 __PACKAGE__->statuscolors->{$self->cust_status};
4177 Returns an array of hashes representing the customer's RT tickets.
4184 my $num = $conf->config('cust_main-max_tickets') || 10;
4187 if ( $conf->config('ticket_system') ) {
4188 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4190 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4194 foreach my $priority (
4195 $conf->config('ticket_system-custom_priority_field-values'), ''
4197 last if scalar(@tickets) >= $num;
4199 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4200 $num - scalar(@tickets),
4210 # Return services representing svc_accts in customer support packages
4211 sub support_services {
4213 my %packages = map { $_ => 1 } $conf->config('support_packages');
4215 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4216 grep { $_->part_svc->svcdb eq 'svc_acct' }
4217 map { $_->cust_svc }
4218 grep { exists $packages{ $_->pkgpart } }
4219 $self->ncancelled_pkgs;
4223 # Return a list of latitude/longitude for one of the services (if any)
4224 sub service_coordinates {
4228 grep { $_->latitude && $_->longitude }
4230 map { $_->cust_svc }
4231 $self->ncancelled_pkgs;
4233 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4238 Returns a masked version of the named field
4243 my ($self,$field) = @_;
4247 'x'x(length($self->getfield($field))-4).
4248 substr($self->getfield($field), (length($self->getfield($field))-4));
4254 =head1 CLASS METHODS
4260 Class method that returns the list of possible status strings for customers
4261 (see L<the status method|/status>). For example:
4263 @statuses = FS::cust_main->statuses();
4269 keys %{ $self->statuscolors };
4272 =item cust_status_sql
4274 Returns an SQL fragment to determine the status of a cust_main record, as a
4279 sub cust_status_sql {
4281 for my $status ( FS::cust_main->statuses() ) {
4282 my $method = $status.'_sql';
4283 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4292 Returns an SQL expression identifying prospective cust_main records (customers
4293 with no packages ever ordered)
4297 use vars qw($select_count_pkgs);
4298 $select_count_pkgs =
4299 "SELECT COUNT(*) FROM cust_pkg
4300 WHERE cust_pkg.custnum = cust_main.custnum";
4302 sub select_count_pkgs_sql {
4307 " 0 = ( $select_count_pkgs ) ";
4312 Returns an SQL expression identifying ordered cust_main records (customers with
4313 no active packages, but recurring packages not yet setup or one time charges
4319 FS::cust_main->none_active_sql.
4320 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4325 Returns an SQL expression identifying active cust_main records (customers with
4326 active recurring packages).
4331 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4334 =item none_active_sql
4336 Returns an SQL expression identifying cust_main records with no active
4337 recurring packages. This includes customers of status prospect, ordered,
4338 inactive, and suspended.
4342 sub none_active_sql {
4343 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4348 Returns an SQL expression identifying inactive cust_main records (customers with
4349 no active recurring packages, but otherwise unsuspended/uncancelled).
4354 FS::cust_main->none_active_sql.
4355 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4361 Returns an SQL expression identifying suspended cust_main records.
4366 sub suspended_sql { susp_sql(@_); }
4368 FS::cust_main->none_active_sql.
4369 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4375 Returns an SQL expression identifying cancelled cust_main records.
4379 sub cancel_sql { shift->cancelled_sql(@_); }
4382 =item uncancelled_sql
4384 Returns an SQL expression identifying un-cancelled cust_main records.
4388 sub uncancelled_sql { uncancel_sql(@_); }
4389 sub uncancel_sql { "
4390 ( 0 < ( $select_count_pkgs
4391 AND ( cust_pkg.cancel IS NULL
4392 OR cust_pkg.cancel = 0
4395 OR 0 = ( $select_count_pkgs )
4401 Returns an SQL fragment to retreive the balance.
4406 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4407 WHERE cust_bill.custnum = cust_main.custnum )
4408 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4409 WHERE cust_pay.custnum = cust_main.custnum )
4410 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4411 WHERE cust_credit.custnum = cust_main.custnum )
4412 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4413 WHERE cust_refund.custnum = cust_main.custnum )
4416 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4418 Returns an SQL fragment to retreive the balance for this customer, optionally
4419 considering invoices with date earlier than START_TIME, and not
4420 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4421 total_unapplied_payments).
4423 Times are specified as SQL fragments or numeric
4424 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4425 L<Date::Parse> for conversion functions. The empty string can be passed
4426 to disable that time constraint completely.
4428 Available options are:
4432 =item unapplied_date
4434 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)
4439 set to true to remove all customer comparison clauses, for totals
4444 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4449 JOIN clause (typically used with the total option)
4453 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4454 time will be ignored. Note that START_TIME and END_TIME only limit the date
4455 range for invoices and I<unapplied> payments, credits, and refunds.
4461 sub balance_date_sql {
4462 my( $class, $start, $end, %opt ) = @_;
4464 my $cutoff = $opt{'cutoff'};
4466 my $owed = FS::cust_bill->owed_sql($cutoff);
4467 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4468 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4469 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4471 my $j = $opt{'join'} || '';
4473 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4474 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4475 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4476 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4478 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4479 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4480 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4481 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4486 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4488 Returns an SQL fragment to retreive the total unapplied payments for this
4489 customer, only considering payments with date earlier than START_TIME, and
4490 optionally not later than END_TIME.
4492 Times are specified as SQL fragments or numeric
4493 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4494 L<Date::Parse> for conversion functions. The empty string can be passed
4495 to disable that time constraint completely.
4497 Available options are:
4501 sub unapplied_payments_date_sql {
4502 my( $class, $start, $end, %opt ) = @_;
4504 my $cutoff = $opt{'cutoff'};
4506 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4508 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4509 'unapplied_date'=>1 );
4511 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4514 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4516 Helper method for balance_date_sql; name (and usage) subject to change
4517 (suggestions welcome).
4519 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4520 cust_refund, cust_credit or cust_pay).
4522 If TABLE is "cust_bill" or the unapplied_date option is true, only
4523 considers records with date earlier than START_TIME, and optionally not
4524 later than END_TIME .
4528 sub _money_table_where {
4529 my( $class, $table, $start, $end, %opt ) = @_;
4532 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4533 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4534 push @where, "$table._date <= $start" if defined($start) && length($start);
4535 push @where, "$table._date > $end" if defined($end) && length($end);
4537 push @where, @{$opt{'where'}} if $opt{'where'};
4538 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4544 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4545 use FS::cust_main::Search;
4548 FS::cust_main::Search->search(@_);
4563 #warn join('-',keys %$param);
4564 my $fh = $param->{filehandle};
4565 my $agentnum = $param->{agentnum};
4566 my $format = $param->{format};
4568 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4571 if ( $format eq 'simple' ) {
4572 @fields = qw( custnum agent_custid amount pkg );
4574 die "unknown format $format";
4577 eval "use Text::CSV_XS;";
4580 my $csv = new Text::CSV_XS;
4587 local $SIG{HUP} = 'IGNORE';
4588 local $SIG{INT} = 'IGNORE';
4589 local $SIG{QUIT} = 'IGNORE';
4590 local $SIG{TERM} = 'IGNORE';
4591 local $SIG{TSTP} = 'IGNORE';
4592 local $SIG{PIPE} = 'IGNORE';
4594 my $oldAutoCommit = $FS::UID::AutoCommit;
4595 local $FS::UID::AutoCommit = 0;
4598 #while ( $columns = $csv->getline($fh) ) {
4600 while ( defined($line=<$fh>) ) {
4602 $csv->parse($line) or do {
4603 $dbh->rollback if $oldAutoCommit;
4604 return "can't parse: ". $csv->error_input();
4607 my @columns = $csv->fields();
4608 #warn join('-',@columns);
4611 foreach my $field ( @fields ) {
4612 $row{$field} = shift @columns;
4615 if ( $row{custnum} && $row{agent_custid} ) {
4616 dbh->rollback if $oldAutoCommit;
4617 return "can't specify custnum with agent_custid $row{agent_custid}";
4621 if ( $row{agent_custid} && $agentnum ) {
4622 %hash = ( 'agent_custid' => $row{agent_custid},
4623 'agentnum' => $agentnum,
4627 if ( $row{custnum} ) {
4628 %hash = ( 'custnum' => $row{custnum} );
4631 unless ( scalar(keys %hash) ) {
4632 $dbh->rollback if $oldAutoCommit;
4633 return "can't find customer without custnum or agent_custid and agentnum";
4636 my $cust_main = qsearchs('cust_main', { %hash } );
4637 unless ( $cust_main ) {
4638 $dbh->rollback if $oldAutoCommit;
4639 my $custnum = $row{custnum} || $row{agent_custid};
4640 return "unknown custnum $custnum";
4643 if ( $row{'amount'} > 0 ) {
4644 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4646 $dbh->rollback if $oldAutoCommit;
4650 } elsif ( $row{'amount'} < 0 ) {
4651 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4654 $dbh->rollback if $oldAutoCommit;
4664 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4666 return "Empty file!" unless $imported;
4672 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4674 Deprecated. Use event notification and message templates
4675 (L<FS::msg_template>) instead.
4677 Sends a templated email notification to the customer (see L<Text::Template>).
4679 OPTIONS is a hash and may include
4681 I<from> - the email sender (default is invoice_from)
4683 I<to> - comma-separated scalar or arrayref of recipients
4684 (default is invoicing_list)
4686 I<subject> - The subject line of the sent email notification
4687 (default is "Notice from company_name")
4689 I<extra_fields> - a hashref of name/value pairs which will be substituted
4692 The following variables are vavailable in the template.
4694 I<$first> - the customer first name
4695 I<$last> - the customer last name
4696 I<$company> - the customer company
4697 I<$payby> - a description of the method of payment for the customer
4698 # would be nice to use FS::payby::shortname
4699 I<$payinfo> - the account information used to collect for this customer
4700 I<$expdate> - the expiration of the customer payment in seconds from epoch
4705 my ($self, $template, %options) = @_;
4707 return unless $conf->exists($template);
4709 my $from = $conf->config('invoice_from', $self->agentnum)
4710 if $conf->exists('invoice_from', $self->agentnum);
4711 $from = $options{from} if exists($options{from});
4713 my $to = join(',', $self->invoicing_list_emailonly);
4714 $to = $options{to} if exists($options{to});
4716 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4717 if $conf->exists('company_name', $self->agentnum);
4718 $subject = $options{subject} if exists($options{subject});
4720 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4721 SOURCE => [ map "$_\n",
4722 $conf->config($template)]
4724 or die "can't create new Text::Template object: Text::Template::ERROR";
4725 $notify_template->compile()
4726 or die "can't compile template: Text::Template::ERROR";
4728 $FS::notify_template::_template::company_name =
4729 $conf->config('company_name', $self->agentnum);
4730 $FS::notify_template::_template::company_address =
4731 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4733 my $paydate = $self->paydate || '2037-12-31';
4734 $FS::notify_template::_template::first = $self->first;
4735 $FS::notify_template::_template::last = $self->last;
4736 $FS::notify_template::_template::company = $self->company;
4737 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4738 my $payby = $self->payby;
4739 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4740 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4742 #credit cards expire at the end of the month/year of their exp date
4743 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4744 $FS::notify_template::_template::payby = 'credit card';
4745 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4746 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4748 }elsif ($payby eq 'COMP') {
4749 $FS::notify_template::_template::payby = 'complimentary account';
4751 $FS::notify_template::_template::payby = 'current method';
4753 $FS::notify_template::_template::expdate = $expire_time;
4755 for (keys %{$options{extra_fields}}){
4757 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4760 send_email(from => $from,
4762 subject => $subject,
4763 body => $notify_template->fill_in( PACKAGE =>
4764 'FS::notify_template::_template' ),
4769 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4771 Generates a templated notification to the customer (see L<Text::Template>).
4773 OPTIONS is a hash and may include
4775 I<extra_fields> - a hashref of name/value pairs which will be substituted
4776 into the template. These values may override values mentioned below
4777 and those from the customer record.
4779 The following variables are available in the template instead of or in addition
4780 to the fields of the customer record.
4782 I<$payby> - a description of the method of payment for the customer
4783 # would be nice to use FS::payby::shortname
4784 I<$payinfo> - the masked account information used to collect for this customer
4785 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4786 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4790 # a lot like cust_bill::print_latex
4791 sub generate_letter {
4792 my ($self, $template, %options) = @_;
4794 return unless $conf->exists($template);
4796 my $letter_template = new Text::Template
4798 SOURCE => [ map "$_\n", $conf->config($template)],
4799 DELIMITERS => [ '[@--', '--@]' ],
4801 or die "can't create new Text::Template object: Text::Template::ERROR";
4803 $letter_template->compile()
4804 or die "can't compile template: Text::Template::ERROR";
4806 my %letter_data = map { $_ => $self->$_ } $self->fields;
4807 $letter_data{payinfo} = $self->mask_payinfo;
4809 #my $paydate = $self->paydate || '2037-12-31';
4810 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4812 my $payby = $self->payby;
4813 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4814 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4816 #credit cards expire at the end of the month/year of their exp date
4817 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4818 $letter_data{payby} = 'credit card';
4819 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4820 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4822 }elsif ($payby eq 'COMP') {
4823 $letter_data{payby} = 'complimentary account';
4825 $letter_data{payby} = 'current method';
4827 $letter_data{expdate} = $expire_time;
4829 for (keys %{$options{extra_fields}}){
4830 $letter_data{$_} = $options{extra_fields}->{$_};
4833 unless(exists($letter_data{returnaddress})){
4834 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4835 $self->agent_template)
4837 if ( length($retadd) ) {
4838 $letter_data{returnaddress} = $retadd;
4839 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4840 $letter_data{returnaddress} =
4841 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4845 ( $conf->config('company_name', $self->agentnum),
4846 $conf->config('company_address', $self->agentnum),
4850 $letter_data{returnaddress} = '~';
4854 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4856 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4858 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4860 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4864 ) or die "can't open temp file: $!\n";
4865 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4866 or die "can't write temp file: $!\n";
4868 $letter_data{'logo_file'} = $lh->filename;
4870 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4874 ) or die "can't open temp file: $!\n";
4876 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4878 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4879 return ($1, $letter_data{'logo_file'});
4883 =item print_ps TEMPLATE
4885 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4891 my($file, $lfile) = $self->generate_letter(@_);
4892 my $ps = FS::Misc::generate_ps($file);
4893 unlink($file.'.tex');
4899 =item print TEMPLATE
4901 Prints the filled in template.
4903 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4907 sub queueable_print {
4910 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4911 or die "invalid customer number: " . $opt{custvnum};
4913 my $error = $self->print( $opt{template} );
4914 die $error if $error;
4918 my ($self, $template) = (shift, shift);
4919 do_print [ $self->print_ps($template) ];
4922 #these three subs should just go away once agent stuff is all config overrides
4924 sub agent_template {
4926 $self->_agent_plandata('agent_templatename');
4929 sub agent_invoice_from {
4931 $self->_agent_plandata('agent_invoice_from');
4934 sub _agent_plandata {
4935 my( $self, $option ) = @_;
4937 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4938 #agent-specific Conf
4940 use FS::part_event::Condition;
4942 my $agentnum = $self->agentnum;
4944 my $regexp = regexp_sql();
4946 my $part_event_option =
4948 'select' => 'part_event_option.*',
4949 'table' => 'part_event_option',
4951 LEFT JOIN part_event USING ( eventpart )
4952 LEFT JOIN part_event_option AS peo_agentnum
4953 ON ( part_event.eventpart = peo_agentnum.eventpart
4954 AND peo_agentnum.optionname = 'agentnum'
4955 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4957 LEFT JOIN part_event_condition
4958 ON ( part_event.eventpart = part_event_condition.eventpart
4959 AND part_event_condition.conditionname = 'cust_bill_age'
4961 LEFT JOIN part_event_condition_option
4962 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4963 AND part_event_condition_option.optionname = 'age'
4966 #'hashref' => { 'optionname' => $option },
4967 #'hashref' => { 'part_event_option.optionname' => $option },
4969 " WHERE part_event_option.optionname = ". dbh->quote($option).
4970 " AND action = 'cust_bill_send_agent' ".
4971 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4972 " AND peo_agentnum.optionname = 'agentnum' ".
4973 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4975 CASE WHEN part_event_condition_option.optionname IS NULL
4977 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4979 , part_event.weight".
4983 unless ( $part_event_option ) {
4984 return $self->agent->invoice_template || ''
4985 if $option eq 'agent_templatename';
4989 $part_event_option->optionvalue;
4993 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4995 Subroutine (not a method), designed to be called from the queue.
4997 Takes a list of options and values.
4999 Pulls up the customer record via the custnum option and calls bill_and_collect.
5004 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5006 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5007 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5009 $cust_main->bill_and_collect( %args );
5012 sub process_bill_and_collect {
5014 my $param = thaw(decode_base64(shift));
5015 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5016 or die "custnum '$param->{custnum}' not found!\n";
5017 $param->{'job'} = $job;
5018 $param->{'fatal'} = 1; # runs from job queue, will be caught
5019 $param->{'retry'} = 1;
5021 $cust_main->bill_and_collect( %$param );
5024 =item process_censustract_update CUSTNUM
5026 Queueable function to update the census tract to the current year (as set in
5027 the 'census_year' configuration variable) and retrieve the new tract code.
5031 sub process_censustract_update {
5032 eval "use FS::Misc::Geo qw(get_censustract)";
5034 my $custnum = shift;
5035 my $cust_main = qsearchs( 'cust_main', { custnum => $custnum })
5036 or die "custnum '$custnum' not found!\n";
5038 my $new_year = $conf->config('census_year') or return;
5039 my $new_tract = get_censustract({ $cust_main->location_hash }, $new_year);
5040 if ( $new_tract =~ /^\d/ ) {
5041 # then it's a tract code
5042 $cust_main->set('censustract', $new_tract);
5043 $cust_main->set('censusyear', $new_year);
5045 local($ignore_expired_card) = 1;
5046 local($ignore_illegal_zip) = 1;
5047 local($ignore_banned_card) = 1;
5048 local($skip_fuzzyfiles) = 1;
5049 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5050 my $error = $cust_main->replace;
5051 die $error if $error;
5054 # it's an error message
5060 sub _upgrade_data { #class method
5061 my ($class, %opts) = @_;
5064 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5067 #this seems to be the only expensive one.. why does it take so long?
5068 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5070 'UPDATE cust_main SET signupdate = (SELECT signupdate FROM h_cust_main WHERE signupdate IS NOT NULL AND h_cust_main.custnum = cust_main.custnum ORDER BY historynum DESC LIMIT 1) WHERE signupdate IS NULL';
5071 FS::upgrade_journal->set_done('cust_main__signupdate');
5074 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5076 # fix yyyy-m-dd formatted paydates
5077 if ( driver_name =~ /^mysql/i ) {
5079 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5080 } else { # the SQL standard
5082 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5084 FS::upgrade_journal->set_done('cust_main__paydate');
5087 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5089 push @statements, #fix the weird BILL with a cc# in payinfo problem
5091 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5093 FS::upgrade_journal->set_done('cust_main__payinfo');
5098 foreach my $sql ( @statements ) {
5099 my $sth = dbh->prepare($sql) or die dbh->errstr;
5100 $sth->execute or die $sth->errstr;
5101 #warn ( (time - $t). " seconds\n" );
5105 local($ignore_expired_card) = 1;
5106 local($ignore_illegal_zip) = 1;
5107 local($ignore_banned_card) = 1;
5108 local($skip_fuzzyfiles) = 1;
5109 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5110 $class->_upgrade_otaker(%opts);
5120 The delete method should possibly take an FS::cust_main object reference
5121 instead of a scalar customer number.
5123 Bill and collect options should probably be passed as references instead of a
5126 There should probably be a configuration file with a list of allowed credit
5129 No multiple currency support (probably a larger project than just this module).
5131 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5133 Birthdates rely on negative epoch values.
5135 The payby for card/check batches is broken. With mixed batching, bad
5138 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5142 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5143 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5144 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.