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;
74 # 1 is mostly method/subroutine entry and options
75 # 2 traces progress of some operations
76 # 3 is even more information including possibly sensitive data
78 $me = '[FS::cust_main]';
81 $ignore_expired_card = 0;
82 $ignore_illegal_zip = 0;
83 $ignore_banned_card = 0;
87 @encrypted_fields = ('payinfo', 'paycvv');
88 sub nohistory_fields { ('payinfo', 'paycvv'); }
90 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
92 #ask FS::UID to run this stuff for us later
93 #$FS::UID::callback{'FS::cust_main'} = sub {
94 install_callback FS::UID sub {
96 #yes, need it for stuff below (prolly should be cached)
101 my ( $hashref, $cache ) = @_;
102 if ( exists $hashref->{'pkgnum'} ) {
103 #@{ $self->{'_pkgnum'} } = ();
104 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
105 $self->{'_pkgnum'} = $subcache;
106 #push @{ $self->{'_pkgnum'} },
107 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
113 FS::cust_main - Object methods for cust_main records
119 $record = new FS::cust_main \%hash;
120 $record = new FS::cust_main { 'column' => 'value' };
122 $error = $record->insert;
124 $error = $new_record->replace($old_record);
126 $error = $record->delete;
128 $error = $record->check;
130 @cust_pkg = $record->all_pkgs;
132 @cust_pkg = $record->ncancelled_pkgs;
134 @cust_pkg = $record->suspended_pkgs;
136 $error = $record->bill;
137 $error = $record->bill %options;
138 $error = $record->bill 'time' => $time;
140 $error = $record->collect;
141 $error = $record->collect %options;
142 $error = $record->collect 'invoice_time' => $time,
147 An FS::cust_main object represents a customer. FS::cust_main inherits from
148 FS::Record. The following fields are currently supported:
154 Primary key (assigned automatically for new customers)
158 Agent (see L<FS::agent>)
162 Advertising source (see L<FS::part_referral>)
174 Cocial security number (optional)
190 (optional, see L<FS::cust_main_county>)
194 (see L<FS::cust_main_county>)
200 (see L<FS::cust_main_county>)
240 (optional, see L<FS::cust_main_county>)
244 (see L<FS::cust_main_county>)
250 (see L<FS::cust_main_county>)
270 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
274 Payment Information (See L<FS::payinfo_Mixin> for data format)
278 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
282 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
286 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
290 Start date month (maestro/solo cards only)
294 Start date year (maestro/solo cards only)
298 Issue number (maestro/solo cards only)
302 Name on card or billing name
306 IP address from which payment information was received
310 Tax exempt, empty or `Y'
314 Order taker (see L<FS::access_user>)
320 =item referral_custnum
322 Referring customer number
326 Enable individual CDR spooling, empty or `Y'
330 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
334 Discourage individual CDR printing, empty or `Y'
338 Allow self-service editing of ticket subjects, empty or 'Y'
340 =item calling_list_exempt
342 Do not call, empty or 'Y'
352 Creates a new customer. To add the customer to the database, see L<"insert">.
354 Note that this stores the hash reference, not a distinct copy of the hash it
355 points to. You can ask the object for a copy with the I<hash> method.
359 sub table { 'cust_main'; }
361 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
363 Adds this customer to the database. If there is an error, returns the error,
364 otherwise returns false.
366 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
367 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
368 are inserted atomicly, or the transaction is rolled back. Passing an empty
369 hash reference is equivalent to not supplying this parameter. There should be
370 a better explanation of this, but until then, here's an example:
373 tie %hash, 'Tie::RefHash'; #this part is important
375 $cust_pkg => [ $svc_acct ],
378 $cust_main->insert( \%hash );
380 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
381 be set as the invoicing list (see L<"invoicing_list">). Errors return as
382 expected and rollback the entire transaction; it is not necessary to call
383 check_invoicing_list first. The invoicing_list is set after the records in the
384 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
385 invoicing_list destination to the newly-created svc_acct. Here's an example:
387 $cust_main->insert( {}, [ $email, 'POST' ] );
389 Currently available options are: I<depend_jobnum>, I<noexport>,
390 I<tax_exemption> and I<prospectnum>.
392 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
393 on the supplied jobnum (they will not run until the specific job completes).
394 This can be used to defer provisioning until some action completes (such
395 as running the customer's credit card successfully).
397 The I<noexport> option is deprecated. If I<noexport> is set true, no
398 provisioning jobs (exports) are scheduled. (You can schedule them later with
399 the B<reexport> method.)
401 The I<tax_exemption> option can be set to an arrayref of tax names.
402 FS::cust_main_exemption records will be created and inserted.
404 If I<prospectnum> is set, moves contacts and locations from that prospect.
410 my $cust_pkgs = @_ ? shift : {};
411 my $invoicing_list = @_ ? shift : '';
413 warn "$me insert called with options ".
414 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
417 local $SIG{HUP} = 'IGNORE';
418 local $SIG{INT} = 'IGNORE';
419 local $SIG{QUIT} = 'IGNORE';
420 local $SIG{TERM} = 'IGNORE';
421 local $SIG{TSTP} = 'IGNORE';
422 local $SIG{PIPE} = 'IGNORE';
424 my $oldAutoCommit = $FS::UID::AutoCommit;
425 local $FS::UID::AutoCommit = 0;
428 my $prepay_identifier = '';
429 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
431 if ( $self->payby eq 'PREPAY' ) {
433 $self->payby('BILL');
434 $prepay_identifier = $self->payinfo;
437 warn " looking up prepaid card $prepay_identifier\n"
440 my $error = $self->get_prepay( $prepay_identifier,
441 'amount_ref' => \$amount,
442 'seconds_ref' => \$seconds,
443 'upbytes_ref' => \$upbytes,
444 'downbytes_ref' => \$downbytes,
445 'totalbytes_ref' => \$totalbytes,
448 $dbh->rollback if $oldAutoCommit;
449 #return "error applying prepaid card (transaction rolled back): $error";
453 $payby = 'PREP' if $amount;
455 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
458 $self->payby('BILL');
459 $amount = $self->paid;
463 warn " inserting $self\n"
466 $self->signupdate(time) unless $self->signupdate;
468 $self->censusyear($conf->config('census_year')||'2012') if $self->censustract;
470 $self->auto_agent_custid()
471 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
473 my $error = $self->SUPER::insert;
475 $dbh->rollback if $oldAutoCommit;
476 #return "inserting cust_main record (transaction rolled back): $error";
480 warn " setting invoicing list\n"
483 if ( $invoicing_list ) {
484 $error = $self->check_invoicing_list( $invoicing_list );
486 $dbh->rollback if $oldAutoCommit;
487 #return "checking invoicing_list (transaction rolled back): $error";
490 $self->invoicing_list( $invoicing_list );
493 warn " setting customer tags\n"
496 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
497 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
498 'custnum' => $self->custnum };
499 my $error = $cust_tag->insert;
501 $dbh->rollback if $oldAutoCommit;
506 my $prospectnum = delete $options{'prospectnum'};
507 if ( $prospectnum ) {
509 warn " moving contacts and locations from prospect $prospectnum\n"
513 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
514 unless ( $prospect_main ) {
515 $dbh->rollback if $oldAutoCommit;
516 return "Unknown prospectnum $prospectnum";
518 $prospect_main->custnum($self->custnum);
519 $prospect_main->disabled('Y');
520 my $error = $prospect_main->replace;
522 $dbh->rollback if $oldAutoCommit;
526 my @contact = $prospect_main->contact;
527 my @cust_location = $prospect_main->cust_location;
528 my @qual = $prospect_main->qual;
530 foreach my $r ( @contact, @cust_location, @qual ) {
532 $r->custnum($self->custnum);
533 my $error = $r->replace;
535 $dbh->rollback if $oldAutoCommit;
542 warn " setting cust_main_exemption\n"
545 my $tax_exemption = delete $options{'tax_exemption'};
546 if ( $tax_exemption ) {
547 foreach my $taxname ( @$tax_exemption ) {
548 my $cust_main_exemption = new FS::cust_main_exemption {
549 'custnum' => $self->custnum,
550 'taxname' => $taxname,
552 my $error = $cust_main_exemption->insert;
554 $dbh->rollback if $oldAutoCommit;
555 return "inserting cust_main_exemption (transaction rolled back): $error";
560 if ( $self->can('start_copy_skel') ) {
561 my $error = $self->start_copy_skel;
563 $dbh->rollback if $oldAutoCommit;
568 warn " ordering packages\n"
571 $error = $self->order_pkgs( $cust_pkgs,
573 'seconds_ref' => \$seconds,
574 'upbytes_ref' => \$upbytes,
575 'downbytes_ref' => \$downbytes,
576 'totalbytes_ref' => \$totalbytes,
579 $dbh->rollback if $oldAutoCommit;
584 $dbh->rollback if $oldAutoCommit;
585 return "No svc_acct record to apply pre-paid time";
587 if ( $upbytes || $downbytes || $totalbytes ) {
588 $dbh->rollback if $oldAutoCommit;
589 return "No svc_acct record to apply pre-paid data";
593 warn " inserting initial $payby payment of $amount\n"
595 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
597 $dbh->rollback if $oldAutoCommit;
598 return "inserting payment (transaction rolled back): $error";
602 unless ( $import || $skip_fuzzyfiles ) {
603 warn " queueing fuzzyfiles update\n"
605 $error = $self->queue_fuzzyfiles_update;
607 $dbh->rollback if $oldAutoCommit;
608 return "updating fuzzy search cache: $error";
612 # FS::geocode_Mixin::after_insert or something?
613 if ( $conf->config('tax_district_method') and !$import ) {
614 # if anything non-empty, try to look it up
615 my $queue = new FS::queue {
616 'job' => 'FS::geocode_Mixin::process_district_update',
617 'custnum' => $self->custnum,
619 my $error = $queue->insert( ref($self), $self->custnum );
621 $dbh->rollback if $oldAutoCommit;
622 return "queueing tax district update: $error";
627 warn " exporting\n" if $DEBUG > 1;
629 my $export_args = $options{'export_args'} || [];
632 map qsearch( 'part_export', {exportnum=>$_} ),
633 $conf->config('cust_main-exports'); #, $agentnum
635 foreach my $part_export ( @part_export ) {
636 my $error = $part_export->export_insert($self, @$export_args);
638 $dbh->rollback if $oldAutoCommit;
639 return "exporting to ". $part_export->exporttype.
640 " (transaction rolled back): $error";
644 #foreach my $depend_jobnum ( @$depend_jobnums ) {
645 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
647 # foreach my $jobnum ( @jobnums ) {
648 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
649 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
651 # my $error = $queue->depend_insert($depend_jobnum);
653 # $dbh->rollback if $oldAutoCommit;
654 # return "error queuing job dependancy: $error";
661 #if ( exists $options{'jobnums'} ) {
662 # push @{ $options{'jobnums'} }, @jobnums;
665 warn " insert complete; committing transaction\n"
668 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
673 use File::CounterFile;
674 sub auto_agent_custid {
677 my $format = $conf->config('cust_main-auto_agent_custid');
679 if ( $format eq '1YMMXXXXXXXX' ) {
681 my $counter = new File::CounterFile 'cust_main.agent_custid';
684 my $ym = 100000000000 + time2str('%y%m00000000', time);
685 if ( $ym > $counter->value ) {
686 $counter->{'value'} = $agent_custid = $ym;
687 $counter->{'updated'} = 1;
689 $agent_custid = $counter->inc;
695 die "Unknown cust_main-auto_agent_custid format: $format";
698 $self->agent_custid($agent_custid);
702 =item PACKAGE METHODS
704 Documentation on customer package methods has been moved to
705 L<FS::cust_main::Packages>.
707 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
709 Recharges this (existing) customer with the specified prepaid card (see
710 L<FS::prepay_credit>), specified either by I<identifier> or as an
711 FS::prepay_credit object. If there is an error, returns the error, otherwise
714 Optionally, five scalar references can be passed as well. They will have their
715 values filled in with the amount, number of seconds, and number of upload,
716 download, and total bytes applied by this prepaid card.
720 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
721 #the only place that uses these args
722 sub recharge_prepay {
723 my( $self, $prepay_credit, $amountref, $secondsref,
724 $upbytesref, $downbytesref, $totalbytesref ) = @_;
726 local $SIG{HUP} = 'IGNORE';
727 local $SIG{INT} = 'IGNORE';
728 local $SIG{QUIT} = 'IGNORE';
729 local $SIG{TERM} = 'IGNORE';
730 local $SIG{TSTP} = 'IGNORE';
731 local $SIG{PIPE} = 'IGNORE';
733 my $oldAutoCommit = $FS::UID::AutoCommit;
734 local $FS::UID::AutoCommit = 0;
737 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
739 my $error = $self->get_prepay( $prepay_credit,
740 'amount_ref' => \$amount,
741 'seconds_ref' => \$seconds,
742 'upbytes_ref' => \$upbytes,
743 'downbytes_ref' => \$downbytes,
744 'totalbytes_ref' => \$totalbytes,
746 || $self->increment_seconds($seconds)
747 || $self->increment_upbytes($upbytes)
748 || $self->increment_downbytes($downbytes)
749 || $self->increment_totalbytes($totalbytes)
750 || $self->insert_cust_pay_prepay( $amount,
752 ? $prepay_credit->identifier
757 $dbh->rollback if $oldAutoCommit;
761 if ( defined($amountref) ) { $$amountref = $amount; }
762 if ( defined($secondsref) ) { $$secondsref = $seconds; }
763 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
764 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
765 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
767 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
772 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
774 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
775 specified either by I<identifier> or as an FS::prepay_credit object.
777 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
778 incremented by the values of the prepaid card.
780 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
781 check or set this customer's I<agentnum>.
783 If there is an error, returns the error, otherwise returns false.
789 my( $self, $prepay_credit, %opt ) = @_;
791 local $SIG{HUP} = 'IGNORE';
792 local $SIG{INT} = 'IGNORE';
793 local $SIG{QUIT} = 'IGNORE';
794 local $SIG{TERM} = 'IGNORE';
795 local $SIG{TSTP} = 'IGNORE';
796 local $SIG{PIPE} = 'IGNORE';
798 my $oldAutoCommit = $FS::UID::AutoCommit;
799 local $FS::UID::AutoCommit = 0;
802 unless ( ref($prepay_credit) ) {
804 my $identifier = $prepay_credit;
806 $prepay_credit = qsearchs(
808 { 'identifier' => $identifier },
813 unless ( $prepay_credit ) {
814 $dbh->rollback if $oldAutoCommit;
815 return "Invalid prepaid card: ". $identifier;
820 if ( $prepay_credit->agentnum ) {
821 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
822 $dbh->rollback if $oldAutoCommit;
823 return "prepaid card not valid for agent ". $self->agentnum;
825 $self->agentnum($prepay_credit->agentnum);
828 my $error = $prepay_credit->delete;
830 $dbh->rollback if $oldAutoCommit;
831 return "removing prepay_credit (transaction rolled back): $error";
834 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
835 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
837 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
842 =item increment_upbytes SECONDS
844 Updates this customer's single or primary account (see L<FS::svc_acct>) by
845 the specified number of upbytes. If there is an error, returns the error,
846 otherwise returns false.
850 sub increment_upbytes {
851 _increment_column( shift, 'upbytes', @_);
854 =item increment_downbytes SECONDS
856 Updates this customer's single or primary account (see L<FS::svc_acct>) by
857 the specified number of downbytes. If there is an error, returns the error,
858 otherwise returns false.
862 sub increment_downbytes {
863 _increment_column( shift, 'downbytes', @_);
866 =item increment_totalbytes SECONDS
868 Updates this customer's single or primary account (see L<FS::svc_acct>) by
869 the specified number of totalbytes. If there is an error, returns the error,
870 otherwise returns false.
874 sub increment_totalbytes {
875 _increment_column( shift, 'totalbytes', @_);
878 =item increment_seconds SECONDS
880 Updates this customer's single or primary account (see L<FS::svc_acct>) by
881 the specified number of seconds. If there is an error, returns the error,
882 otherwise returns false.
886 sub increment_seconds {
887 _increment_column( shift, 'seconds', @_);
890 =item _increment_column AMOUNT
892 Updates this customer's single or primary account (see L<FS::svc_acct>) by
893 the specified number of seconds or bytes. If there is an error, returns
894 the error, otherwise returns false.
898 sub _increment_column {
899 my( $self, $column, $amount ) = @_;
900 warn "$me increment_column called: $column, $amount\n"
903 return '' unless $amount;
905 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
906 $self->ncancelled_pkgs;
909 return 'No packages with primary or single services found'.
910 ' to apply pre-paid time';
911 } elsif ( scalar(@cust_pkg) > 1 ) {
912 #maybe have a way to specify the package/account?
913 return 'Multiple packages found to apply pre-paid time';
916 my $cust_pkg = $cust_pkg[0];
917 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
921 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
924 return 'No account found to apply pre-paid time';
925 } elsif ( scalar(@cust_svc) > 1 ) {
926 return 'Multiple accounts found to apply pre-paid time';
929 my $svc_acct = $cust_svc[0]->svc_x;
930 warn " found service svcnum ". $svc_acct->pkgnum.
931 ' ('. $svc_acct->email. ")\n"
934 $column = "increment_$column";
935 $svc_acct->$column($amount);
939 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
941 Inserts a prepayment in the specified amount for this customer. An optional
942 second argument can specify the prepayment identifier for tracking purposes.
943 If there is an error, returns the error, otherwise returns false.
947 sub insert_cust_pay_prepay {
948 shift->insert_cust_pay('PREP', @_);
951 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
953 Inserts a cash payment in the specified amount for this customer. An optional
954 second argument can specify the payment identifier for tracking purposes.
955 If there is an error, returns the error, otherwise returns false.
959 sub insert_cust_pay_cash {
960 shift->insert_cust_pay('CASH', @_);
963 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
965 Inserts a Western Union payment in the specified amount for this customer. An
966 optional second argument can specify the prepayment identifier for tracking
967 purposes. If there is an error, returns the error, otherwise returns false.
971 sub insert_cust_pay_west {
972 shift->insert_cust_pay('WEST', @_);
975 sub insert_cust_pay {
976 my( $self, $payby, $amount ) = splice(@_, 0, 3);
977 my $payinfo = scalar(@_) ? shift : '';
979 my $cust_pay = new FS::cust_pay {
980 'custnum' => $self->custnum,
981 'paid' => sprintf('%.2f', $amount),
982 #'_date' => #date the prepaid card was purchased???
984 'payinfo' => $payinfo,
992 This method is deprecated. See the I<depend_jobnum> option to the insert and
993 order_pkgs methods for a better way to defer provisioning.
995 Re-schedules all exports by calling the B<reexport> method of all associated
996 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
997 otherwise returns false.
1004 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1005 "use the depend_jobnum option to insert or order_pkgs to delay export";
1007 local $SIG{HUP} = 'IGNORE';
1008 local $SIG{INT} = 'IGNORE';
1009 local $SIG{QUIT} = 'IGNORE';
1010 local $SIG{TERM} = 'IGNORE';
1011 local $SIG{TSTP} = 'IGNORE';
1012 local $SIG{PIPE} = 'IGNORE';
1014 my $oldAutoCommit = $FS::UID::AutoCommit;
1015 local $FS::UID::AutoCommit = 0;
1018 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1019 my $error = $cust_pkg->reexport;
1021 $dbh->rollback if $oldAutoCommit;
1026 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1031 =item delete [ OPTION => VALUE ... ]
1033 This deletes the customer. If there is an error, returns the error, otherwise
1036 This will completely remove all traces of the customer record. This is not
1037 what you want when a customer cancels service; for that, cancel all of the
1038 customer's packages (see L</cancel>).
1040 If the customer has any uncancelled packages, you need to pass a new (valid)
1041 customer number for those packages to be transferred to, as the "new_customer"
1042 option. Cancelled packages will be deleted. Did I mention that this is NOT
1043 what you want when a customer cancels service and that you really should be
1044 looking at L<FS::cust_pkg/cancel>?
1046 You can't delete a customer with invoices (see L<FS::cust_bill>),
1047 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1048 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1049 set the "delete_financials" option to a true value.
1054 my( $self, %opt ) = @_;
1056 local $SIG{HUP} = 'IGNORE';
1057 local $SIG{INT} = 'IGNORE';
1058 local $SIG{QUIT} = 'IGNORE';
1059 local $SIG{TERM} = 'IGNORE';
1060 local $SIG{TSTP} = 'IGNORE';
1061 local $SIG{PIPE} = 'IGNORE';
1063 my $oldAutoCommit = $FS::UID::AutoCommit;
1064 local $FS::UID::AutoCommit = 0;
1067 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1068 $dbh->rollback if $oldAutoCommit;
1069 return "Can't delete a master agent customer";
1072 #use FS::access_user
1073 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1074 $dbh->rollback if $oldAutoCommit;
1075 return "Can't delete a master employee customer";
1078 tie my %financial_tables, 'Tie::IxHash',
1079 'cust_bill' => 'invoices',
1080 'cust_statement' => 'statements',
1081 'cust_credit' => 'credits',
1082 'cust_pay' => 'payments',
1083 'cust_refund' => 'refunds',
1086 foreach my $table ( keys %financial_tables ) {
1088 my @records = $self->$table();
1090 if ( @records && ! $opt{'delete_financials'} ) {
1091 $dbh->rollback if $oldAutoCommit;
1092 return "Can't delete a customer with ". $financial_tables{$table};
1095 foreach my $record ( @records ) {
1096 my $error = $record->delete;
1098 $dbh->rollback if $oldAutoCommit;
1099 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1105 my @cust_pkg = $self->ncancelled_pkgs;
1107 my $new_custnum = $opt{'new_custnum'};
1108 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1109 $dbh->rollback if $oldAutoCommit;
1110 return "Invalid new customer number: $new_custnum";
1112 foreach my $cust_pkg ( @cust_pkg ) {
1113 my %hash = $cust_pkg->hash;
1114 $hash{'custnum'} = $new_custnum;
1115 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1116 my $error = $new_cust_pkg->replace($cust_pkg,
1117 options => { $cust_pkg->options },
1120 $dbh->rollback if $oldAutoCommit;
1125 my @cancelled_cust_pkg = $self->all_pkgs;
1126 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1127 my $error = $cust_pkg->delete;
1129 $dbh->rollback if $oldAutoCommit;
1134 #cust_tax_adjustment in financials?
1135 #cust_pay_pending? ouch
1137 foreach my $table (qw(
1138 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1139 cust_location cust_main_note cust_tax_adjustment
1140 cust_pay_void cust_pay_batch queue cust_tax_exempt
1142 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1143 my $error = $record->delete;
1145 $dbh->rollback if $oldAutoCommit;
1151 my $sth = $dbh->prepare(
1152 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1154 my $errstr = $dbh->errstr;
1155 $dbh->rollback if $oldAutoCommit;
1158 $sth->execute($self->custnum) or do {
1159 my $errstr = $sth->errstr;
1160 $dbh->rollback if $oldAutoCommit;
1166 my $ticket_dbh = '';
1167 if ($conf->config('ticket_system') eq 'RT_Internal') {
1169 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1170 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1171 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1172 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1175 if ( $ticket_dbh ) {
1177 my $ticket_sth = $ticket_dbh->prepare(
1178 'DELETE FROM Links WHERE Target = ?'
1180 my $errstr = $ticket_dbh->errstr;
1181 $dbh->rollback if $oldAutoCommit;
1184 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1186 my $errstr = $ticket_sth->errstr;
1187 $dbh->rollback if $oldAutoCommit;
1191 #check and see if the customer is the only link on the ticket, and
1192 #if so, set the ticket to deleted status in RT?
1193 #maybe someday, for now this will at least fix tickets not displaying
1197 #delete the customer record
1199 my $error = $self->SUPER::delete;
1201 $dbh->rollback if $oldAutoCommit;
1205 # cust_main exports!
1207 #my $export_args = $options{'export_args'} || [];
1210 map qsearch( 'part_export', {exportnum=>$_} ),
1211 $conf->config('cust_main-exports'); #, $agentnum
1213 foreach my $part_export ( @part_export ) {
1214 my $error = $part_export->export_delete( $self ); #, @$export_args);
1216 $dbh->rollback if $oldAutoCommit;
1217 return "exporting to ". $part_export->exporttype.
1218 " (transaction rolled back): $error";
1222 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1227 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1229 This merges this customer into the provided new custnum, and then deletes the
1230 customer. If there is an error, returns the error, otherwise returns false.
1232 The source customer's name, company name, phone numbers, agent,
1233 referring customer, customer class, advertising source, order taker, and
1234 billing information (except balance) are discarded.
1236 All packages are moved to the target customer. Packages with package locations
1237 are preserved. Packages without package locations are moved to a new package
1238 location with the source customer's service/shipping address.
1240 All invoices, statements, payments, credits and refunds are moved to the target
1241 customer. The source customer's balance is added to the target customer.
1243 All notes, attachments, tickets and customer tags are moved to the target
1246 Change history is not currently moved.
1251 my( $self, $new_custnum, %opt ) = @_;
1253 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1255 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1256 return "Invalid new customer number: $new_custnum";
1259 local $SIG{HUP} = 'IGNORE';
1260 local $SIG{INT} = 'IGNORE';
1261 local $SIG{QUIT} = 'IGNORE';
1262 local $SIG{TERM} = 'IGNORE';
1263 local $SIG{TSTP} = 'IGNORE';
1264 local $SIG{PIPE} = 'IGNORE';
1266 my $oldAutoCommit = $FS::UID::AutoCommit;
1267 local $FS::UID::AutoCommit = 0;
1270 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1271 $dbh->rollback if $oldAutoCommit;
1272 return "Can't merge a master agent customer";
1275 #use FS::access_user
1276 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1277 $dbh->rollback if $oldAutoCommit;
1278 return "Can't merge a master employee customer";
1281 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1282 'status' => { op=>'!=', value=>'done' },
1286 $dbh->rollback if $oldAutoCommit;
1287 return "Can't merge a customer with pending payments";
1290 tie my %financial_tables, 'Tie::IxHash',
1291 'cust_bill' => 'invoices',
1292 'cust_statement' => 'statements',
1293 'cust_credit' => 'credits',
1294 'cust_pay' => 'payments',
1295 'cust_pay_void' => 'voided payments',
1296 'cust_refund' => 'refunds',
1299 foreach my $table ( keys %financial_tables ) {
1301 my @records = $self->$table();
1303 foreach my $record ( @records ) {
1304 $record->custnum($new_custnum);
1305 my $error = $record->replace;
1307 $dbh->rollback if $oldAutoCommit;
1308 return "Error merging ". $financial_tables{$table}. ": $error\n";
1314 my $name = $self->ship_name;
1316 my $locationnum = '';
1317 foreach my $cust_pkg ( $self->all_pkgs ) {
1318 $cust_pkg->custnum($new_custnum);
1320 unless ( $cust_pkg->locationnum ) {
1321 unless ( $locationnum ) {
1322 my $cust_location = new FS::cust_location {
1323 $self->location_hash,
1324 'custnum' => $new_custnum,
1326 my $error = $cust_location->insert;
1328 $dbh->rollback if $oldAutoCommit;
1331 $locationnum = $cust_location->locationnum;
1333 $cust_pkg->locationnum($locationnum);
1336 my $error = $cust_pkg->replace;
1338 $dbh->rollback if $oldAutoCommit;
1342 # add customer (ship) name to svc_phone.phone_name if blank
1343 my @cust_svc = $cust_pkg->cust_svc;
1344 foreach my $cust_svc (@cust_svc) {
1345 my($label, $value, $svcdb) = $cust_svc->label;
1346 next unless $svcdb eq 'svc_phone';
1347 my $svc_phone = $cust_svc->svc_x;
1348 next if $svc_phone->phone_name;
1349 $svc_phone->phone_name($name);
1350 my $error = $svc_phone->replace;
1352 $dbh->rollback if $oldAutoCommit;
1360 # cust_tax_exempt (texas tax exemptions)
1361 # cust_recon (some sort of not-well understood thing for OnPac)
1363 #these are moved over
1364 foreach my $table (qw(
1365 cust_tag cust_location contact cust_attachment cust_main_note
1366 cust_tax_adjustment cust_pay_batch queue
1368 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1369 $record->custnum($new_custnum);
1370 my $error = $record->replace;
1372 $dbh->rollback if $oldAutoCommit;
1378 #these aren't preserved
1379 foreach my $table (qw(
1380 cust_main_exemption cust_main_invoice
1382 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1383 my $error = $record->delete;
1385 $dbh->rollback if $oldAutoCommit;
1392 my $sth = $dbh->prepare(
1393 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1395 my $errstr = $dbh->errstr;
1396 $dbh->rollback if $oldAutoCommit;
1399 $sth->execute($new_custnum, $self->custnum) or do {
1400 my $errstr = $sth->errstr;
1401 $dbh->rollback if $oldAutoCommit;
1407 my $ticket_dbh = '';
1408 if ($conf->config('ticket_system') eq 'RT_Internal') {
1410 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1411 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1412 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1413 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1416 if ( $ticket_dbh ) {
1418 my $ticket_sth = $ticket_dbh->prepare(
1419 'UPDATE Links SET Target = ? WHERE Target = ?'
1421 my $errstr = $ticket_dbh->errstr;
1422 $dbh->rollback if $oldAutoCommit;
1425 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1426 'freeside://freeside/cust_main/'.$self->custnum)
1428 my $errstr = $ticket_sth->errstr;
1429 $dbh->rollback if $oldAutoCommit;
1435 #delete the customer record
1437 my $error = $self->delete;
1439 $dbh->rollback if $oldAutoCommit;
1443 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1448 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1451 Replaces the OLD_RECORD with this one in the database. If there is an error,
1452 returns the error, otherwise returns false.
1454 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1455 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1456 expected and rollback the entire transaction; it is not necessary to call
1457 check_invoicing_list first. Here's an example:
1459 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1461 Currently available options are: I<tax_exemption>.
1463 The I<tax_exemption> option can be set to an arrayref of tax names.
1464 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1471 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1473 : $self->replace_old;
1477 warn "$me replace called\n"
1480 my $curuser = $FS::CurrentUser::CurrentUser;
1481 if ( $self->payby eq 'COMP'
1482 && $self->payby ne $old->payby
1483 && ! $curuser->access_right('Complimentary customer')
1486 return "You are not permitted to create complimentary accounts.";
1489 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1490 && $conf->exists('enable_taxproducts')
1493 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1495 $self->set('geocode', '')
1496 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1497 && length($self->get($pre.'zip')) >= 10;
1500 for my $pre ( grep $old->get($_.'coord_auto'), ( '', 'ship_' ) ) {
1502 $self->set($pre.'coord_auto', '') && next
1503 if $self->get($pre.'latitude') && $self->get($pre.'longitude')
1504 && ( $self->get($pre.'latitude') != $old->get($pre.'latitude')
1505 || $self->get($pre.'longitude') != $old->get($pre.'longitude')
1508 $self->set_coord($pre)
1509 if $old->get($pre.'address1') ne $self->get($pre.'address1')
1510 || $old->get($pre.'city') ne $self->get($pre.'city')
1511 || $old->get($pre.'state') ne $self->get($pre.'state')
1512 || $old->get($pre.'country') ne $self->get($pre.'country');
1516 unless ( $import ) {
1518 if ! $self->coord_auto && ! $self->latitude && ! $self->longitude;
1520 $self->set_coord('ship_')
1521 if $self->has_ship_address && ! $self->ship_coord_auto
1522 && ! $self->ship_latitude && ! $self->ship_longitude;
1525 local($ignore_expired_card) = 1
1526 if $old->payby =~ /^(CARD|DCRD)$/
1527 && $self->payby =~ /^(CARD|DCRD)$/
1528 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1530 local($ignore_banned_card) = 1
1531 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1532 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1533 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1535 if ( $self->censustract ne '' and $self->censustract ne $old->censustract ) {
1536 # update censusyear whenever tract code changes
1537 $self->censusyear($conf->config('census_year')||'2012');
1540 return "Invoicing locale is required"
1543 && $conf->exists('cust_main-require_locale');
1545 local $SIG{HUP} = 'IGNORE';
1546 local $SIG{INT} = 'IGNORE';
1547 local $SIG{QUIT} = 'IGNORE';
1548 local $SIG{TERM} = 'IGNORE';
1549 local $SIG{TSTP} = 'IGNORE';
1550 local $SIG{PIPE} = 'IGNORE';
1552 my $oldAutoCommit = $FS::UID::AutoCommit;
1553 local $FS::UID::AutoCommit = 0;
1556 my $error = $self->SUPER::replace($old);
1559 $dbh->rollback if $oldAutoCommit;
1563 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1564 my $invoicing_list = shift @param;
1565 $error = $self->check_invoicing_list( $invoicing_list );
1567 $dbh->rollback if $oldAutoCommit;
1570 $self->invoicing_list( $invoicing_list );
1573 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1575 #this could be more efficient than deleting and re-inserting, if it matters
1576 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1577 my $error = $cust_tag->delete;
1579 $dbh->rollback if $oldAutoCommit;
1583 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1584 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1585 'custnum' => $self->custnum };
1586 my $error = $cust_tag->insert;
1588 $dbh->rollback if $oldAutoCommit;
1595 my %options = @param;
1597 my $tax_exemption = delete $options{'tax_exemption'};
1598 if ( $tax_exemption ) {
1600 my %cust_main_exemption =
1601 map { $_->taxname => $_ }
1602 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1604 foreach my $taxname ( @$tax_exemption ) {
1606 next if delete $cust_main_exemption{$taxname};
1608 my $cust_main_exemption = new FS::cust_main_exemption {
1609 'custnum' => $self->custnum,
1610 'taxname' => $taxname,
1612 my $error = $cust_main_exemption->insert;
1614 $dbh->rollback if $oldAutoCommit;
1615 return "inserting cust_main_exemption (transaction rolled back): $error";
1619 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1620 my $error = $cust_main_exemption->delete;
1622 $dbh->rollback if $oldAutoCommit;
1623 return "deleting cust_main_exemption (transaction rolled back): $error";
1629 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1630 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1631 && $self->get('payinfo') !~ /^99\d{14}$/
1633 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1638 # card/check/lec info has changed, want to retry realtime_ invoice events
1639 my $error = $self->retry_realtime;
1641 $dbh->rollback if $oldAutoCommit;
1646 unless ( $import || $skip_fuzzyfiles ) {
1647 $error = $self->queue_fuzzyfiles_update;
1649 $dbh->rollback if $oldAutoCommit;
1650 return "updating fuzzy search cache: $error";
1654 # FS::geocode_Mixin::after_replace ?
1655 # though this will go away anyway once we move customer bill/service
1656 # locations into cust_location
1657 # We can trigger this on any address change--just have to make sure
1658 # not to trigger it on itself.
1659 if ( $conf->config('tax_district_method') and !$import
1660 and ( $self->get('ship_address1') ne $old->get('ship_address1')
1661 or $self->get('address1') ne $old->get('address1') ) ) {
1662 my $queue = new FS::queue {
1663 'job' => 'FS::geocode_Mixin::process_district_update',
1664 'custnum' => $self->custnum,
1666 my $error = $queue->insert( ref($self), $self->custnum );
1668 $dbh->rollback if $oldAutoCommit;
1669 return "queueing tax district update: $error";
1673 # cust_main exports!
1675 my $export_args = $options{'export_args'} || [];
1678 map qsearch( 'part_export', {exportnum=>$_} ),
1679 $conf->config('cust_main-exports'); #, $agentnum
1681 foreach my $part_export ( @part_export ) {
1682 my $error = $part_export->export_replace( $self, $old, @$export_args);
1684 $dbh->rollback if $oldAutoCommit;
1685 return "exporting to ". $part_export->exporttype.
1686 " (transaction rolled back): $error";
1690 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1695 =item queue_fuzzyfiles_update
1697 Used by insert & replace to update the fuzzy search cache
1701 use FS::cust_main::Search;
1702 sub queue_fuzzyfiles_update {
1705 local $SIG{HUP} = 'IGNORE';
1706 local $SIG{INT} = 'IGNORE';
1707 local $SIG{QUIT} = 'IGNORE';
1708 local $SIG{TERM} = 'IGNORE';
1709 local $SIG{TSTP} = 'IGNORE';
1710 local $SIG{PIPE} = 'IGNORE';
1712 my $oldAutoCommit = $FS::UID::AutoCommit;
1713 local $FS::UID::AutoCommit = 0;
1716 my $queue = new FS::queue { 'job' => 'FS::cust_main::Search::append_fuzzyfiles' };
1717 my $error = $queue->insert( map $self->getfield($_), @FS::cust_main::Search::fuzzyfields );
1719 $dbh->rollback if $oldAutoCommit;
1720 return "queueing job (transaction rolled back): $error";
1723 if ( $self->ship_last ) {
1724 $queue = new FS::queue { 'job' => 'FS::cust_main::Search::append_fuzzyfiles' };
1725 $error = $queue->insert( map $self->getfield("ship_$_"), @FS::cust_main::Search::fuzzyfields );
1727 $dbh->rollback if $oldAutoCommit;
1728 return "queueing job (transaction rolled back): $error";
1732 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1739 Checks all fields to make sure this is a valid customer record. If there is
1740 an error, returns the error, otherwise returns false. Called by the insert
1741 and replace methods.
1748 warn "$me check BEFORE: \n". $self->_dump
1752 $self->ut_numbern('custnum')
1753 || $self->ut_number('agentnum')
1754 || $self->ut_textn('agent_custid')
1755 || $self->ut_number('refnum')
1756 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1757 || $self->ut_textn('custbatch')
1758 || $self->ut_name('last')
1759 || $self->ut_name('first')
1760 || $self->ut_snumbern('birthdate')
1761 || $self->ut_snumbern('signupdate')
1762 || $self->ut_textn('company')
1763 || $self->ut_text('address1')
1764 || $self->ut_textn('address2')
1765 || $self->ut_text('city')
1766 || $self->ut_textn('county')
1767 || $self->ut_textn('state')
1768 || $self->ut_country('country')
1769 || $self->ut_coordn('latitude')
1770 || $self->ut_coordn('longitude')
1771 || $self->ut_enum('coord_auto', [ '', 'Y' ])
1772 || $self->ut_numbern('censusyear')
1773 || $self->ut_anything('comments')
1774 || $self->ut_numbern('referral_custnum')
1775 || $self->ut_textn('stateid')
1776 || $self->ut_textn('stateid_state')
1777 || $self->ut_textn('invoice_terms')
1778 || $self->ut_alphan('geocode')
1779 || $self->ut_alphan('district')
1780 || $self->ut_floatn('cdr_termination_percentage')
1781 || $self->ut_floatn('credit_limit')
1782 || $self->ut_numbern('billday')
1783 || $self->ut_enum('edit_subject', [ '', 'Y' ] )
1784 || $self->ut_enum('calling_list_exempt', [ '', 'Y' ] )
1785 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1789 unless $import || ($self->latitude && $self->longitude);
1791 #barf. need message catalogs. i18n. etc.
1792 $error .= "Please select an advertising source."
1793 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1794 return $error if $error;
1796 return "Unknown agent"
1797 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1799 return "Unknown refnum"
1800 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1802 return "Unknown referring custnum: ". $self->referral_custnum
1803 unless ! $self->referral_custnum
1804 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1806 if ( $self->censustract ne '' ) {
1807 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1808 or return "Illegal census tract: ". $self->censustract;
1810 $self->censustract("$1.$2");
1813 if ( $self->ss eq '' ) {
1818 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1819 or return "Illegal social security number: ". $self->ss;
1820 $self->ss("$1-$2-$3");
1824 # bad idea to disable, causes billing to fail because of no tax rates later
1825 # except we don't fail any more
1826 unless ( $import ) {
1827 unless ( qsearch('cust_main_county', {
1828 'country' => $self->country,
1831 return "Unknown state/county/country: ".
1832 $self->state. "/". $self->county. "/". $self->country
1833 unless qsearch('cust_main_county',{
1834 'state' => $self->state,
1835 'county' => $self->county,
1836 'country' => $self->country,
1842 $self->ut_phonen('daytime', $self->country)
1843 || $self->ut_phonen('night', $self->country)
1844 || $self->ut_phonen('fax', $self->country)
1845 || $self->ut_phonen('mobile', $self->country)
1847 return $error if $error;
1849 unless ( $ignore_illegal_zip ) {
1850 $error = $self->ut_zip('zip', $self->country);
1851 return $error if $error;
1854 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1855 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1858 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1860 : FS::Msgcat::_gettext('daytime');
1861 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1863 : FS::Msgcat::_gettext('night');
1865 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1867 : FS::Msgcat::_gettext('mobile');
1869 return "$daytime_label, $night_label or $mobile_label is required"
1873 if ( $self->has_ship_address
1874 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1875 $self->addr_fields )
1879 $self->ut_name('ship_last')
1880 || $self->ut_name('ship_first')
1881 || $self->ut_textn('ship_company')
1882 || $self->ut_text('ship_address1')
1883 || $self->ut_textn('ship_address2')
1884 || $self->ut_text('ship_city')
1885 || $self->ut_textn('ship_county')
1886 || $self->ut_textn('ship_state')
1887 || $self->ut_country('ship_country')
1888 || $self->ut_coordn('ship_latitude')
1889 || $self->ut_coordn('ship_longitude')
1890 || $self->ut_enum('ship_coord_auto', [ '', 'Y' ] )
1892 return $error if $error;
1894 $self->set_coord('ship_')
1895 unless $import || ($self->ship_latitude && $self->ship_longitude);
1897 #false laziness with above
1898 unless ( qsearchs('cust_main_county', {
1899 'country' => $self->ship_country,
1902 return "Unknown ship_state/ship_county/ship_country: ".
1903 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1904 unless qsearch('cust_main_county',{
1905 'state' => $self->ship_state,
1906 'county' => $self->ship_county,
1907 'country' => $self->ship_country,
1913 $self->ut_phonen('ship_daytime', $self->ship_country)
1914 || $self->ut_phonen('ship_night', $self->ship_country)
1915 || $self->ut_phonen('ship_fax', $self->ship_country)
1916 || $self->ut_phonen('ship_mobile', $self->ship_country)
1918 return $error if $error;
1920 unless ( $ignore_illegal_zip ) {
1921 $error = $self->ut_zip('ship_zip', $self->ship_country);
1922 return $error if $error;
1924 return "Unit # is required."
1925 if $self->ship_address2 =~ /^\s*$/
1926 && $conf->exists('cust_main-require_address2');
1928 } else { # ship_ info eq billing info, so don't store dup info in database
1930 $self->setfield("ship_$_", '')
1931 foreach $self->addr_fields;
1933 return "Unit # is required."
1934 if $self->address2 =~ /^\s*$/
1935 && $conf->exists('cust_main-require_address2');
1939 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1940 # or return "Illegal payby: ". $self->payby;
1942 FS::payby->can_payby($self->table, $self->payby)
1943 or return "Illegal payby: ". $self->payby;
1945 $error = $self->ut_numbern('paystart_month')
1946 || $self->ut_numbern('paystart_year')
1947 || $self->ut_numbern('payissue')
1948 || $self->ut_textn('paytype')
1950 return $error if $error;
1952 if ( $self->payip eq '' ) {
1955 $error = $self->ut_ip('payip');
1956 return $error if $error;
1959 # If it is encrypted and the private key is not availaible then we can't
1960 # check the credit card.
1961 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1963 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1965 my $payinfo = $self->payinfo;
1966 $payinfo =~ s/\D//g;
1967 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1968 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1970 $self->payinfo($payinfo);
1972 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1974 return gettext('unknown_card_type')
1975 if $self->payinfo !~ /^99\d{14}$/ #token
1976 && cardtype($self->payinfo) eq "Unknown";
1978 unless ( $ignore_banned_card ) {
1979 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1981 if ( $ban->bantype eq 'warn' ) {
1982 #or others depending on value of $ban->reason ?
1983 return '_duplicate_card'.
1984 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1985 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1986 ' (ban# '. $ban->bannum. ')'
1987 unless $self->override_ban_warn;
1989 return 'Banned credit card: banned on '.
1990 time2str('%a %h %o at %r', $ban->_date).
1991 ' by '. $ban->otaker.
1992 ' (ban# '. $ban->bannum. ')';
1997 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1998 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1999 $self->paycvv =~ /^(\d{4})$/
2000 or return "CVV2 (CID) for American Express cards is four digits.";
2003 $self->paycvv =~ /^(\d{3})$/
2004 or return "CVV2 (CVC2/CID) is three digits.";
2011 my $cardtype = cardtype($payinfo);
2012 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
2014 return "Start date or issue number is required for $cardtype cards"
2015 unless $self->paystart_month && $self->paystart_year or $self->payissue;
2017 return "Start month must be between 1 and 12"
2018 if $self->paystart_month
2019 and $self->paystart_month < 1 || $self->paystart_month > 12;
2021 return "Start year must be 1990 or later"
2022 if $self->paystart_year
2023 and $self->paystart_year < 1990;
2025 return "Issue number must be beween 1 and 99"
2027 and $self->payissue < 1 || $self->payissue > 99;
2030 $self->paystart_month('');
2031 $self->paystart_year('');
2032 $self->payissue('');
2035 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
2037 my $payinfo = $self->payinfo;
2038 $payinfo =~ s/[^\d\@\.]//g;
2039 if ( $conf->config('echeck-country') eq 'CA' ) {
2040 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
2041 or return 'invalid echeck account@branch.bank';
2042 $payinfo = "$1\@$2.$3";
2043 } elsif ( $conf->config('echeck-country') eq 'US' ) {
2044 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
2045 $payinfo = "$1\@$2";
2047 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2048 $payinfo = "$1\@$2";
2050 $self->payinfo($payinfo);
2053 unless ( $ignore_banned_card ) {
2054 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2056 if ( $ban->bantype eq 'warn' ) {
2057 #or others depending on value of $ban->reason ?
2058 return '_duplicate_ach' unless $self->override_ban_warn;
2060 return 'Banned ACH account: banned on '.
2061 time2str('%a %h %o at %r', $ban->_date).
2062 ' by '. $ban->otaker.
2063 ' (ban# '. $ban->bannum. ')';
2068 } elsif ( $self->payby eq 'LECB' ) {
2070 my $payinfo = $self->payinfo;
2071 $payinfo =~ s/\D//g;
2072 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2074 $self->payinfo($payinfo);
2077 } elsif ( $self->payby eq 'BILL' ) {
2079 $error = $self->ut_textn('payinfo');
2080 return "Illegal P.O. number: ". $self->payinfo if $error;
2083 } elsif ( $self->payby eq 'COMP' ) {
2085 my $curuser = $FS::CurrentUser::CurrentUser;
2086 if ( ! $self->custnum
2087 && ! $curuser->access_right('Complimentary customer')
2090 return "You are not permitted to create complimentary accounts."
2093 $error = $self->ut_textn('payinfo');
2094 return "Illegal comp account issuer: ". $self->payinfo if $error;
2097 } elsif ( $self->payby eq 'PREPAY' ) {
2099 my $payinfo = $self->payinfo;
2100 $payinfo =~ s/\W//g; #anything else would just confuse things
2101 $self->payinfo($payinfo);
2102 $error = $self->ut_alpha('payinfo');
2103 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2104 return "Unknown prepayment identifier"
2105 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2110 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2111 return "Expiration date required"
2112 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2116 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2117 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2118 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2119 ( $m, $y ) = ( $2, "19$1" );
2120 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2121 ( $m, $y ) = ( $3, "20$2" );
2123 return "Illegal expiration date: ". $self->paydate;
2125 $m = sprintf('%02d',$m);
2126 $self->paydate("$y-$m-01");
2127 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2128 return gettext('expired_card')
2130 && !$ignore_expired_card
2131 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2134 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2135 ( ! $conf->exists('require_cardname')
2136 || $self->payby !~ /^(CARD|DCRD)$/ )
2138 $self->payname( $self->first. " ". $self->getfield('last') );
2140 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2141 or return gettext('illegal_name'). " payname: ". $self->payname;
2145 return "Please select an invoicing locale"
2148 && $conf->exists('cust_main-require_locale');
2150 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2151 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2155 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2157 warn "$me check AFTER: \n". $self->_dump
2160 $self->SUPER::check;
2165 Returns a list of fields which have ship_ duplicates.
2170 qw( last first company
2171 address1 address2 city county state zip country
2173 daytime night fax mobile
2177 =item has_ship_address
2179 Returns true if this customer record has a separate shipping address.
2183 sub has_ship_address {
2185 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2190 Returns a list of key/value pairs, with the following keys: address1,
2191 adddress2, city, county, state, zip, country, district, and geocode. The
2192 shipping address is used if present.
2198 Returns all locations (see L<FS::cust_location>) for this customer.
2204 qsearch('cust_location', { 'custnum' => $self->custnum } );
2209 Returns all contacts (see L<FS::contact>) for this customer.
2213 #already used :/ sub contact {
2216 qsearch('contact', { 'custnum' => $self->custnum } );
2221 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2222 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2223 on success or a list of errors.
2229 grep { $_->unsuspend } $self->suspended_pkgs;
2234 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2236 Returns a list: an empty list on success or a list of errors.
2242 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2245 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2247 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2248 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2249 of a list of pkgparts; the hashref has the following keys:
2253 =item pkgparts - listref of pkgparts
2255 =item (other options are passed to the suspend method)
2260 Returns a list: an empty list on success or a list of errors.
2264 sub suspend_if_pkgpart {
2266 my (@pkgparts, %opt);
2267 if (ref($_[0]) eq 'HASH'){
2268 @pkgparts = @{$_[0]{pkgparts}};
2273 grep { $_->suspend(%opt) }
2274 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2275 $self->unsuspended_pkgs;
2278 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2280 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2281 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2282 instead of a list of pkgparts; the hashref has the following keys:
2286 =item pkgparts - listref of pkgparts
2288 =item (other options are passed to the suspend method)
2292 Returns a list: an empty list on success or a list of errors.
2296 sub suspend_unless_pkgpart {
2298 my (@pkgparts, %opt);
2299 if (ref($_[0]) eq 'HASH'){
2300 @pkgparts = @{$_[0]{pkgparts}};
2305 grep { $_->suspend(%opt) }
2306 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2307 $self->unsuspended_pkgs;
2310 =item cancel [ OPTION => VALUE ... ]
2312 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2314 Available options are:
2318 =item quiet - can be set true to supress email cancellation notices.
2320 =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.
2322 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2324 =item nobill - can be set true to skip billing if it might otherwise be done.
2328 Always returns a list: an empty list on success or a list of errors.
2332 # nb that dates are not specified as valid options to this method
2335 my( $self, %opt ) = @_;
2337 warn "$me cancel called on customer ". $self->custnum. " with options ".
2338 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2341 return ( 'access denied' )
2342 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2344 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2346 #should try decryption (we might have the private key)
2347 # and if not maybe queue a job for the server that does?
2348 return ( "Can't (yet) ban encrypted credit cards" )
2349 if $self->is_encrypted($self->payinfo);
2351 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2352 my $error = $ban->insert;
2353 return ( $error ) if $error;
2357 my @pkgs = $self->ncancelled_pkgs;
2359 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2361 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2362 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2366 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2367 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2370 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2373 sub _banned_pay_hashref {
2384 'payby' => $payby2ban{$self->payby},
2385 'payinfo' => $self->payinfo,
2386 #don't ever *search* on reason! #'reason' =>
2390 sub _new_banned_pay_hashref {
2392 my $hr = $self->_banned_pay_hashref;
2393 $hr->{payinfo} = md5_base64($hr->{payinfo});
2399 Returns all notes (see L<FS::cust_main_note>) for this customer.
2404 my($self,$orderby_classnum) = (shift,shift);
2405 my $orderby = "_DATE DESC";
2406 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2407 qsearch( 'cust_main_note',
2408 { 'custnum' => $self->custnum },
2410 "ORDER BY $orderby",
2416 Returns the agent (see L<FS::agent>) for this customer.
2422 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2427 Returns the agent name (see L<FS::agent>) for this customer.
2433 $self->agent->agent;
2438 Returns any tags associated with this customer, as FS::cust_tag objects,
2439 or an empty list if there are no tags.
2445 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2450 Returns any tags associated with this customer, as FS::part_tag objects,
2451 or an empty list if there are no tags.
2457 map $_->part_tag, $self->cust_tag;
2463 Returns the customer class, as an FS::cust_class object, or the empty string
2464 if there is no customer class.
2470 if ( $self->classnum ) {
2471 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2479 Returns the customer category name, or the empty string if there is no customer
2486 my $cust_class = $self->cust_class;
2488 ? $cust_class->categoryname
2494 Returns the customer class name, or the empty string if there is no customer
2501 my $cust_class = $self->cust_class;
2503 ? $cust_class->classname
2507 =item BILLING METHODS
2509 Documentation on billing methods has been moved to
2510 L<FS::cust_main::Billing>.
2512 =item REALTIME BILLING METHODS
2514 Documentation on realtime billing methods has been moved to
2515 L<FS::cust_main::Billing_Realtime>.
2519 Removes the I<paycvv> field from the database directly.
2521 If there is an error, returns the error, otherwise returns false.
2527 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2528 or return dbh->errstr;
2529 $sth->execute($self->custnum)
2530 or return $sth->errstr;
2535 =item batch_card OPTION => VALUE...
2537 Adds a payment for this invoice to the pending credit card batch (see
2538 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2539 runs the payment using a realtime gateway.
2544 my ($self, %options) = @_;
2547 if (exists($options{amount})) {
2548 $amount = $options{amount};
2550 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2552 return '' unless $amount > 0;
2554 my $invnum = delete $options{invnum};
2555 my $payby = $options{payby} || $self->payby; #still dubious
2557 if ($options{'realtime'}) {
2558 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2564 my $oldAutoCommit = $FS::UID::AutoCommit;
2565 local $FS::UID::AutoCommit = 0;
2568 #this needs to handle mysql as well as Pg, like svc_acct.pm
2569 #(make it into a common function if folks need to do batching with mysql)
2570 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2571 or return "Cannot lock pay_batch: " . $dbh->errstr;
2575 'payby' => FS::payby->payby2payment($payby),
2577 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2579 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2581 unless ( $pay_batch ) {
2582 $pay_batch = new FS::pay_batch \%pay_batch;
2583 my $error = $pay_batch->insert;
2585 $dbh->rollback if $oldAutoCommit;
2586 die "error creating new batch: $error\n";
2590 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2591 'batchnum' => $pay_batch->batchnum,
2592 'custnum' => $self->custnum,
2595 foreach (qw( address1 address2 city state zip country latitude longitude
2596 payby payinfo paydate payname ))
2598 $options{$_} = '' unless exists($options{$_});
2601 my $cust_pay_batch = new FS::cust_pay_batch ( {
2602 'batchnum' => $pay_batch->batchnum,
2603 'invnum' => $invnum || 0, # is there a better value?
2604 # this field should be
2606 # cust_bill_pay_batch now
2607 'custnum' => $self->custnum,
2608 'last' => $self->getfield('last'),
2609 'first' => $self->getfield('first'),
2610 'address1' => $options{address1} || $self->address1,
2611 'address2' => $options{address2} || $self->address2,
2612 'city' => $options{city} || $self->city,
2613 'state' => $options{state} || $self->state,
2614 'zip' => $options{zip} || $self->zip,
2615 'country' => $options{country} || $self->country,
2616 'payby' => $options{payby} || $self->payby,
2617 'payinfo' => $options{payinfo} || $self->payinfo,
2618 'exp' => $options{paydate} || $self->paydate,
2619 'payname' => $options{payname} || $self->payname,
2620 'amount' => $amount, # consolidating
2623 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2624 if $old_cust_pay_batch;
2627 if ($old_cust_pay_batch) {
2628 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2630 $error = $cust_pay_batch->insert;
2634 $dbh->rollback if $oldAutoCommit;
2638 my $unapplied = $self->total_unapplied_credits
2639 + $self->total_unapplied_payments
2640 + $self->in_transit_payments;
2641 foreach my $cust_bill ($self->open_cust_bill) {
2642 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2643 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2644 'invnum' => $cust_bill->invnum,
2645 'paybatchnum' => $cust_pay_batch->paybatchnum,
2646 'amount' => $cust_bill->owed,
2649 if ($unapplied >= $cust_bill_pay_batch->amount){
2650 $unapplied -= $cust_bill_pay_batch->amount;
2653 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2654 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2656 $error = $cust_bill_pay_batch->insert;
2658 $dbh->rollback if $oldAutoCommit;
2663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2669 Returns the total owed for this customer on all invoices
2670 (see L<FS::cust_bill/owed>).
2676 $self->total_owed_date(2145859200); #12/31/2037
2679 =item total_owed_date TIME
2681 Returns the total owed for this customer on all invoices with date earlier than
2682 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2683 see L<Time::Local> and L<Date::Parse> for conversion functions.
2687 sub total_owed_date {
2691 my $custnum = $self->custnum;
2693 my $owed_sql = FS::cust_bill->owed_sql;
2696 SELECT SUM($owed_sql) FROM cust_bill
2697 WHERE custnum = $custnum
2701 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2705 =item total_owed_pkgnum PKGNUM
2707 Returns the total owed on all invoices for this customer's specific package
2708 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2712 sub total_owed_pkgnum {
2713 my( $self, $pkgnum ) = @_;
2714 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2717 =item total_owed_date_pkgnum TIME PKGNUM
2719 Returns the total owed for this customer's specific package when using
2720 experimental package balances on all invoices with date earlier than
2721 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2722 see L<Time::Local> and L<Date::Parse> for conversion functions.
2726 sub total_owed_date_pkgnum {
2727 my( $self, $time, $pkgnum ) = @_;
2730 foreach my $cust_bill (
2731 grep { $_->_date <= $time }
2732 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2734 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2736 sprintf( "%.2f", $total_bill );
2742 Returns the total amount of all payments.
2749 $total += $_->paid foreach $self->cust_pay;
2750 sprintf( "%.2f", $total );
2753 =item total_unapplied_credits
2755 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2756 customer. See L<FS::cust_credit/credited>.
2758 =item total_credited
2760 Old name for total_unapplied_credits. Don't use.
2764 sub total_credited {
2765 #carp "total_credited deprecated, use total_unapplied_credits";
2766 shift->total_unapplied_credits(@_);
2769 sub total_unapplied_credits {
2772 my $custnum = $self->custnum;
2774 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2777 SELECT SUM($unapplied_sql) FROM cust_credit
2778 WHERE custnum = $custnum
2781 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2785 =item total_unapplied_credits_pkgnum PKGNUM
2787 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2788 customer. See L<FS::cust_credit/credited>.
2792 sub total_unapplied_credits_pkgnum {
2793 my( $self, $pkgnum ) = @_;
2794 my $total_credit = 0;
2795 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2796 sprintf( "%.2f", $total_credit );
2800 =item total_unapplied_payments
2802 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2803 See L<FS::cust_pay/unapplied>.
2807 sub total_unapplied_payments {
2810 my $custnum = $self->custnum;
2812 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2815 SELECT SUM($unapplied_sql) FROM cust_pay
2816 WHERE custnum = $custnum
2819 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2823 =item total_unapplied_payments_pkgnum PKGNUM
2825 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2826 specific package when using experimental package balances. See
2827 L<FS::cust_pay/unapplied>.
2831 sub total_unapplied_payments_pkgnum {
2832 my( $self, $pkgnum ) = @_;
2833 my $total_unapplied = 0;
2834 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2835 sprintf( "%.2f", $total_unapplied );
2839 =item total_unapplied_refunds
2841 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2842 customer. See L<FS::cust_refund/unapplied>.
2846 sub total_unapplied_refunds {
2848 my $custnum = $self->custnum;
2850 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2853 SELECT SUM($unapplied_sql) FROM cust_refund
2854 WHERE custnum = $custnum
2857 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2863 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2864 total_unapplied_credits minus total_unapplied_payments).
2870 $self->balance_date_range;
2873 =item balance_date TIME
2875 Returns the balance for this customer, only considering invoices with date
2876 earlier than TIME (total_owed_date minus total_credited minus
2877 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2878 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2885 $self->balance_date_range(shift);
2888 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2890 Returns the balance for this customer, optionally considering invoices with
2891 date earlier than START_TIME, and not later than END_TIME
2892 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2894 Times are specified as SQL fragments or numeric
2895 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2896 L<Date::Parse> for conversion functions. The empty string can be passed
2897 to disable that time constraint completely.
2899 Available options are:
2903 =item unapplied_date
2905 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)
2911 sub balance_date_range {
2913 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2914 ') FROM cust_main WHERE custnum='. $self->custnum;
2915 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2918 =item balance_pkgnum PKGNUM
2920 Returns the balance for this customer's specific package when using
2921 experimental package balances (total_owed plus total_unrefunded, minus
2922 total_unapplied_credits minus total_unapplied_payments)
2926 sub balance_pkgnum {
2927 my( $self, $pkgnum ) = @_;
2930 $self->total_owed_pkgnum($pkgnum)
2931 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2932 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2933 - $self->total_unapplied_credits_pkgnum($pkgnum)
2934 - $self->total_unapplied_payments_pkgnum($pkgnum)
2938 =item in_transit_payments
2940 Returns the total of requests for payments for this customer pending in
2941 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2945 sub in_transit_payments {
2947 my $in_transit_payments = 0;
2948 foreach my $pay_batch ( qsearch('pay_batch', {
2951 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2952 'batchnum' => $pay_batch->batchnum,
2953 'custnum' => $self->custnum,
2955 $in_transit_payments += $cust_pay_batch->amount;
2958 sprintf( "%.2f", $in_transit_payments );
2963 Returns a hash of useful information for making a payment.
2973 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2974 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2975 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2979 For credit card transactions:
2991 For electronic check transactions:
3006 $return{balance} = $self->balance;
3008 $return{payname} = $self->payname
3009 || ( $self->first. ' '. $self->get('last') );
3011 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
3013 $return{payby} = $self->payby;
3014 $return{stateid_state} = $self->stateid_state;
3016 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3017 $return{card_type} = cardtype($self->payinfo);
3018 $return{payinfo} = $self->paymask;
3020 @return{'month', 'year'} = $self->paydate_monthyear;
3024 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3025 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3026 $return{payinfo1} = $payinfo1;
3027 $return{payinfo2} = $payinfo2;
3028 $return{paytype} = $self->paytype;
3029 $return{paystate} = $self->paystate;
3033 #doubleclick protection
3035 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3041 =item paydate_monthyear
3043 Returns a two-element list consisting of the month and year of this customer's
3044 paydate (credit card expiration date for CARD customers)
3048 sub paydate_monthyear {
3050 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3052 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3061 Returns the exact time in seconds corresponding to the payment method
3062 expiration date. For CARD/DCRD customers this is the end of the month;
3063 for others (COMP is the only other payby that uses paydate) it's the start.
3064 Returns 0 if the paydate is empty or set to the far future.
3070 my ($month, $year) = $self->paydate_monthyear;
3071 return 0 if !$year or $year >= 2037;
3072 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3074 if ( $month == 13 ) {
3078 return timelocal(0,0,0,1,$month-1,$year) - 1;
3081 return timelocal(0,0,0,1,$month-1,$year);
3085 =item paydate_epoch_sql
3087 Class method. Returns an SQL expression to obtain the payment expiration date
3088 as a number of seconds.
3092 # Special expiration date behavior for non-CARD/DCRD customers has been
3093 # carefully preserved. Do we really use that?
3094 sub paydate_epoch_sql {
3096 my $table = shift || 'cust_main';
3097 my ($case1, $case2);
3098 if ( driver_name eq 'Pg' ) {
3099 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3100 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3102 elsif ( lc(driver_name) eq 'mysql' ) {
3103 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3104 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3107 return "CASE WHEN $table.payby IN('CARD','DCRD')
3113 =item tax_exemption TAXNAME
3118 my( $self, $taxname ) = @_;
3120 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3121 'taxname' => $taxname,
3126 =item cust_main_exemption
3130 sub cust_main_exemption {
3132 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3135 =item invoicing_list [ ARRAYREF ]
3137 If an arguement is given, sets these email addresses as invoice recipients
3138 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3139 (except as warnings), so use check_invoicing_list first.
3141 Returns a list of email addresses (with svcnum entries expanded).
3143 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3144 check it without disturbing anything by passing nothing.
3146 This interface may change in the future.
3150 sub invoicing_list {
3151 my( $self, $arrayref ) = @_;
3154 my @cust_main_invoice;
3155 if ( $self->custnum ) {
3156 @cust_main_invoice =
3157 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3159 @cust_main_invoice = ();
3161 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3162 #warn $cust_main_invoice->destnum;
3163 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3164 #warn $cust_main_invoice->destnum;
3165 my $error = $cust_main_invoice->delete;
3166 warn $error if $error;
3169 if ( $self->custnum ) {
3170 @cust_main_invoice =
3171 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3173 @cust_main_invoice = ();
3175 my %seen = map { $_->address => 1 } @cust_main_invoice;
3176 foreach my $address ( @{$arrayref} ) {
3177 next if exists $seen{$address} && $seen{$address};
3178 $seen{$address} = 1;
3179 my $cust_main_invoice = new FS::cust_main_invoice ( {
3180 'custnum' => $self->custnum,
3183 my $error = $cust_main_invoice->insert;
3184 warn $error if $error;
3188 if ( $self->custnum ) {
3190 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3197 =item check_invoicing_list ARRAYREF
3199 Checks these arguements as valid input for the invoicing_list method. If there
3200 is an error, returns the error, otherwise returns false.
3204 sub check_invoicing_list {
3205 my( $self, $arrayref ) = @_;
3207 foreach my $address ( @$arrayref ) {
3209 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3210 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3213 my $cust_main_invoice = new FS::cust_main_invoice ( {
3214 'custnum' => $self->custnum,
3217 my $error = $self->custnum
3218 ? $cust_main_invoice->check
3219 : $cust_main_invoice->checkdest
3221 return $error if $error;
3225 return "Email address required"
3226 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3227 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3232 =item set_default_invoicing_list
3234 Sets the invoicing list to all accounts associated with this customer,
3235 overwriting any previous invoicing list.
3239 sub set_default_invoicing_list {
3241 $self->invoicing_list($self->all_emails);
3246 Returns the email addresses of all accounts provisioned for this customer.
3253 foreach my $cust_pkg ( $self->all_pkgs ) {
3254 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3256 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3257 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3259 $list{$_}=1 foreach map { $_->email } @svc_acct;
3264 =item invoicing_list_addpost
3266 Adds postal invoicing to this customer. If this customer is already configured
3267 to receive postal invoices, does nothing.
3271 sub invoicing_list_addpost {
3273 return if grep { $_ eq 'POST' } $self->invoicing_list;
3274 my @invoicing_list = $self->invoicing_list;
3275 push @invoicing_list, 'POST';
3276 $self->invoicing_list(\@invoicing_list);
3279 =item invoicing_list_emailonly
3281 Returns the list of email invoice recipients (invoicing_list without non-email
3282 destinations such as POST and FAX).
3286 sub invoicing_list_emailonly {
3288 warn "$me invoicing_list_emailonly called"
3290 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3293 =item invoicing_list_emailonly_scalar
3295 Returns the list of email invoice recipients (invoicing_list without non-email
3296 destinations such as POST and FAX) as a comma-separated scalar.
3300 sub invoicing_list_emailonly_scalar {
3302 warn "$me invoicing_list_emailonly_scalar called"
3304 join(', ', $self->invoicing_list_emailonly);
3307 =item referral_custnum_cust_main
3309 Returns the customer who referred this customer (or the empty string, if
3310 this customer was not referred).
3312 Note the difference with referral_cust_main method: This method,
3313 referral_custnum_cust_main returns the single customer (if any) who referred
3314 this customer, while referral_cust_main returns an array of customers referred
3319 sub referral_custnum_cust_main {
3321 return '' unless $self->referral_custnum;
3322 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3325 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3327 Returns an array of customers referred by this customer (referral_custnum set
3328 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3329 customers referred by customers referred by this customer and so on, inclusive.
3330 The default behavior is DEPTH 1 (no recursion).
3332 Note the difference with referral_custnum_cust_main method: This method,
3333 referral_cust_main, returns an array of customers referred BY this customer,
3334 while referral_custnum_cust_main returns the single customer (if any) who
3335 referred this customer.
3339 sub referral_cust_main {
3341 my $depth = @_ ? shift : 1;
3342 my $exclude = @_ ? shift : {};
3345 map { $exclude->{$_->custnum}++; $_; }
3346 grep { ! $exclude->{ $_->custnum } }
3347 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3351 map { $_->referral_cust_main($depth-1, $exclude) }
3358 =item referral_cust_main_ncancelled
3360 Same as referral_cust_main, except only returns customers with uncancelled
3365 sub referral_cust_main_ncancelled {
3367 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3370 =item referral_cust_pkg [ DEPTH ]
3372 Like referral_cust_main, except returns a flat list of all unsuspended (and
3373 uncancelled) packages for each customer. The number of items in this list may
3374 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3378 sub referral_cust_pkg {
3380 my $depth = @_ ? shift : 1;
3382 map { $_->unsuspended_pkgs }
3383 grep { $_->unsuspended_pkgs }
3384 $self->referral_cust_main($depth);
3387 =item referring_cust_main
3389 Returns the single cust_main record for the customer who referred this customer
3390 (referral_custnum), or false.
3394 sub referring_cust_main {
3396 return '' unless $self->referral_custnum;
3397 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3400 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3402 Applies a credit to this customer. If there is an error, returns the error,
3403 otherwise returns false.
3405 REASON can be a text string, an FS::reason object, or a scalar reference to
3406 a reasonnum. If a text string, it will be automatically inserted as a new
3407 reason, and a 'reason_type' option must be passed to indicate the
3408 FS::reason_type for the new reason.
3410 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3412 Any other options are passed to FS::cust_credit::insert.
3417 my( $self, $amount, $reason, %options ) = @_;
3419 my $cust_credit = new FS::cust_credit {
3420 'custnum' => $self->custnum,
3421 'amount' => $amount,
3424 if ( ref($reason) ) {
3426 if ( ref($reason) eq 'SCALAR' ) {
3427 $cust_credit->reasonnum( $$reason );
3429 $cust_credit->reasonnum( $reason->reasonnum );
3433 $cust_credit->set('reason', $reason)
3436 for (qw( addlinfo eventnum )) {
3437 $cust_credit->$_( delete $options{$_} )
3438 if exists($options{$_});
3441 $cust_credit->insert(%options);
3445 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3447 Creates a one-time charge for this customer. If there is an error, returns
3448 the error, otherwise returns false.
3450 New-style, with a hashref of options:
3452 my $error = $cust_main->charge(
3456 'start_date' => str2time('7/4/2009'),
3457 'pkg' => 'Description',
3458 'comment' => 'Comment',
3459 'additional' => [], #extra invoice detail
3460 'classnum' => 1, #pkg_class
3462 'setuptax' => '', # or 'Y' for tax exempt
3465 'taxclass' => 'Tax class',
3468 'taxproduct' => 2, #part_pkg_taxproduct
3469 'override' => {}, #XXX describe
3471 #will be filled in with the new object
3472 'cust_pkg_ref' => \$cust_pkg,
3474 #generate an invoice immediately
3476 'invoice_terms' => '', #with these terms
3482 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3488 my ( $amount, $quantity, $start_date, $classnum );
3489 my ( $pkg, $comment, $additional );
3490 my ( $setuptax, $taxclass ); #internal taxes
3491 my ( $taxproduct, $override ); #vendor (CCH) taxes
3493 my $cust_pkg_ref = '';
3494 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3495 if ( ref( $_[0] ) ) {
3496 $amount = $_[0]->{amount};
3497 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3498 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3499 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3500 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3501 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3502 : '$'. sprintf("%.2f",$amount);
3503 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3504 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3505 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3506 $additional = $_[0]->{additional} || [];
3507 $taxproduct = $_[0]->{taxproductnum};
3508 $override = { '' => $_[0]->{tax_override} };
3509 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3510 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3511 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3516 $pkg = @_ ? shift : 'One-time charge';
3517 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3519 $taxclass = @_ ? shift : '';
3523 local $SIG{HUP} = 'IGNORE';
3524 local $SIG{INT} = 'IGNORE';
3525 local $SIG{QUIT} = 'IGNORE';
3526 local $SIG{TERM} = 'IGNORE';
3527 local $SIG{TSTP} = 'IGNORE';
3528 local $SIG{PIPE} = 'IGNORE';
3530 my $oldAutoCommit = $FS::UID::AutoCommit;
3531 local $FS::UID::AutoCommit = 0;
3534 my $part_pkg = new FS::part_pkg ( {
3536 'comment' => $comment,
3540 'classnum' => ( $classnum ? $classnum : '' ),
3541 'setuptax' => $setuptax,
3542 'taxclass' => $taxclass,
3543 'taxproductnum' => $taxproduct,
3546 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3547 ( 0 .. @$additional - 1 )
3549 'additional_count' => scalar(@$additional),
3550 'setup_fee' => $amount,
3553 my $error = $part_pkg->insert( options => \%options,
3554 tax_overrides => $override,
3557 $dbh->rollback if $oldAutoCommit;
3561 my $pkgpart = $part_pkg->pkgpart;
3562 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3563 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3564 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3565 $error = $type_pkgs->insert;
3567 $dbh->rollback if $oldAutoCommit;
3572 my $cust_pkg = new FS::cust_pkg ( {
3573 'custnum' => $self->custnum,
3574 'pkgpart' => $pkgpart,
3575 'quantity' => $quantity,
3576 'start_date' => $start_date,
3577 'no_auto' => $no_auto,
3580 $error = $cust_pkg->insert;
3582 $dbh->rollback if $oldAutoCommit;
3584 } elsif ( $cust_pkg_ref ) {
3585 ${$cust_pkg_ref} = $cust_pkg;
3589 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3590 'pkg_list' => [ $cust_pkg ],
3593 $dbh->rollback if $oldAutoCommit;
3598 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3603 #=item charge_postal_fee
3605 #Applies a one time charge this customer. If there is an error,
3606 #returns the error, returns the cust_pkg charge object or false
3607 #if there was no charge.
3611 # This should be a customer event. For that to work requires that bill
3612 # also be a customer event.
3614 sub charge_postal_fee {
3617 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3618 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3620 my $cust_pkg = new FS::cust_pkg ( {
3621 'custnum' => $self->custnum,
3622 'pkgpart' => $pkgpart,
3626 my $error = $cust_pkg->insert;
3627 $error ? $error : $cust_pkg;
3630 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3632 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3634 Optionally, a list or hashref of additional arguments to the qsearch call can
3641 my $opt = ref($_[0]) ? shift : { @_ };
3643 #return $self->num_cust_bill unless wantarray || keys %$opt;
3645 $opt->{'table'} = 'cust_bill';
3646 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3647 $opt->{'hashref'}{'custnum'} = $self->custnum;
3648 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3650 map { $_ } #behavior of sort undefined in scalar context
3651 sort { $a->_date <=> $b->_date }
3655 =item open_cust_bill
3657 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3662 sub open_cust_bill {
3666 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3672 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3674 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3678 sub legacy_cust_bill {
3681 #return $self->num_legacy_cust_bill unless wantarray;
3683 map { $_ } #behavior of sort undefined in scalar context
3684 sort { $a->_date <=> $b->_date }
3685 qsearch({ 'table' => 'legacy_cust_bill',
3686 'hashref' => { 'custnum' => $self->custnum, },
3687 'order_by' => 'ORDER BY _date ASC',
3691 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3693 Returns all the statements (see L<FS::cust_statement>) for this customer.
3695 Optionally, a list or hashref of additional arguments to the qsearch call can
3700 sub cust_statement {
3702 my $opt = ref($_[0]) ? shift : { @_ };
3704 #return $self->num_cust_statement unless wantarray || keys %$opt;
3706 $opt->{'table'} = 'cust_statement';
3707 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3708 $opt->{'hashref'}{'custnum'} = $self->custnum;
3709 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3711 map { $_ } #behavior of sort undefined in scalar context
3712 sort { $a->_date <=> $b->_date }
3718 Returns all the credits (see L<FS::cust_credit>) for this customer.
3724 map { $_ } #return $self->num_cust_credit unless wantarray;
3725 sort { $a->_date <=> $b->_date }
3726 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3729 =item cust_credit_pkgnum
3731 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3732 package when using experimental package balances.
3736 sub cust_credit_pkgnum {
3737 my( $self, $pkgnum ) = @_;
3738 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3739 sort { $a->_date <=> $b->_date }
3740 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3741 'pkgnum' => $pkgnum,
3748 Returns all the payments (see L<FS::cust_pay>) for this customer.
3754 return $self->num_cust_pay unless wantarray;
3755 sort { $a->_date <=> $b->_date }
3756 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3761 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3762 called automatically when the cust_pay method is used in a scalar context.
3768 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3769 my $sth = dbh->prepare($sql) or die dbh->errstr;
3770 $sth->execute($self->custnum) or die $sth->errstr;
3771 $sth->fetchrow_arrayref->[0];
3774 =item cust_pay_pkgnum
3776 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3777 package when using experimental package balances.
3781 sub cust_pay_pkgnum {
3782 my( $self, $pkgnum ) = @_;
3783 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3784 sort { $a->_date <=> $b->_date }
3785 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3786 'pkgnum' => $pkgnum,
3793 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3799 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3800 sort { $a->_date <=> $b->_date }
3801 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3804 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3806 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3808 Optionally, a list or hashref of additional arguments to the qsearch call can
3813 sub cust_pay_batch {
3815 my $opt = ref($_[0]) ? shift : { @_ };
3817 #return $self->num_cust_statement unless wantarray || keys %$opt;
3819 $opt->{'table'} = 'cust_pay_batch';
3820 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3821 $opt->{'hashref'}{'custnum'} = $self->custnum;
3822 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3824 map { $_ } #behavior of sort undefined in scalar context
3825 sort { $a->paybatchnum <=> $b->paybatchnum }
3829 =item cust_pay_pending
3831 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3832 (without status "done").
3836 sub cust_pay_pending {
3838 return $self->num_cust_pay_pending unless wantarray;
3839 sort { $a->_date <=> $b->_date }
3840 qsearch( 'cust_pay_pending', {
3841 'custnum' => $self->custnum,
3842 'status' => { op=>'!=', value=>'done' },
3847 =item cust_pay_pending_attempt
3849 Returns all payment attempts / declined payments for this customer, as pending
3850 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3851 a corresponding payment (see L<FS::cust_pay>).
3855 sub cust_pay_pending_attempt {
3857 return $self->num_cust_pay_pending_attempt unless wantarray;
3858 sort { $a->_date <=> $b->_date }
3859 qsearch( 'cust_pay_pending', {
3860 'custnum' => $self->custnum,
3867 =item num_cust_pay_pending
3869 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3870 customer (without status "done"). Also called automatically when the
3871 cust_pay_pending method is used in a scalar context.
3875 sub num_cust_pay_pending {
3878 " SELECT COUNT(*) FROM cust_pay_pending ".
3879 " WHERE custnum = ? AND status != 'done' ",
3884 =item num_cust_pay_pending_attempt
3886 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3887 customer, with status "done" but without a corresp. Also called automatically when the
3888 cust_pay_pending method is used in a scalar context.
3892 sub num_cust_pay_pending_attempt {
3895 " SELECT COUNT(*) FROM cust_pay_pending ".
3896 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3903 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3909 map { $_ } #return $self->num_cust_refund unless wantarray;
3910 sort { $a->_date <=> $b->_date }
3911 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3914 =item display_custnum
3916 Returns the displayed customer number for this customer: agent_custid if
3917 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3921 sub display_custnum {
3924 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3925 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3926 if ( $special eq 'CoStAg' ) {
3927 $prefix = uc( join('',
3929 ($self->state =~ /^(..)/),
3930 $prefix || ($self->agent->agent =~ /^(..)/)
3933 elsif ( $special eq 'CoStCl' ) {
3934 $prefix = uc( join('',
3936 ($self->state =~ /^(..)/),
3937 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3940 # add any others here if needed
3943 my $length = $conf->config('cust_main-custnum-display_length');
3944 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3945 return $self->agent_custid;
3946 } elsif ( $prefix ) {
3947 $length = 8 if !defined($length);
3949 sprintf('%0'.$length.'d', $self->custnum)
3950 } elsif ( $length ) {
3951 return sprintf('%0'.$length.'d', $self->custnum);
3953 return $self->custnum;
3959 Returns a name string for this customer, either "Company (Last, First)" or
3966 my $name = $self->contact;
3967 $name = $self->company. " ($name)" if $self->company;
3973 Returns a name string for this (service/shipping) contact, either
3974 "Company (Last, First)" or "Last, First".
3980 if ( $self->get('ship_last') ) {
3981 my $name = $self->ship_contact;
3982 $name = $self->ship_company. " ($name)" if $self->ship_company;
3991 Returns a name string for this customer, either "Company" or "First Last".
3997 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4000 =item ship_name_short
4002 Returns a name string for this (service/shipping) contact, either "Company"
4007 sub ship_name_short {
4009 if ( $self->get('ship_last') ) {
4010 $self->ship_company !~ /^\s*$/
4011 ? $self->ship_company
4012 : $self->ship_contact_firstlast;
4014 $self->name_company_or_firstlast;
4020 Returns this customer's full (billing) contact name only, "Last, First"
4026 $self->get('last'). ', '. $self->first;
4031 Returns this customer's full (shipping) contact name only, "Last, First"
4037 $self->get('ship_last')
4038 ? $self->get('ship_last'). ', '. $self->ship_first
4042 =item contact_firstlast
4044 Returns this customers full (billing) contact name only, "First Last".
4048 sub contact_firstlast {
4050 $self->first. ' '. $self->get('last');
4053 =item ship_contact_firstlast
4055 Returns this customer's full (shipping) contact name only, "First Last".
4059 sub ship_contact_firstlast {
4061 $self->get('ship_last')
4062 ? $self->first. ' '. $self->get('ship_last')
4063 : $self->contact_firstlast;
4068 Returns this customer's full country name
4074 code2country($self->country);
4077 =item geocode DATA_VENDOR
4079 Returns a value for the customer location as encoded by DATA_VENDOR.
4080 Currently this only makes sense for "CCH" as DATA_VENDOR.
4088 Returns a status string for this customer, currently:
4092 =item prospect - No packages have ever been ordered
4094 =item ordered - Recurring packages all are new (not yet billed).
4096 =item active - One or more recurring packages is active
4098 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4100 =item suspended - All non-cancelled recurring packages are suspended
4102 =item cancelled - All recurring packages are cancelled
4106 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4107 cust_main-status_module configuration option.
4111 sub status { shift->cust_status(@_); }
4115 for my $status ( FS::cust_main->statuses() ) {
4116 my $method = $status.'_sql';
4117 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4118 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4119 $sth->execute( ($self->custnum) x $numnum )
4120 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4121 return $status if $sth->fetchrow_arrayref->[0];
4125 =item ucfirst_cust_status
4127 =item ucfirst_status
4129 Returns the status with the first character capitalized.
4133 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4135 sub ucfirst_cust_status {
4137 ucfirst($self->cust_status);
4142 Returns a hex triplet color string for this customer's status.
4146 sub statuscolor { shift->cust_statuscolor(@_); }
4148 sub cust_statuscolor {
4150 __PACKAGE__->statuscolors->{$self->cust_status};
4155 Returns an array of hashes representing the customer's RT tickets.
4162 my $num = $conf->config('cust_main-max_tickets') || 10;
4165 if ( $conf->config('ticket_system') ) {
4166 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4168 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4172 foreach my $priority (
4173 $conf->config('ticket_system-custom_priority_field-values'), ''
4175 last if scalar(@tickets) >= $num;
4177 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4178 $num - scalar(@tickets),
4188 # Return services representing svc_accts in customer support packages
4189 sub support_services {
4191 my %packages = map { $_ => 1 } $conf->config('support_packages');
4193 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4194 grep { $_->part_svc->svcdb eq 'svc_acct' }
4195 map { $_->cust_svc }
4196 grep { exists $packages{ $_->pkgpart } }
4197 $self->ncancelled_pkgs;
4201 # Return a list of latitude/longitude for one of the services (if any)
4202 sub service_coordinates {
4206 grep { $_->latitude && $_->longitude }
4208 map { $_->cust_svc }
4209 $self->ncancelled_pkgs;
4211 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4216 Returns a masked version of the named field
4221 my ($self,$field) = @_;
4225 'x'x(length($self->getfield($field))-4).
4226 substr($self->getfield($field), (length($self->getfield($field))-4));
4232 =head1 CLASS METHODS
4238 Class method that returns the list of possible status strings for customers
4239 (see L<the status method|/status>). For example:
4241 @statuses = FS::cust_main->statuses();
4247 keys %{ $self->statuscolors };
4250 =item cust_status_sql
4252 Returns an SQL fragment to determine the status of a cust_main record, as a
4257 sub cust_status_sql {
4259 for my $status ( FS::cust_main->statuses() ) {
4260 my $method = $status.'_sql';
4261 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4270 Returns an SQL expression identifying prospective cust_main records (customers
4271 with no packages ever ordered)
4275 use vars qw($select_count_pkgs);
4276 $select_count_pkgs =
4277 "SELECT COUNT(*) FROM cust_pkg
4278 WHERE cust_pkg.custnum = cust_main.custnum";
4280 sub select_count_pkgs_sql {
4285 " 0 = ( $select_count_pkgs ) ";
4290 Returns an SQL expression identifying ordered cust_main records (customers with
4291 no active packages, but recurring packages not yet setup or one time charges
4297 FS::cust_main->none_active_sql.
4298 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4303 Returns an SQL expression identifying active cust_main records (customers with
4304 active recurring packages).
4309 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4312 =item none_active_sql
4314 Returns an SQL expression identifying cust_main records with no active
4315 recurring packages. This includes customers of status prospect, ordered,
4316 inactive, and suspended.
4320 sub none_active_sql {
4321 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4326 Returns an SQL expression identifying inactive cust_main records (customers with
4327 no active recurring packages, but otherwise unsuspended/uncancelled).
4332 FS::cust_main->none_active_sql.
4333 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4339 Returns an SQL expression identifying suspended cust_main records.
4344 sub suspended_sql { susp_sql(@_); }
4346 FS::cust_main->none_active_sql.
4347 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4353 Returns an SQL expression identifying cancelled cust_main records.
4357 sub cancel_sql { shift->cancelled_sql(@_); }
4360 =item uncancelled_sql
4362 Returns an SQL expression identifying un-cancelled cust_main records.
4366 sub uncancelled_sql { uncancel_sql(@_); }
4367 sub uncancel_sql { "
4368 ( 0 < ( $select_count_pkgs
4369 AND ( cust_pkg.cancel IS NULL
4370 OR cust_pkg.cancel = 0
4373 OR 0 = ( $select_count_pkgs )
4379 Returns an SQL fragment to retreive the balance.
4384 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4385 WHERE cust_bill.custnum = cust_main.custnum )
4386 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4387 WHERE cust_pay.custnum = cust_main.custnum )
4388 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4389 WHERE cust_credit.custnum = cust_main.custnum )
4390 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4391 WHERE cust_refund.custnum = cust_main.custnum )
4394 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4396 Returns an SQL fragment to retreive the balance for this customer, optionally
4397 considering invoices with date earlier than START_TIME, and not
4398 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4399 total_unapplied_payments).
4401 Times are specified as SQL fragments or numeric
4402 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4403 L<Date::Parse> for conversion functions. The empty string can be passed
4404 to disable that time constraint completely.
4406 Available options are:
4410 =item unapplied_date
4412 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)
4417 set to true to remove all customer comparison clauses, for totals
4422 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4427 JOIN clause (typically used with the total option)
4431 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4432 time will be ignored. Note that START_TIME and END_TIME only limit the date
4433 range for invoices and I<unapplied> payments, credits, and refunds.
4439 sub balance_date_sql {
4440 my( $class, $start, $end, %opt ) = @_;
4442 my $cutoff = $opt{'cutoff'};
4444 my $owed = FS::cust_bill->owed_sql($cutoff);
4445 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4446 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4447 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4449 my $j = $opt{'join'} || '';
4451 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4452 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4453 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4454 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4456 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4457 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4458 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4459 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4464 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4466 Returns an SQL fragment to retreive the total unapplied payments for this
4467 customer, only considering payments with date earlier than START_TIME, and
4468 optionally not later than END_TIME.
4470 Times are specified as SQL fragments or numeric
4471 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4472 L<Date::Parse> for conversion functions. The empty string can be passed
4473 to disable that time constraint completely.
4475 Available options are:
4479 sub unapplied_payments_date_sql {
4480 my( $class, $start, $end, %opt ) = @_;
4482 my $cutoff = $opt{'cutoff'};
4484 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4486 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4487 'unapplied_date'=>1 );
4489 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4492 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4494 Helper method for balance_date_sql; name (and usage) subject to change
4495 (suggestions welcome).
4497 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4498 cust_refund, cust_credit or cust_pay).
4500 If TABLE is "cust_bill" or the unapplied_date option is true, only
4501 considers records with date earlier than START_TIME, and optionally not
4502 later than END_TIME .
4506 sub _money_table_where {
4507 my( $class, $table, $start, $end, %opt ) = @_;
4510 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4511 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4512 push @where, "$table._date <= $start" if defined($start) && length($start);
4513 push @where, "$table._date > $end" if defined($end) && length($end);
4515 push @where, @{$opt{'where'}} if $opt{'where'};
4516 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4522 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4523 use FS::cust_main::Search;
4526 FS::cust_main::Search->search(@_);
4541 #warn join('-',keys %$param);
4542 my $fh = $param->{filehandle};
4543 my $agentnum = $param->{agentnum};
4544 my $format = $param->{format};
4546 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4549 if ( $format eq 'simple' ) {
4550 @fields = qw( custnum agent_custid amount pkg );
4552 die "unknown format $format";
4555 eval "use Text::CSV_XS;";
4558 my $csv = new Text::CSV_XS;
4565 local $SIG{HUP} = 'IGNORE';
4566 local $SIG{INT} = 'IGNORE';
4567 local $SIG{QUIT} = 'IGNORE';
4568 local $SIG{TERM} = 'IGNORE';
4569 local $SIG{TSTP} = 'IGNORE';
4570 local $SIG{PIPE} = 'IGNORE';
4572 my $oldAutoCommit = $FS::UID::AutoCommit;
4573 local $FS::UID::AutoCommit = 0;
4576 #while ( $columns = $csv->getline($fh) ) {
4578 while ( defined($line=<$fh>) ) {
4580 $csv->parse($line) or do {
4581 $dbh->rollback if $oldAutoCommit;
4582 return "can't parse: ". $csv->error_input();
4585 my @columns = $csv->fields();
4586 #warn join('-',@columns);
4589 foreach my $field ( @fields ) {
4590 $row{$field} = shift @columns;
4593 if ( $row{custnum} && $row{agent_custid} ) {
4594 dbh->rollback if $oldAutoCommit;
4595 return "can't specify custnum with agent_custid $row{agent_custid}";
4599 if ( $row{agent_custid} && $agentnum ) {
4600 %hash = ( 'agent_custid' => $row{agent_custid},
4601 'agentnum' => $agentnum,
4605 if ( $row{custnum} ) {
4606 %hash = ( 'custnum' => $row{custnum} );
4609 unless ( scalar(keys %hash) ) {
4610 $dbh->rollback if $oldAutoCommit;
4611 return "can't find customer without custnum or agent_custid and agentnum";
4614 my $cust_main = qsearchs('cust_main', { %hash } );
4615 unless ( $cust_main ) {
4616 $dbh->rollback if $oldAutoCommit;
4617 my $custnum = $row{custnum} || $row{agent_custid};
4618 return "unknown custnum $custnum";
4621 if ( $row{'amount'} > 0 ) {
4622 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4624 $dbh->rollback if $oldAutoCommit;
4628 } elsif ( $row{'amount'} < 0 ) {
4629 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4632 $dbh->rollback if $oldAutoCommit;
4642 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4644 return "Empty file!" unless $imported;
4650 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4652 Deprecated. Use event notification and message templates
4653 (L<FS::msg_template>) instead.
4655 Sends a templated email notification to the customer (see L<Text::Template>).
4657 OPTIONS is a hash and may include
4659 I<from> - the email sender (default is invoice_from)
4661 I<to> - comma-separated scalar or arrayref of recipients
4662 (default is invoicing_list)
4664 I<subject> - The subject line of the sent email notification
4665 (default is "Notice from company_name")
4667 I<extra_fields> - a hashref of name/value pairs which will be substituted
4670 The following variables are vavailable in the template.
4672 I<$first> - the customer first name
4673 I<$last> - the customer last name
4674 I<$company> - the customer company
4675 I<$payby> - a description of the method of payment for the customer
4676 # would be nice to use FS::payby::shortname
4677 I<$payinfo> - the account information used to collect for this customer
4678 I<$expdate> - the expiration of the customer payment in seconds from epoch
4683 my ($self, $template, %options) = @_;
4685 return unless $conf->exists($template);
4687 my $from = $conf->config('invoice_from', $self->agentnum)
4688 if $conf->exists('invoice_from', $self->agentnum);
4689 $from = $options{from} if exists($options{from});
4691 my $to = join(',', $self->invoicing_list_emailonly);
4692 $to = $options{to} if exists($options{to});
4694 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4695 if $conf->exists('company_name', $self->agentnum);
4696 $subject = $options{subject} if exists($options{subject});
4698 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4699 SOURCE => [ map "$_\n",
4700 $conf->config($template)]
4702 or die "can't create new Text::Template object: Text::Template::ERROR";
4703 $notify_template->compile()
4704 or die "can't compile template: Text::Template::ERROR";
4706 $FS::notify_template::_template::company_name =
4707 $conf->config('company_name', $self->agentnum);
4708 $FS::notify_template::_template::company_address =
4709 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4711 my $paydate = $self->paydate || '2037-12-31';
4712 $FS::notify_template::_template::first = $self->first;
4713 $FS::notify_template::_template::last = $self->last;
4714 $FS::notify_template::_template::company = $self->company;
4715 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4716 my $payby = $self->payby;
4717 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4718 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4720 #credit cards expire at the end of the month/year of their exp date
4721 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4722 $FS::notify_template::_template::payby = 'credit card';
4723 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4724 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4726 }elsif ($payby eq 'COMP') {
4727 $FS::notify_template::_template::payby = 'complimentary account';
4729 $FS::notify_template::_template::payby = 'current method';
4731 $FS::notify_template::_template::expdate = $expire_time;
4733 for (keys %{$options{extra_fields}}){
4735 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4738 send_email(from => $from,
4740 subject => $subject,
4741 body => $notify_template->fill_in( PACKAGE =>
4742 'FS::notify_template::_template' ),
4747 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4749 Generates a templated notification to the customer (see L<Text::Template>).
4751 OPTIONS is a hash and may include
4753 I<extra_fields> - a hashref of name/value pairs which will be substituted
4754 into the template. These values may override values mentioned below
4755 and those from the customer record.
4757 The following variables are available in the template instead of or in addition
4758 to the fields of the customer record.
4760 I<$payby> - a description of the method of payment for the customer
4761 # would be nice to use FS::payby::shortname
4762 I<$payinfo> - the masked account information used to collect for this customer
4763 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4764 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4768 # a lot like cust_bill::print_latex
4769 sub generate_letter {
4770 my ($self, $template, %options) = @_;
4772 return unless $conf->exists($template);
4774 my $letter_template = new Text::Template
4776 SOURCE => [ map "$_\n", $conf->config($template)],
4777 DELIMITERS => [ '[@--', '--@]' ],
4779 or die "can't create new Text::Template object: Text::Template::ERROR";
4781 $letter_template->compile()
4782 or die "can't compile template: Text::Template::ERROR";
4784 my %letter_data = map { $_ => $self->$_ } $self->fields;
4785 $letter_data{payinfo} = $self->mask_payinfo;
4787 #my $paydate = $self->paydate || '2037-12-31';
4788 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4790 my $payby = $self->payby;
4791 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4792 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4794 #credit cards expire at the end of the month/year of their exp date
4795 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4796 $letter_data{payby} = 'credit card';
4797 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4798 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4800 }elsif ($payby eq 'COMP') {
4801 $letter_data{payby} = 'complimentary account';
4803 $letter_data{payby} = 'current method';
4805 $letter_data{expdate} = $expire_time;
4807 for (keys %{$options{extra_fields}}){
4808 $letter_data{$_} = $options{extra_fields}->{$_};
4811 unless(exists($letter_data{returnaddress})){
4812 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4813 $self->agent_template)
4815 if ( length($retadd) ) {
4816 $letter_data{returnaddress} = $retadd;
4817 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4818 $letter_data{returnaddress} =
4819 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4823 ( $conf->config('company_name', $self->agentnum),
4824 $conf->config('company_address', $self->agentnum),
4828 $letter_data{returnaddress} = '~';
4832 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4834 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4836 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4838 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4842 ) or die "can't open temp file: $!\n";
4843 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4844 or die "can't write temp file: $!\n";
4846 $letter_data{'logo_file'} = $lh->filename;
4848 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4852 ) or die "can't open temp file: $!\n";
4854 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4856 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4857 return ($1, $letter_data{'logo_file'});
4861 =item print_ps TEMPLATE
4863 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4869 my($file, $lfile) = $self->generate_letter(@_);
4870 my $ps = FS::Misc::generate_ps($file);
4871 unlink($file.'.tex');
4877 =item print TEMPLATE
4879 Prints the filled in template.
4881 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4885 sub queueable_print {
4888 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4889 or die "invalid customer number: " . $opt{custvnum};
4891 my $error = $self->print( $opt{template} );
4892 die $error if $error;
4896 my ($self, $template) = (shift, shift);
4897 do_print [ $self->print_ps($template) ];
4900 #these three subs should just go away once agent stuff is all config overrides
4902 sub agent_template {
4904 $self->_agent_plandata('agent_templatename');
4907 sub agent_invoice_from {
4909 $self->_agent_plandata('agent_invoice_from');
4912 sub _agent_plandata {
4913 my( $self, $option ) = @_;
4915 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4916 #agent-specific Conf
4918 use FS::part_event::Condition;
4920 my $agentnum = $self->agentnum;
4922 my $regexp = regexp_sql();
4924 my $part_event_option =
4926 'select' => 'part_event_option.*',
4927 'table' => 'part_event_option',
4929 LEFT JOIN part_event USING ( eventpart )
4930 LEFT JOIN part_event_option AS peo_agentnum
4931 ON ( part_event.eventpart = peo_agentnum.eventpart
4932 AND peo_agentnum.optionname = 'agentnum'
4933 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4935 LEFT JOIN part_event_condition
4936 ON ( part_event.eventpart = part_event_condition.eventpart
4937 AND part_event_condition.conditionname = 'cust_bill_age'
4939 LEFT JOIN part_event_condition_option
4940 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4941 AND part_event_condition_option.optionname = 'age'
4944 #'hashref' => { 'optionname' => $option },
4945 #'hashref' => { 'part_event_option.optionname' => $option },
4947 " WHERE part_event_option.optionname = ". dbh->quote($option).
4948 " AND action = 'cust_bill_send_agent' ".
4949 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4950 " AND peo_agentnum.optionname = 'agentnum' ".
4951 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4953 CASE WHEN part_event_condition_option.optionname IS NULL
4955 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4957 , part_event.weight".
4961 unless ( $part_event_option ) {
4962 return $self->agent->invoice_template || ''
4963 if $option eq 'agent_templatename';
4967 $part_event_option->optionvalue;
4971 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4973 Subroutine (not a method), designed to be called from the queue.
4975 Takes a list of options and values.
4977 Pulls up the customer record via the custnum option and calls bill_and_collect.
4982 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4984 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4985 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4987 $cust_main->bill_and_collect( %args );
4990 sub process_bill_and_collect {
4992 my $param = thaw(decode_base64(shift));
4993 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4994 or die "custnum '$param->{custnum}' not found!\n";
4995 $param->{'job'} = $job;
4996 $param->{'fatal'} = 1; # runs from job queue, will be caught
4997 $param->{'retry'} = 1;
4999 $cust_main->bill_and_collect( %$param );
5002 =item process_censustract_update CUSTNUM
5004 Queueable function to update the census tract to the current year (as set in
5005 the 'census_year' configuration variable) and retrieve the new tract code.
5009 sub process_censustract_update {
5010 eval "use FS::Misc::Geo qw(get_censustract)";
5012 my $custnum = shift;
5013 my $cust_main = qsearchs( 'cust_main', { custnum => $custnum })
5014 or die "custnum '$custnum' not found!\n";
5016 my $new_year = $conf->config('census_year') or return;
5017 my $new_tract = get_censustract({ $cust_main->location_hash }, $new_year);
5018 if ( $new_tract =~ /^\d/ ) {
5019 # then it's a tract code
5020 $cust_main->set('censustract', $new_tract);
5021 $cust_main->set('censusyear', $new_year);
5023 local($ignore_expired_card) = 1;
5024 local($ignore_illegal_zip) = 1;
5025 local($ignore_banned_card) = 1;
5026 local($skip_fuzzyfiles) = 1;
5027 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5028 my $error = $cust_main->replace;
5029 die $error if $error;
5032 # it's an error message
5038 sub _upgrade_data { #class method
5039 my ($class, %opts) = @_;
5042 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5043 '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',
5045 # fix yyyy-m-dd formatted paydates
5046 if ( driver_name =~ /^mysql/i ) {
5048 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5050 else { # the SQL standard
5052 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5055 push @statements, #fix the weird BILL with a cc# in payinfo problem
5057 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5059 foreach my $sql ( @statements ) {
5060 my $sth = dbh->prepare($sql) or die dbh->errstr;
5061 $sth->execute or die $sth->errstr;
5064 local($ignore_expired_card) = 1;
5065 local($ignore_illegal_zip) = 1;
5066 local($ignore_banned_card) = 1;
5067 local($skip_fuzzyfiles) = 1;
5068 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5069 $class->_upgrade_otaker(%opts);
5079 The delete method should possibly take an FS::cust_main object reference
5080 instead of a scalar customer number.
5082 Bill and collect options should probably be passed as references instead of a
5085 There should probably be a configuration file with a list of allowed credit
5088 No multiple currency support (probably a larger project than just this module).
5090 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5092 Birthdates rely on negative epoch values.
5094 The payby for card/check batches is broken. With mixed batching, bad
5097 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5101 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5102 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5103 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.