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
17 $skip_fuzzyfiles @fuzzyfields
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);
44 use FS::cust_pay_pending;
45 use FS::cust_pay_void;
46 use FS::cust_pay_batch;
49 use FS::part_referral;
50 use FS::cust_main_county;
51 use FS::cust_location;
53 use FS::cust_main_exemption;
54 use FS::cust_tax_adjustment;
55 use FS::cust_tax_location;
57 use FS::cust_main_invoice;
59 use FS::prepay_credit;
65 use FS::payment_gateway;
66 use FS::agent_payment_gateway;
68 use FS::cust_main_note;
69 use FS::cust_attachment;
73 # 1 is mostly method/subroutine entry and options
74 # 2 traces progress of some operations
75 # 3 is even more information including possibly sensitive data
77 $me = '[FS::cust_main]';
80 $ignore_expired_card = 0;
81 $ignore_illegal_zip = 0;
82 $ignore_banned_card = 0;
85 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
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->auto_agent_custid()
469 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
471 my $error = $self->SUPER::insert;
473 $dbh->rollback if $oldAutoCommit;
474 #return "inserting cust_main record (transaction rolled back): $error";
478 warn " setting invoicing list\n"
481 if ( $invoicing_list ) {
482 $error = $self->check_invoicing_list( $invoicing_list );
484 $dbh->rollback if $oldAutoCommit;
485 #return "checking invoicing_list (transaction rolled back): $error";
488 $self->invoicing_list( $invoicing_list );
491 warn " setting customer tags\n"
494 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
495 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
496 'custnum' => $self->custnum };
497 my $error = $cust_tag->insert;
499 $dbh->rollback if $oldAutoCommit;
504 my $prospectnum = delete $options{'prospectnum'};
505 if ( $prospectnum ) {
507 warn " moving contacts and locations from prospect $prospectnum\n"
511 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
512 unless ( $prospect_main ) {
513 $dbh->rollback if $oldAutoCommit;
514 return "Unknown prospectnum $prospectnum";
516 $prospect_main->custnum($self->custnum);
517 $prospect_main->disabled('Y');
518 my $error = $prospect_main->replace;
520 $dbh->rollback if $oldAutoCommit;
524 my @contact = $prospect_main->contact;
525 my @cust_location = $prospect_main->cust_location;
526 my @qual = $prospect_main->qual;
528 foreach my $r ( @contact, @cust_location, @qual ) {
530 $r->custnum($self->custnum);
531 my $error = $r->replace;
533 $dbh->rollback if $oldAutoCommit;
540 warn " setting cust_main_exemption\n"
543 my $tax_exemption = delete $options{'tax_exemption'};
544 if ( $tax_exemption ) {
545 foreach my $taxname ( @$tax_exemption ) {
546 my $cust_main_exemption = new FS::cust_main_exemption {
547 'custnum' => $self->custnum,
548 'taxname' => $taxname,
550 my $error = $cust_main_exemption->insert;
552 $dbh->rollback if $oldAutoCommit;
553 return "inserting cust_main_exemption (transaction rolled back): $error";
558 if ( $self->can('start_copy_skel') ) {
559 my $error = $self->start_copy_skel;
561 $dbh->rollback if $oldAutoCommit;
566 warn " ordering packages\n"
569 $error = $self->order_pkgs( $cust_pkgs,
571 'seconds_ref' => \$seconds,
572 'upbytes_ref' => \$upbytes,
573 'downbytes_ref' => \$downbytes,
574 'totalbytes_ref' => \$totalbytes,
577 $dbh->rollback if $oldAutoCommit;
582 $dbh->rollback if $oldAutoCommit;
583 return "No svc_acct record to apply pre-paid time";
585 if ( $upbytes || $downbytes || $totalbytes ) {
586 $dbh->rollback if $oldAutoCommit;
587 return "No svc_acct record to apply pre-paid data";
591 warn " inserting initial $payby payment of $amount\n"
593 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
595 $dbh->rollback if $oldAutoCommit;
596 return "inserting payment (transaction rolled back): $error";
600 unless ( $import || $skip_fuzzyfiles ) {
601 warn " queueing fuzzyfiles update\n"
603 $error = $self->queue_fuzzyfiles_update;
605 $dbh->rollback if $oldAutoCommit;
606 return "updating fuzzy search cache: $error";
611 warn " exporting\n" if $DEBUG > 1;
613 my $export_args = $options{'export_args'} || [];
616 map qsearch( 'part_export', {exportnum=>$_} ),
617 $conf->config('cust_main-exports'); #, $agentnum
619 foreach my $part_export ( @part_export ) {
620 my $error = $part_export->export_insert($self, @$export_args);
622 $dbh->rollback if $oldAutoCommit;
623 return "exporting to ". $part_export->exporttype.
624 " (transaction rolled back): $error";
628 #foreach my $depend_jobnum ( @$depend_jobnums ) {
629 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
631 # foreach my $jobnum ( @jobnums ) {
632 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
633 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
635 # my $error = $queue->depend_insert($depend_jobnum);
637 # $dbh->rollback if $oldAutoCommit;
638 # return "error queuing job dependancy: $error";
645 #if ( exists $options{'jobnums'} ) {
646 # push @{ $options{'jobnums'} }, @jobnums;
649 warn " insert complete; committing transaction\n"
652 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
657 use File::CounterFile;
658 sub auto_agent_custid {
661 my $format = $conf->config('cust_main-auto_agent_custid');
663 if ( $format eq '1YMMXXXXXXXX' ) {
665 my $counter = new File::CounterFile 'cust_main.agent_custid';
668 my $ym = 100000000000 + time2str('%y%m00000000', time);
669 if ( $ym > $counter->value ) {
670 $counter->{'value'} = $agent_custid = $ym;
671 $counter->{'updated'} = 1;
673 $agent_custid = $counter->inc;
679 die "Unknown cust_main-auto_agent_custid format: $format";
682 $self->agent_custid($agent_custid);
686 =item PACKAGE METHODS
688 Documentation on customer package methods has been moved to
689 L<FS::cust_main::Packages>.
691 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
693 Recharges this (existing) customer with the specified prepaid card (see
694 L<FS::prepay_credit>), specified either by I<identifier> or as an
695 FS::prepay_credit object. If there is an error, returns the error, otherwise
698 Optionally, five scalar references can be passed as well. They will have their
699 values filled in with the amount, number of seconds, and number of upload,
700 download, and total bytes applied by this prepaid card.
704 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
705 #the only place that uses these args
706 sub recharge_prepay {
707 my( $self, $prepay_credit, $amountref, $secondsref,
708 $upbytesref, $downbytesref, $totalbytesref ) = @_;
710 local $SIG{HUP} = 'IGNORE';
711 local $SIG{INT} = 'IGNORE';
712 local $SIG{QUIT} = 'IGNORE';
713 local $SIG{TERM} = 'IGNORE';
714 local $SIG{TSTP} = 'IGNORE';
715 local $SIG{PIPE} = 'IGNORE';
717 my $oldAutoCommit = $FS::UID::AutoCommit;
718 local $FS::UID::AutoCommit = 0;
721 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
723 my $error = $self->get_prepay( $prepay_credit,
724 'amount_ref' => \$amount,
725 'seconds_ref' => \$seconds,
726 'upbytes_ref' => \$upbytes,
727 'downbytes_ref' => \$downbytes,
728 'totalbytes_ref' => \$totalbytes,
730 || $self->increment_seconds($seconds)
731 || $self->increment_upbytes($upbytes)
732 || $self->increment_downbytes($downbytes)
733 || $self->increment_totalbytes($totalbytes)
734 || $self->insert_cust_pay_prepay( $amount,
736 ? $prepay_credit->identifier
741 $dbh->rollback if $oldAutoCommit;
745 if ( defined($amountref) ) { $$amountref = $amount; }
746 if ( defined($secondsref) ) { $$secondsref = $seconds; }
747 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
748 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
749 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
751 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
756 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
758 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
759 specified either by I<identifier> or as an FS::prepay_credit object.
761 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
762 incremented by the values of the prepaid card.
764 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
765 check or set this customer's I<agentnum>.
767 If there is an error, returns the error, otherwise returns false.
773 my( $self, $prepay_credit, %opt ) = @_;
775 local $SIG{HUP} = 'IGNORE';
776 local $SIG{INT} = 'IGNORE';
777 local $SIG{QUIT} = 'IGNORE';
778 local $SIG{TERM} = 'IGNORE';
779 local $SIG{TSTP} = 'IGNORE';
780 local $SIG{PIPE} = 'IGNORE';
782 my $oldAutoCommit = $FS::UID::AutoCommit;
783 local $FS::UID::AutoCommit = 0;
786 unless ( ref($prepay_credit) ) {
788 my $identifier = $prepay_credit;
790 $prepay_credit = qsearchs(
792 { 'identifier' => $identifier },
797 unless ( $prepay_credit ) {
798 $dbh->rollback if $oldAutoCommit;
799 return "Invalid prepaid card: ". $identifier;
804 if ( $prepay_credit->agentnum ) {
805 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
806 $dbh->rollback if $oldAutoCommit;
807 return "prepaid card not valid for agent ". $self->agentnum;
809 $self->agentnum($prepay_credit->agentnum);
812 my $error = $prepay_credit->delete;
814 $dbh->rollback if $oldAutoCommit;
815 return "removing prepay_credit (transaction rolled back): $error";
818 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
819 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
821 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
826 =item increment_upbytes SECONDS
828 Updates this customer's single or primary account (see L<FS::svc_acct>) by
829 the specified number of upbytes. If there is an error, returns the error,
830 otherwise returns false.
834 sub increment_upbytes {
835 _increment_column( shift, 'upbytes', @_);
838 =item increment_downbytes SECONDS
840 Updates this customer's single or primary account (see L<FS::svc_acct>) by
841 the specified number of downbytes. If there is an error, returns the error,
842 otherwise returns false.
846 sub increment_downbytes {
847 _increment_column( shift, 'downbytes', @_);
850 =item increment_totalbytes SECONDS
852 Updates this customer's single or primary account (see L<FS::svc_acct>) by
853 the specified number of totalbytes. If there is an error, returns the error,
854 otherwise returns false.
858 sub increment_totalbytes {
859 _increment_column( shift, 'totalbytes', @_);
862 =item increment_seconds SECONDS
864 Updates this customer's single or primary account (see L<FS::svc_acct>) by
865 the specified number of seconds. If there is an error, returns the error,
866 otherwise returns false.
870 sub increment_seconds {
871 _increment_column( shift, 'seconds', @_);
874 =item _increment_column AMOUNT
876 Updates this customer's single or primary account (see L<FS::svc_acct>) by
877 the specified number of seconds or bytes. If there is an error, returns
878 the error, otherwise returns false.
882 sub _increment_column {
883 my( $self, $column, $amount ) = @_;
884 warn "$me increment_column called: $column, $amount\n"
887 return '' unless $amount;
889 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
890 $self->ncancelled_pkgs;
893 return 'No packages with primary or single services found'.
894 ' to apply pre-paid time';
895 } elsif ( scalar(@cust_pkg) > 1 ) {
896 #maybe have a way to specify the package/account?
897 return 'Multiple packages found to apply pre-paid time';
900 my $cust_pkg = $cust_pkg[0];
901 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
905 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
908 return 'No account found to apply pre-paid time';
909 } elsif ( scalar(@cust_svc) > 1 ) {
910 return 'Multiple accounts found to apply pre-paid time';
913 my $svc_acct = $cust_svc[0]->svc_x;
914 warn " found service svcnum ". $svc_acct->pkgnum.
915 ' ('. $svc_acct->email. ")\n"
918 $column = "increment_$column";
919 $svc_acct->$column($amount);
923 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
925 Inserts a prepayment in the specified amount for this customer. An optional
926 second argument can specify the prepayment identifier for tracking purposes.
927 If there is an error, returns the error, otherwise returns false.
931 sub insert_cust_pay_prepay {
932 shift->insert_cust_pay('PREP', @_);
935 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
937 Inserts a cash payment in the specified amount for this customer. An optional
938 second argument can specify the payment identifier for tracking purposes.
939 If there is an error, returns the error, otherwise returns false.
943 sub insert_cust_pay_cash {
944 shift->insert_cust_pay('CASH', @_);
947 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
949 Inserts a Western Union payment in the specified amount for this customer. An
950 optional second argument can specify the prepayment identifier for tracking
951 purposes. If there is an error, returns the error, otherwise returns false.
955 sub insert_cust_pay_west {
956 shift->insert_cust_pay('WEST', @_);
959 sub insert_cust_pay {
960 my( $self, $payby, $amount ) = splice(@_, 0, 3);
961 my $payinfo = scalar(@_) ? shift : '';
963 my $cust_pay = new FS::cust_pay {
964 'custnum' => $self->custnum,
965 'paid' => sprintf('%.2f', $amount),
966 #'_date' => #date the prepaid card was purchased???
968 'payinfo' => $payinfo,
976 This method is deprecated. See the I<depend_jobnum> option to the insert and
977 order_pkgs methods for a better way to defer provisioning.
979 Re-schedules all exports by calling the B<reexport> method of all associated
980 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
981 otherwise returns false.
988 carp "WARNING: FS::cust_main::reexport is deprectated; ".
989 "use the depend_jobnum option to insert or order_pkgs to delay export";
991 local $SIG{HUP} = 'IGNORE';
992 local $SIG{INT} = 'IGNORE';
993 local $SIG{QUIT} = 'IGNORE';
994 local $SIG{TERM} = 'IGNORE';
995 local $SIG{TSTP} = 'IGNORE';
996 local $SIG{PIPE} = 'IGNORE';
998 my $oldAutoCommit = $FS::UID::AutoCommit;
999 local $FS::UID::AutoCommit = 0;
1002 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1003 my $error = $cust_pkg->reexport;
1005 $dbh->rollback if $oldAutoCommit;
1010 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1015 =item delete [ OPTION => VALUE ... ]
1017 This deletes the customer. If there is an error, returns the error, otherwise
1020 This will completely remove all traces of the customer record. This is not
1021 what you want when a customer cancels service; for that, cancel all of the
1022 customer's packages (see L</cancel>).
1024 If the customer has any uncancelled packages, you need to pass a new (valid)
1025 customer number for those packages to be transferred to, as the "new_customer"
1026 option. Cancelled packages will be deleted. Did I mention that this is NOT
1027 what you want when a customer cancels service and that you really should be
1028 looking at L<FS::cust_pkg/cancel>?
1030 You can't delete a customer with invoices (see L<FS::cust_bill>),
1031 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1032 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1033 set the "delete_financials" option to a true value.
1038 my( $self, %opt ) = @_;
1040 local $SIG{HUP} = 'IGNORE';
1041 local $SIG{INT} = 'IGNORE';
1042 local $SIG{QUIT} = 'IGNORE';
1043 local $SIG{TERM} = 'IGNORE';
1044 local $SIG{TSTP} = 'IGNORE';
1045 local $SIG{PIPE} = 'IGNORE';
1047 my $oldAutoCommit = $FS::UID::AutoCommit;
1048 local $FS::UID::AutoCommit = 0;
1051 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1052 $dbh->rollback if $oldAutoCommit;
1053 return "Can't delete a master agent customer";
1056 #use FS::access_user
1057 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1058 $dbh->rollback if $oldAutoCommit;
1059 return "Can't delete a master employee customer";
1062 tie my %financial_tables, 'Tie::IxHash',
1063 'cust_bill' => 'invoices',
1064 'cust_statement' => 'statements',
1065 'cust_credit' => 'credits',
1066 'cust_pay' => 'payments',
1067 'cust_refund' => 'refunds',
1070 foreach my $table ( keys %financial_tables ) {
1072 my @records = $self->$table();
1074 if ( @records && ! $opt{'delete_financials'} ) {
1075 $dbh->rollback if $oldAutoCommit;
1076 return "Can't delete a customer with ". $financial_tables{$table};
1079 foreach my $record ( @records ) {
1080 my $error = $record->delete;
1082 $dbh->rollback if $oldAutoCommit;
1083 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1089 my @cust_pkg = $self->ncancelled_pkgs;
1091 my $new_custnum = $opt{'new_custnum'};
1092 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1093 $dbh->rollback if $oldAutoCommit;
1094 return "Invalid new customer number: $new_custnum";
1096 foreach my $cust_pkg ( @cust_pkg ) {
1097 my %hash = $cust_pkg->hash;
1098 $hash{'custnum'} = $new_custnum;
1099 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1100 my $error = $new_cust_pkg->replace($cust_pkg,
1101 options => { $cust_pkg->options },
1104 $dbh->rollback if $oldAutoCommit;
1109 my @cancelled_cust_pkg = $self->all_pkgs;
1110 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1111 my $error = $cust_pkg->delete;
1113 $dbh->rollback if $oldAutoCommit;
1118 #cust_tax_adjustment in financials?
1119 #cust_pay_pending? ouch
1121 foreach my $table (qw(
1122 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1123 cust_location cust_main_note cust_tax_adjustment
1124 cust_pay_void cust_pay_batch queue cust_tax_exempt
1126 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1127 my $error = $record->delete;
1129 $dbh->rollback if $oldAutoCommit;
1135 my $sth = $dbh->prepare(
1136 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1138 my $errstr = $dbh->errstr;
1139 $dbh->rollback if $oldAutoCommit;
1142 $sth->execute($self->custnum) or do {
1143 my $errstr = $sth->errstr;
1144 $dbh->rollback if $oldAutoCommit;
1150 my $ticket_dbh = '';
1151 if ($conf->config('ticket_system') eq 'RT_Internal') {
1153 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1154 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1155 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1156 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1159 if ( $ticket_dbh ) {
1161 my $ticket_sth = $ticket_dbh->prepare(
1162 'DELETE FROM Links WHERE Target = ?'
1164 my $errstr = $ticket_dbh->errstr;
1165 $dbh->rollback if $oldAutoCommit;
1168 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1170 my $errstr = $ticket_sth->errstr;
1171 $dbh->rollback if $oldAutoCommit;
1175 #check and see if the customer is the only link on the ticket, and
1176 #if so, set the ticket to deleted status in RT?
1177 #maybe someday, for now this will at least fix tickets not displaying
1181 #delete the customer record
1183 my $error = $self->SUPER::delete;
1185 $dbh->rollback if $oldAutoCommit;
1189 # cust_main exports!
1191 #my $export_args = $options{'export_args'} || [];
1194 map qsearch( 'part_export', {exportnum=>$_} ),
1195 $conf->config('cust_main-exports'); #, $agentnum
1197 foreach my $part_export ( @part_export ) {
1198 my $error = $part_export->export_delete( $self ); #, @$export_args);
1200 $dbh->rollback if $oldAutoCommit;
1201 return "exporting to ". $part_export->exporttype.
1202 " (transaction rolled back): $error";
1206 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1211 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1213 This merges this customer into the provided new custnum, and then deletes the
1214 customer. If there is an error, returns the error, otherwise returns false.
1216 The source customer's name, company name, phone numbers, agent,
1217 referring customer, customer class, advertising source, order taker, and
1218 billing information (except balance) are discarded.
1220 All packages are moved to the target customer. Packages with package locations
1221 are preserved. Packages without package locations are moved to a new package
1222 location with the source customer's service/shipping address.
1224 All invoices, statements, payments, credits and refunds are moved to the target
1225 customer. The source customer's balance is added to the target customer.
1227 All notes, attachments, tickets and customer tags are moved to the target
1230 Change history is not currently moved.
1235 my( $self, $new_custnum, %opt ) = @_;
1237 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1239 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1240 return "Invalid new customer number: $new_custnum";
1243 local $SIG{HUP} = 'IGNORE';
1244 local $SIG{INT} = 'IGNORE';
1245 local $SIG{QUIT} = 'IGNORE';
1246 local $SIG{TERM} = 'IGNORE';
1247 local $SIG{TSTP} = 'IGNORE';
1248 local $SIG{PIPE} = 'IGNORE';
1250 my $oldAutoCommit = $FS::UID::AutoCommit;
1251 local $FS::UID::AutoCommit = 0;
1254 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1255 $dbh->rollback if $oldAutoCommit;
1256 return "Can't merge a master agent customer";
1259 #use FS::access_user
1260 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1261 $dbh->rollback if $oldAutoCommit;
1262 return "Can't merge a master employee customer";
1265 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1266 'status' => { op=>'!=', value=>'done' },
1270 $dbh->rollback if $oldAutoCommit;
1271 return "Can't merge a customer with pending payments";
1274 tie my %financial_tables, 'Tie::IxHash',
1275 'cust_bill' => 'invoices',
1276 'cust_statement' => 'statements',
1277 'cust_credit' => 'credits',
1278 'cust_pay' => 'payments',
1279 'cust_pay_void' => 'voided payments',
1280 'cust_refund' => 'refunds',
1283 foreach my $table ( keys %financial_tables ) {
1285 my @records = $self->$table();
1287 foreach my $record ( @records ) {
1288 $record->custnum($new_custnum);
1289 my $error = $record->replace;
1291 $dbh->rollback if $oldAutoCommit;
1292 return "Error merging ". $financial_tables{$table}. ": $error\n";
1298 my $name = $self->ship_name;
1300 my $locationnum = '';
1301 foreach my $cust_pkg ( $self->all_pkgs ) {
1302 $cust_pkg->custnum($new_custnum);
1304 unless ( $cust_pkg->locationnum ) {
1305 unless ( $locationnum ) {
1306 my $cust_location = new FS::cust_location {
1307 $self->location_hash,
1308 'custnum' => $new_custnum,
1310 my $error = $cust_location->insert;
1312 $dbh->rollback if $oldAutoCommit;
1315 $locationnum = $cust_location->locationnum;
1317 $cust_pkg->locationnum($locationnum);
1320 my $error = $cust_pkg->replace;
1322 $dbh->rollback if $oldAutoCommit;
1326 # add customer (ship) name to svc_phone.phone_name if blank
1327 my @cust_svc = $cust_pkg->cust_svc;
1328 foreach my $cust_svc (@cust_svc) {
1329 my($label, $value, $svcdb) = $cust_svc->label;
1330 next unless $svcdb eq 'svc_phone';
1331 my $svc_phone = $cust_svc->svc_x;
1332 next if $svc_phone->phone_name;
1333 $svc_phone->phone_name($name);
1334 my $error = $svc_phone->replace;
1336 $dbh->rollback if $oldAutoCommit;
1344 # cust_tax_exempt (texas tax exemptions)
1345 # cust_recon (some sort of not-well understood thing for OnPac)
1347 #these are moved over
1348 foreach my $table (qw(
1349 cust_tag cust_location contact cust_attachment cust_main_note
1350 cust_tax_adjustment cust_pay_batch queue
1352 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1353 $record->custnum($new_custnum);
1354 my $error = $record->replace;
1356 $dbh->rollback if $oldAutoCommit;
1362 #these aren't preserved
1363 foreach my $table (qw(
1364 cust_main_exemption cust_main_invoice
1366 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1367 my $error = $record->delete;
1369 $dbh->rollback if $oldAutoCommit;
1376 my $sth = $dbh->prepare(
1377 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1379 my $errstr = $dbh->errstr;
1380 $dbh->rollback if $oldAutoCommit;
1383 $sth->execute($new_custnum, $self->custnum) or do {
1384 my $errstr = $sth->errstr;
1385 $dbh->rollback if $oldAutoCommit;
1391 my $ticket_dbh = '';
1392 if ($conf->config('ticket_system') eq 'RT_Internal') {
1394 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1395 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1396 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1397 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1400 if ( $ticket_dbh ) {
1402 my $ticket_sth = $ticket_dbh->prepare(
1403 'UPDATE Links SET Target = ? WHERE Target = ?'
1405 my $errstr = $ticket_dbh->errstr;
1406 $dbh->rollback if $oldAutoCommit;
1409 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1410 'freeside://freeside/cust_main/'.$self->custnum)
1412 my $errstr = $ticket_sth->errstr;
1413 $dbh->rollback if $oldAutoCommit;
1419 #delete the customer record
1421 my $error = $self->delete;
1423 $dbh->rollback if $oldAutoCommit;
1427 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1432 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1435 Replaces the OLD_RECORD with this one in the database. If there is an error,
1436 returns the error, otherwise returns false.
1438 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1439 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1440 expected and rollback the entire transaction; it is not necessary to call
1441 check_invoicing_list first. Here's an example:
1443 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1445 Currently available options are: I<tax_exemption>.
1447 The I<tax_exemption> option can be set to an arrayref of tax names.
1448 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1455 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1457 : $self->replace_old;
1461 warn "$me replace called\n"
1464 my $curuser = $FS::CurrentUser::CurrentUser;
1465 if ( $self->payby eq 'COMP'
1466 && $self->payby ne $old->payby
1467 && ! $curuser->access_right('Complimentary customer')
1470 return "You are not permitted to create complimentary accounts.";
1473 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1474 && $conf->exists('enable_taxproducts')
1477 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1479 $self->set('geocode', '')
1480 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1481 && length($self->get($pre.'zip')) >= 10;
1484 local($ignore_expired_card) = 1
1485 if $old->payby =~ /^(CARD|DCRD)$/
1486 && $self->payby =~ /^(CARD|DCRD)$/
1487 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1489 local($ignore_banned_card) = 1
1490 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1491 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1492 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1494 local $SIG{HUP} = 'IGNORE';
1495 local $SIG{INT} = 'IGNORE';
1496 local $SIG{QUIT} = 'IGNORE';
1497 local $SIG{TERM} = 'IGNORE';
1498 local $SIG{TSTP} = 'IGNORE';
1499 local $SIG{PIPE} = 'IGNORE';
1501 my $oldAutoCommit = $FS::UID::AutoCommit;
1502 local $FS::UID::AutoCommit = 0;
1505 my $error = $self->SUPER::replace($old);
1508 $dbh->rollback if $oldAutoCommit;
1512 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1513 my $invoicing_list = shift @param;
1514 $error = $self->check_invoicing_list( $invoicing_list );
1516 $dbh->rollback if $oldAutoCommit;
1519 $self->invoicing_list( $invoicing_list );
1522 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1524 #this could be more efficient than deleting and re-inserting, if it matters
1525 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1526 my $error = $cust_tag->delete;
1528 $dbh->rollback if $oldAutoCommit;
1532 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1533 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1534 'custnum' => $self->custnum };
1535 my $error = $cust_tag->insert;
1537 $dbh->rollback if $oldAutoCommit;
1544 my %options = @param;
1546 my $tax_exemption = delete $options{'tax_exemption'};
1547 if ( $tax_exemption ) {
1549 my %cust_main_exemption =
1550 map { $_->taxname => $_ }
1551 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1553 foreach my $taxname ( @$tax_exemption ) {
1555 next if delete $cust_main_exemption{$taxname};
1557 my $cust_main_exemption = new FS::cust_main_exemption {
1558 'custnum' => $self->custnum,
1559 'taxname' => $taxname,
1561 my $error = $cust_main_exemption->insert;
1563 $dbh->rollback if $oldAutoCommit;
1564 return "inserting cust_main_exemption (transaction rolled back): $error";
1568 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1569 my $error = $cust_main_exemption->delete;
1571 $dbh->rollback if $oldAutoCommit;
1572 return "deleting cust_main_exemption (transaction rolled back): $error";
1578 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1579 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1580 && $self->get('payinfo') !~ /^99\d{14}$/
1582 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1587 # card/check/lec info has changed, want to retry realtime_ invoice events
1588 my $error = $self->retry_realtime;
1590 $dbh->rollback if $oldAutoCommit;
1595 unless ( $import || $skip_fuzzyfiles ) {
1596 $error = $self->queue_fuzzyfiles_update;
1598 $dbh->rollback if $oldAutoCommit;
1599 return "updating fuzzy search cache: $error";
1603 # cust_main exports!
1605 my $export_args = $options{'export_args'} || [];
1608 map qsearch( 'part_export', {exportnum=>$_} ),
1609 $conf->config('cust_main-exports'); #, $agentnum
1611 foreach my $part_export ( @part_export ) {
1612 my $error = $part_export->export_replace( $self, $old, @$export_args);
1614 $dbh->rollback if $oldAutoCommit;
1615 return "exporting to ". $part_export->exporttype.
1616 " (transaction rolled back): $error";
1620 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1625 =item queue_fuzzyfiles_update
1627 Used by insert & replace to update the fuzzy search cache
1631 sub queue_fuzzyfiles_update {
1634 local $SIG{HUP} = 'IGNORE';
1635 local $SIG{INT} = 'IGNORE';
1636 local $SIG{QUIT} = 'IGNORE';
1637 local $SIG{TERM} = 'IGNORE';
1638 local $SIG{TSTP} = 'IGNORE';
1639 local $SIG{PIPE} = 'IGNORE';
1641 my $oldAutoCommit = $FS::UID::AutoCommit;
1642 local $FS::UID::AutoCommit = 0;
1645 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1646 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1648 $dbh->rollback if $oldAutoCommit;
1649 return "queueing job (transaction rolled back): $error";
1652 if ( $self->ship_last ) {
1653 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1654 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1656 $dbh->rollback if $oldAutoCommit;
1657 return "queueing job (transaction rolled back): $error";
1661 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1668 Checks all fields to make sure this is a valid customer record. If there is
1669 an error, returns the error, otherwise returns false. Called by the insert
1670 and replace methods.
1677 warn "$me check BEFORE: \n". $self->_dump
1681 $self->ut_numbern('custnum')
1682 || $self->ut_number('agentnum')
1683 || $self->ut_textn('agent_custid')
1684 || $self->ut_number('refnum')
1685 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1686 || $self->ut_textn('custbatch')
1687 || $self->ut_name('last')
1688 || $self->ut_name('first')
1689 || $self->ut_snumbern('birthdate')
1690 || $self->ut_snumbern('signupdate')
1691 || $self->ut_textn('company')
1692 || $self->ut_text('address1')
1693 || $self->ut_textn('address2')
1694 || $self->ut_text('city')
1695 || $self->ut_textn('county')
1696 || $self->ut_textn('state')
1697 || $self->ut_country('country')
1698 || $self->ut_anything('comments')
1699 || $self->ut_numbern('referral_custnum')
1700 || $self->ut_textn('stateid')
1701 || $self->ut_textn('stateid_state')
1702 || $self->ut_textn('invoice_terms')
1703 || $self->ut_alphan('geocode')
1704 || $self->ut_floatn('cdr_termination_percentage')
1705 || $self->ut_floatn('credit_limit')
1706 || $self->ut_numbern('billday')
1707 || $self->ut_enum('edit_subject', [ '', 'Y' ] )
1708 || $self->ut_enum('calling_list_exempt', [ '', 'Y' ] )
1709 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1712 #barf. need message catalogs. i18n. etc.
1713 $error .= "Please select an advertising source."
1714 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1715 return $error if $error;
1717 return "Unknown agent"
1718 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1720 return "Unknown refnum"
1721 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1723 return "Unknown referring custnum: ". $self->referral_custnum
1724 unless ! $self->referral_custnum
1725 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1727 if ( $self->censustract ne '' ) {
1728 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1729 or return "Illegal census tract: ". $self->censustract;
1731 $self->censustract("$1.$2");
1734 if ( $self->ss eq '' ) {
1739 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1740 or return "Illegal social security number: ". $self->ss;
1741 $self->ss("$1-$2-$3");
1745 # bad idea to disable, causes billing to fail because of no tax rates later
1746 # except we don't fail any more
1747 unless ( $import ) {
1748 unless ( qsearch('cust_main_county', {
1749 'country' => $self->country,
1752 return "Unknown state/county/country: ".
1753 $self->state. "/". $self->county. "/". $self->country
1754 unless qsearch('cust_main_county',{
1755 'state' => $self->state,
1756 'county' => $self->county,
1757 'country' => $self->country,
1763 $self->ut_phonen('daytime', $self->country)
1764 || $self->ut_phonen('night', $self->country)
1765 || $self->ut_phonen('fax', $self->country)
1766 || $self->ut_phonen('mobile', $self->country)
1768 return $error if $error;
1770 unless ( $ignore_illegal_zip ) {
1771 $error = $self->ut_zip('zip', $self->country);
1772 return $error if $error;
1775 if ( $conf->exists('cust_main-require_phone')
1776 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1779 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1781 : FS::Msgcat::_gettext('daytime');
1782 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1784 : FS::Msgcat::_gettext('night');
1786 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1788 : FS::Msgcat::_gettext('mobile');
1790 return "$daytime_label, $night_label or $mobile_label is required"
1794 if ( $self->has_ship_address
1795 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1796 $self->addr_fields )
1800 $self->ut_name('ship_last')
1801 || $self->ut_name('ship_first')
1802 || $self->ut_textn('ship_company')
1803 || $self->ut_text('ship_address1')
1804 || $self->ut_textn('ship_address2')
1805 || $self->ut_text('ship_city')
1806 || $self->ut_textn('ship_county')
1807 || $self->ut_textn('ship_state')
1808 || $self->ut_country('ship_country')
1810 return $error if $error;
1812 #false laziness with above
1813 unless ( qsearchs('cust_main_county', {
1814 'country' => $self->ship_country,
1817 return "Unknown ship_state/ship_county/ship_country: ".
1818 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1819 unless qsearch('cust_main_county',{
1820 'state' => $self->ship_state,
1821 'county' => $self->ship_county,
1822 'country' => $self->ship_country,
1828 $self->ut_phonen('ship_daytime', $self->ship_country)
1829 || $self->ut_phonen('ship_night', $self->ship_country)
1830 || $self->ut_phonen('ship_fax', $self->ship_country)
1831 || $self->ut_phonen('ship_mobile', $self->ship_country)
1833 return $error if $error;
1835 unless ( $ignore_illegal_zip ) {
1836 $error = $self->ut_zip('ship_zip', $self->ship_country);
1837 return $error if $error;
1839 return "Unit # is required."
1840 if $self->ship_address2 =~ /^\s*$/
1841 && $conf->exists('cust_main-require_address2');
1843 } else { # ship_ info eq billing info, so don't store dup info in database
1845 $self->setfield("ship_$_", '')
1846 foreach $self->addr_fields;
1848 return "Unit # is required."
1849 if $self->address2 =~ /^\s*$/
1850 && $conf->exists('cust_main-require_address2');
1854 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1855 # or return "Illegal payby: ". $self->payby;
1857 FS::payby->can_payby($self->table, $self->payby)
1858 or return "Illegal payby: ". $self->payby;
1860 $error = $self->ut_numbern('paystart_month')
1861 || $self->ut_numbern('paystart_year')
1862 || $self->ut_numbern('payissue')
1863 || $self->ut_textn('paytype')
1865 return $error if $error;
1867 if ( $self->payip eq '' ) {
1870 $error = $self->ut_ip('payip');
1871 return $error if $error;
1874 # If it is encrypted and the private key is not availaible then we can't
1875 # check the credit card.
1876 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1878 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1880 my $payinfo = $self->payinfo;
1881 $payinfo =~ s/\D//g;
1882 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1883 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1885 $self->payinfo($payinfo);
1887 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1889 return gettext('unknown_card_type')
1890 if $self->payinfo !~ /^99\d{14}$/ #token
1891 && cardtype($self->payinfo) eq "Unknown";
1893 unless ( $ignore_banned_card ) {
1894 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1896 if ( $ban->bantype eq 'warn' ) {
1897 #or others depending on value of $ban->reason ?
1898 return '_duplicate_card'.
1899 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1900 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1901 ' (ban# '. $ban->bannum. ')'
1902 unless $self->override_ban_warn;
1904 return 'Banned credit card: banned on '.
1905 time2str('%a %h %o at %r', $ban->_date).
1906 ' by '. $ban->otaker.
1907 ' (ban# '. $ban->bannum. ')';
1912 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1913 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1914 $self->paycvv =~ /^(\d{4})$/
1915 or return "CVV2 (CID) for American Express cards is four digits.";
1918 $self->paycvv =~ /^(\d{3})$/
1919 or return "CVV2 (CVC2/CID) is three digits.";
1926 my $cardtype = cardtype($payinfo);
1927 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1929 return "Start date or issue number is required for $cardtype cards"
1930 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1932 return "Start month must be between 1 and 12"
1933 if $self->paystart_month
1934 and $self->paystart_month < 1 || $self->paystart_month > 12;
1936 return "Start year must be 1990 or later"
1937 if $self->paystart_year
1938 and $self->paystart_year < 1990;
1940 return "Issue number must be beween 1 and 99"
1942 and $self->payissue < 1 || $self->payissue > 99;
1945 $self->paystart_month('');
1946 $self->paystart_year('');
1947 $self->payissue('');
1950 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1952 my $payinfo = $self->payinfo;
1953 $payinfo =~ s/[^\d\@\.]//g;
1954 if ( $conf->exists('cust_main-require-bank-branch') ) {
1955 $payinfo =~ /^(\d+)\@(\d+)\.(\d+)$/ or return 'invalid echeck account@branch.bank';
1956 $payinfo = "$1\@$2.$3";
1957 } elsif ( $conf->exists('echeck-nonus') ) {
1958 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1959 $payinfo = "$1\@$2";
1961 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1962 $payinfo = "$1\@$2";
1964 $self->payinfo($payinfo);
1967 unless ( $ignore_banned_card ) {
1968 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1970 if ( $ban->bantype eq 'warn' ) {
1971 #or others depending on value of $ban->reason ?
1972 return '_duplicate_ach' unless $self->override_ban_warn;
1974 return 'Banned ACH account: banned on '.
1975 time2str('%a %h %o at %r', $ban->_date).
1976 ' by '. $ban->otaker.
1977 ' (ban# '. $ban->bannum. ')';
1982 } elsif ( $self->payby eq 'LECB' ) {
1984 my $payinfo = $self->payinfo;
1985 $payinfo =~ s/\D//g;
1986 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1988 $self->payinfo($payinfo);
1991 } elsif ( $self->payby eq 'BILL' ) {
1993 $error = $self->ut_textn('payinfo');
1994 return "Illegal P.O. number: ". $self->payinfo if $error;
1997 } elsif ( $self->payby eq 'COMP' ) {
1999 my $curuser = $FS::CurrentUser::CurrentUser;
2000 if ( ! $self->custnum
2001 && ! $curuser->access_right('Complimentary customer')
2004 return "You are not permitted to create complimentary accounts."
2007 $error = $self->ut_textn('payinfo');
2008 return "Illegal comp account issuer: ". $self->payinfo if $error;
2011 } elsif ( $self->payby eq 'PREPAY' ) {
2013 my $payinfo = $self->payinfo;
2014 $payinfo =~ s/\W//g; #anything else would just confuse things
2015 $self->payinfo($payinfo);
2016 $error = $self->ut_alpha('payinfo');
2017 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2018 return "Unknown prepayment identifier"
2019 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2024 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2025 return "Expiration date required"
2026 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2030 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2031 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2032 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2033 ( $m, $y ) = ( $2, "19$1" );
2034 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2035 ( $m, $y ) = ( $3, "20$2" );
2037 return "Illegal expiration date: ". $self->paydate;
2039 $m = sprintf('%02d',$m);
2040 $self->paydate("$y-$m-01");
2041 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2042 return gettext('expired_card')
2044 && !$ignore_expired_card
2045 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2048 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2049 ( ! $conf->exists('require_cardname')
2050 || $self->payby !~ /^(CARD|DCRD)$/ )
2052 $self->payname( $self->first. " ". $self->getfield('last') );
2054 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2055 or return gettext('illegal_name'). " payname: ". $self->payname;
2059 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2060 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2064 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2066 warn "$me check AFTER: \n". $self->_dump
2069 $self->SUPER::check;
2074 Returns a list of fields which have ship_ duplicates.
2079 qw( last first company
2080 address1 address2 city county state zip country
2081 daytime night fax mobile
2085 =item has_ship_address
2087 Returns true if this customer record has a separate shipping address.
2091 sub has_ship_address {
2093 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2098 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2099 city, county, state, zip, country, and geocode. The shipping address is used if present.
2105 Returns all locations (see L<FS::cust_location>) for this customer.
2111 qsearch('cust_location', { 'custnum' => $self->custnum } );
2116 Returns all contacts (see L<FS::contact>) for this customer.
2120 #already used :/ sub contact {
2123 qsearch('contact', { 'custnum' => $self->custnum } );
2128 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2129 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2130 on success or a list of errors.
2136 grep { $_->unsuspend } $self->suspended_pkgs;
2141 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2143 Returns a list: an empty list on success or a list of errors.
2149 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2152 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2154 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2155 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2156 of a list of pkgparts; the hashref has the following keys:
2160 =item pkgparts - listref of pkgparts
2162 =item (other options are passed to the suspend method)
2167 Returns a list: an empty list on success or a list of errors.
2171 sub suspend_if_pkgpart {
2173 my (@pkgparts, %opt);
2174 if (ref($_[0]) eq 'HASH'){
2175 @pkgparts = @{$_[0]{pkgparts}};
2180 grep { $_->suspend(%opt) }
2181 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2182 $self->unsuspended_pkgs;
2185 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2187 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2188 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2189 instead of a list of pkgparts; the hashref has the following keys:
2193 =item pkgparts - listref of pkgparts
2195 =item (other options are passed to the suspend method)
2199 Returns a list: an empty list on success or a list of errors.
2203 sub suspend_unless_pkgpart {
2205 my (@pkgparts, %opt);
2206 if (ref($_[0]) eq 'HASH'){
2207 @pkgparts = @{$_[0]{pkgparts}};
2212 grep { $_->suspend(%opt) }
2213 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2214 $self->unsuspended_pkgs;
2217 =item cancel [ OPTION => VALUE ... ]
2219 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2221 Available options are:
2225 =item quiet - can be set true to supress email cancellation notices.
2227 =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.
2229 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2231 =item nobill - can be set true to skip billing if it might otherwise be done.
2235 Always returns a list: an empty list on success or a list of errors.
2239 # nb that dates are not specified as valid options to this method
2242 my( $self, %opt ) = @_;
2244 warn "$me cancel called on customer ". $self->custnum. " with options ".
2245 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2248 return ( 'access denied' )
2249 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2251 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2253 #should try decryption (we might have the private key)
2254 # and if not maybe queue a job for the server that does?
2255 return ( "Can't (yet) ban encrypted credit cards" )
2256 if $self->is_encrypted($self->payinfo);
2258 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2259 my $error = $ban->insert;
2260 return ( $error ) if $error;
2264 my @pkgs = $self->ncancelled_pkgs;
2266 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2268 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2269 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2273 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2274 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2277 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2280 sub _banned_pay_hashref {
2291 'payby' => $payby2ban{$self->payby},
2292 'payinfo' => $self->payinfo,
2293 #don't ever *search* on reason! #'reason' =>
2297 sub _new_banned_pay_hashref {
2299 my $hr = $self->_banned_pay_hashref;
2300 $hr->{payinfo} = md5_base64($hr->{payinfo});
2306 Returns all notes (see L<FS::cust_main_note>) for this customer.
2311 my($self,$orderby_classnum) = (shift,shift);
2312 my $orderby = "_DATE DESC";
2313 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2314 qsearch( 'cust_main_note',
2315 { 'custnum' => $self->custnum },
2317 "ORDER BY $orderby",
2323 Returns the agent (see L<FS::agent>) for this customer.
2329 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2334 Returns the agent name (see L<FS::agent>) for this customer.
2340 $self->agent->agent;
2345 Returns any tags associated with this customer, as FS::cust_tag objects,
2346 or an empty list if there are no tags.
2352 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2357 Returns any tags associated with this customer, as FS::part_tag objects,
2358 or an empty list if there are no tags.
2364 map $_->part_tag, $self->cust_tag;
2370 Returns the customer class, as an FS::cust_class object, or the empty string
2371 if there is no customer class.
2377 if ( $self->classnum ) {
2378 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2386 Returns the customer category name, or the empty string if there is no customer
2393 my $cust_class = $self->cust_class;
2395 ? $cust_class->categoryname
2401 Returns the customer class name, or the empty string if there is no customer
2408 my $cust_class = $self->cust_class;
2410 ? $cust_class->classname
2414 =item BILLING METHODS
2416 Documentation on billing methods has been moved to
2417 L<FS::cust_main::Billing>.
2419 =item REALTIME BILLING METHODS
2421 Documentation on realtime billing methods has been moved to
2422 L<FS::cust_main::Billing_Realtime>.
2426 Removes the I<paycvv> field from the database directly.
2428 If there is an error, returns the error, otherwise returns false.
2434 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2435 or return dbh->errstr;
2436 $sth->execute($self->custnum)
2437 or return $sth->errstr;
2442 =item batch_card OPTION => VALUE...
2444 Adds a payment for this invoice to the pending credit card batch (see
2445 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2446 runs the payment using a realtime gateway.
2451 my ($self, %options) = @_;
2454 if (exists($options{amount})) {
2455 $amount = $options{amount};
2457 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2459 return '' unless $amount > 0;
2461 my $invnum = delete $options{invnum};
2462 my $payby = $options{payby} || $self->payby; #still dubious
2464 if ($options{'realtime'}) {
2465 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2471 my $oldAutoCommit = $FS::UID::AutoCommit;
2472 local $FS::UID::AutoCommit = 0;
2475 #this needs to handle mysql as well as Pg, like svc_acct.pm
2476 #(make it into a common function if folks need to do batching with mysql)
2477 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2478 or return "Cannot lock pay_batch: " . $dbh->errstr;
2482 'payby' => FS::payby->payby2payment($payby),
2484 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2486 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2488 unless ( $pay_batch ) {
2489 $pay_batch = new FS::pay_batch \%pay_batch;
2490 my $error = $pay_batch->insert;
2492 $dbh->rollback if $oldAutoCommit;
2493 die "error creating new batch: $error\n";
2497 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2498 'batchnum' => $pay_batch->batchnum,
2499 'custnum' => $self->custnum,
2502 foreach (qw( address1 address2 city state zip country payby payinfo paydate
2504 $options{$_} = '' unless exists($options{$_});
2507 my $cust_pay_batch = new FS::cust_pay_batch ( {
2508 'batchnum' => $pay_batch->batchnum,
2509 'invnum' => $invnum || 0, # is there a better value?
2510 # this field should be
2512 # cust_bill_pay_batch now
2513 'custnum' => $self->custnum,
2514 'last' => $self->getfield('last'),
2515 'first' => $self->getfield('first'),
2516 'address1' => $options{address1} || $self->address1,
2517 'address2' => $options{address2} || $self->address2,
2518 'city' => $options{city} || $self->city,
2519 'state' => $options{state} || $self->state,
2520 'zip' => $options{zip} || $self->zip,
2521 'country' => $options{country} || $self->country,
2522 'payby' => $options{payby} || $self->payby,
2523 'payinfo' => $options{payinfo} || $self->payinfo,
2524 'exp' => $options{paydate} || $self->paydate,
2525 'payname' => $options{payname} || $self->payname,
2526 'amount' => $amount, # consolidating
2529 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2530 if $old_cust_pay_batch;
2533 if ($old_cust_pay_batch) {
2534 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2536 $error = $cust_pay_batch->insert;
2540 $dbh->rollback if $oldAutoCommit;
2544 my $unapplied = $self->total_unapplied_credits
2545 + $self->total_unapplied_payments
2546 + $self->in_transit_payments;
2547 foreach my $cust_bill ($self->open_cust_bill) {
2548 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2549 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2550 'invnum' => $cust_bill->invnum,
2551 'paybatchnum' => $cust_pay_batch->paybatchnum,
2552 'amount' => $cust_bill->owed,
2555 if ($unapplied >= $cust_bill_pay_batch->amount){
2556 $unapplied -= $cust_bill_pay_batch->amount;
2559 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2560 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2562 $error = $cust_bill_pay_batch->insert;
2564 $dbh->rollback if $oldAutoCommit;
2569 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2575 Returns the total owed for this customer on all invoices
2576 (see L<FS::cust_bill/owed>).
2582 $self->total_owed_date(2145859200); #12/31/2037
2585 =item total_owed_date TIME
2587 Returns the total owed for this customer on all invoices with date earlier than
2588 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2589 see L<Time::Local> and L<Date::Parse> for conversion functions.
2593 sub total_owed_date {
2597 my $custnum = $self->custnum;
2599 my $owed_sql = FS::cust_bill->owed_sql;
2602 SELECT SUM($owed_sql) FROM cust_bill
2603 WHERE custnum = $custnum
2607 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2611 =item total_owed_pkgnum PKGNUM
2613 Returns the total owed on all invoices for this customer's specific package
2614 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2618 sub total_owed_pkgnum {
2619 my( $self, $pkgnum ) = @_;
2620 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2623 =item total_owed_date_pkgnum TIME PKGNUM
2625 Returns the total owed for this customer's specific package when using
2626 experimental package balances on all invoices with date earlier than
2627 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2628 see L<Time::Local> and L<Date::Parse> for conversion functions.
2632 sub total_owed_date_pkgnum {
2633 my( $self, $time, $pkgnum ) = @_;
2636 foreach my $cust_bill (
2637 grep { $_->_date <= $time }
2638 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2640 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2642 sprintf( "%.2f", $total_bill );
2648 Returns the total amount of all payments.
2655 $total += $_->paid foreach $self->cust_pay;
2656 sprintf( "%.2f", $total );
2659 =item total_unapplied_credits
2661 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2662 customer. See L<FS::cust_credit/credited>.
2664 =item total_credited
2666 Old name for total_unapplied_credits. Don't use.
2670 sub total_credited {
2671 #carp "total_credited deprecated, use total_unapplied_credits";
2672 shift->total_unapplied_credits(@_);
2675 sub total_unapplied_credits {
2678 my $custnum = $self->custnum;
2680 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2683 SELECT SUM($unapplied_sql) FROM cust_credit
2684 WHERE custnum = $custnum
2687 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2691 =item total_unapplied_credits_pkgnum PKGNUM
2693 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2694 customer. See L<FS::cust_credit/credited>.
2698 sub total_unapplied_credits_pkgnum {
2699 my( $self, $pkgnum ) = @_;
2700 my $total_credit = 0;
2701 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2702 sprintf( "%.2f", $total_credit );
2706 =item total_unapplied_payments
2708 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2709 See L<FS::cust_pay/unapplied>.
2713 sub total_unapplied_payments {
2716 my $custnum = $self->custnum;
2718 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2721 SELECT SUM($unapplied_sql) FROM cust_pay
2722 WHERE custnum = $custnum
2725 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2729 =item total_unapplied_payments_pkgnum PKGNUM
2731 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2732 specific package when using experimental package balances. See
2733 L<FS::cust_pay/unapplied>.
2737 sub total_unapplied_payments_pkgnum {
2738 my( $self, $pkgnum ) = @_;
2739 my $total_unapplied = 0;
2740 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2741 sprintf( "%.2f", $total_unapplied );
2745 =item total_unapplied_refunds
2747 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2748 customer. See L<FS::cust_refund/unapplied>.
2752 sub total_unapplied_refunds {
2754 my $custnum = $self->custnum;
2756 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2759 SELECT SUM($unapplied_sql) FROM cust_refund
2760 WHERE custnum = $custnum
2763 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2769 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2770 total_unapplied_credits minus total_unapplied_payments).
2776 $self->balance_date_range;
2779 =item balance_date TIME
2781 Returns the balance for this customer, only considering invoices with date
2782 earlier than TIME (total_owed_date minus total_credited minus
2783 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2784 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2791 $self->balance_date_range(shift);
2794 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2796 Returns the balance for this customer, optionally considering invoices with
2797 date earlier than START_TIME, and not later than END_TIME
2798 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2800 Times are specified as SQL fragments or numeric
2801 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2802 L<Date::Parse> for conversion functions. The empty string can be passed
2803 to disable that time constraint completely.
2805 Available options are:
2809 =item unapplied_date
2811 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)
2817 sub balance_date_range {
2819 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2820 ') FROM cust_main WHERE custnum='. $self->custnum;
2821 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2824 =item balance_pkgnum PKGNUM
2826 Returns the balance for this customer's specific package when using
2827 experimental package balances (total_owed plus total_unrefunded, minus
2828 total_unapplied_credits minus total_unapplied_payments)
2832 sub balance_pkgnum {
2833 my( $self, $pkgnum ) = @_;
2836 $self->total_owed_pkgnum($pkgnum)
2837 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2838 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2839 - $self->total_unapplied_credits_pkgnum($pkgnum)
2840 - $self->total_unapplied_payments_pkgnum($pkgnum)
2844 =item in_transit_payments
2846 Returns the total of requests for payments for this customer pending in
2847 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2851 sub in_transit_payments {
2853 my $in_transit_payments = 0;
2854 foreach my $pay_batch ( qsearch('pay_batch', {
2857 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2858 'batchnum' => $pay_batch->batchnum,
2859 'custnum' => $self->custnum,
2861 $in_transit_payments += $cust_pay_batch->amount;
2864 sprintf( "%.2f", $in_transit_payments );
2869 Returns a hash of useful information for making a payment.
2879 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2880 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2881 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2885 For credit card transactions:
2897 For electronic check transactions:
2912 $return{balance} = $self->balance;
2914 $return{payname} = $self->payname
2915 || ( $self->first. ' '. $self->get('last') );
2917 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
2919 $return{payby} = $self->payby;
2920 $return{stateid_state} = $self->stateid_state;
2922 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2923 $return{card_type} = cardtype($self->payinfo);
2924 $return{payinfo} = $self->paymask;
2926 @return{'month', 'year'} = $self->paydate_monthyear;
2930 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2931 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2932 $return{payinfo1} = $payinfo1;
2933 $return{payinfo2} = $payinfo2;
2934 $return{paytype} = $self->paytype;
2935 $return{paystate} = $self->paystate;
2939 #doubleclick protection
2941 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2947 =item paydate_monthyear
2949 Returns a two-element list consisting of the month and year of this customer's
2950 paydate (credit card expiration date for CARD customers)
2954 sub paydate_monthyear {
2956 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2958 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2967 Returns the exact time in seconds corresponding to the payment method
2968 expiration date. For CARD/DCRD customers this is the end of the month;
2969 for others (COMP is the only other payby that uses paydate) it's the start.
2970 Returns 0 if the paydate is empty or set to the far future.
2976 my ($month, $year) = $self->paydate_monthyear;
2977 return 0 if !$year or $year >= 2037;
2978 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2980 if ( $month == 13 ) {
2984 return timelocal(0,0,0,1,$month-1,$year) - 1;
2987 return timelocal(0,0,0,1,$month-1,$year);
2991 =item paydate_epoch_sql
2993 Class method. Returns an SQL expression to obtain the payment expiration date
2994 as a number of seconds.
2998 # Special expiration date behavior for non-CARD/DCRD customers has been
2999 # carefully preserved. Do we really use that?
3000 sub paydate_epoch_sql {
3002 my $table = shift || 'cust_main';
3003 my ($case1, $case2);
3004 if ( driver_name eq 'Pg' ) {
3005 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3006 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3008 elsif ( lc(driver_name) eq 'mysql' ) {
3009 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3010 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3013 return "CASE WHEN $table.payby IN('CARD','DCRD')
3019 =item tax_exemption TAXNAME
3024 my( $self, $taxname ) = @_;
3026 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3027 'taxname' => $taxname,
3032 =item cust_main_exemption
3036 sub cust_main_exemption {
3038 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3041 =item invoicing_list [ ARRAYREF ]
3043 If an arguement is given, sets these email addresses as invoice recipients
3044 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3045 (except as warnings), so use check_invoicing_list first.
3047 Returns a list of email addresses (with svcnum entries expanded).
3049 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3050 check it without disturbing anything by passing nothing.
3052 This interface may change in the future.
3056 sub invoicing_list {
3057 my( $self, $arrayref ) = @_;
3060 my @cust_main_invoice;
3061 if ( $self->custnum ) {
3062 @cust_main_invoice =
3063 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3065 @cust_main_invoice = ();
3067 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3068 #warn $cust_main_invoice->destnum;
3069 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3070 #warn $cust_main_invoice->destnum;
3071 my $error = $cust_main_invoice->delete;
3072 warn $error if $error;
3075 if ( $self->custnum ) {
3076 @cust_main_invoice =
3077 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3079 @cust_main_invoice = ();
3081 my %seen = map { $_->address => 1 } @cust_main_invoice;
3082 foreach my $address ( @{$arrayref} ) {
3083 next if exists $seen{$address} && $seen{$address};
3084 $seen{$address} = 1;
3085 my $cust_main_invoice = new FS::cust_main_invoice ( {
3086 'custnum' => $self->custnum,
3089 my $error = $cust_main_invoice->insert;
3090 warn $error if $error;
3094 if ( $self->custnum ) {
3096 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3103 =item check_invoicing_list ARRAYREF
3105 Checks these arguements as valid input for the invoicing_list method. If there
3106 is an error, returns the error, otherwise returns false.
3110 sub check_invoicing_list {
3111 my( $self, $arrayref ) = @_;
3113 foreach my $address ( @$arrayref ) {
3115 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3116 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3119 my $cust_main_invoice = new FS::cust_main_invoice ( {
3120 'custnum' => $self->custnum,
3123 my $error = $self->custnum
3124 ? $cust_main_invoice->check
3125 : $cust_main_invoice->checkdest
3127 return $error if $error;
3131 return "Email address required"
3132 if $conf->exists('cust_main-require_invoicing_list_email')
3133 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3138 =item set_default_invoicing_list
3140 Sets the invoicing list to all accounts associated with this customer,
3141 overwriting any previous invoicing list.
3145 sub set_default_invoicing_list {
3147 $self->invoicing_list($self->all_emails);
3152 Returns the email addresses of all accounts provisioned for this customer.
3159 foreach my $cust_pkg ( $self->all_pkgs ) {
3160 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3162 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3163 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3165 $list{$_}=1 foreach map { $_->email } @svc_acct;
3170 =item invoicing_list_addpost
3172 Adds postal invoicing to this customer. If this customer is already configured
3173 to receive postal invoices, does nothing.
3177 sub invoicing_list_addpost {
3179 return if grep { $_ eq 'POST' } $self->invoicing_list;
3180 my @invoicing_list = $self->invoicing_list;
3181 push @invoicing_list, 'POST';
3182 $self->invoicing_list(\@invoicing_list);
3185 =item invoicing_list_emailonly
3187 Returns the list of email invoice recipients (invoicing_list without non-email
3188 destinations such as POST and FAX).
3192 sub invoicing_list_emailonly {
3194 warn "$me invoicing_list_emailonly called"
3196 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3199 =item invoicing_list_emailonly_scalar
3201 Returns the list of email invoice recipients (invoicing_list without non-email
3202 destinations such as POST and FAX) as a comma-separated scalar.
3206 sub invoicing_list_emailonly_scalar {
3208 warn "$me invoicing_list_emailonly_scalar called"
3210 join(', ', $self->invoicing_list_emailonly);
3213 =item referral_custnum_cust_main
3215 Returns the customer who referred this customer (or the empty string, if
3216 this customer was not referred).
3218 Note the difference with referral_cust_main method: This method,
3219 referral_custnum_cust_main returns the single customer (if any) who referred
3220 this customer, while referral_cust_main returns an array of customers referred
3225 sub referral_custnum_cust_main {
3227 return '' unless $self->referral_custnum;
3228 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3231 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3233 Returns an array of customers referred by this customer (referral_custnum set
3234 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3235 customers referred by customers referred by this customer and so on, inclusive.
3236 The default behavior is DEPTH 1 (no recursion).
3238 Note the difference with referral_custnum_cust_main method: This method,
3239 referral_cust_main, returns an array of customers referred BY this customer,
3240 while referral_custnum_cust_main returns the single customer (if any) who
3241 referred this customer.
3245 sub referral_cust_main {
3247 my $depth = @_ ? shift : 1;
3248 my $exclude = @_ ? shift : {};
3251 map { $exclude->{$_->custnum}++; $_; }
3252 grep { ! $exclude->{ $_->custnum } }
3253 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3257 map { $_->referral_cust_main($depth-1, $exclude) }
3264 =item referral_cust_main_ncancelled
3266 Same as referral_cust_main, except only returns customers with uncancelled
3271 sub referral_cust_main_ncancelled {
3273 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3276 =item referral_cust_pkg [ DEPTH ]
3278 Like referral_cust_main, except returns a flat list of all unsuspended (and
3279 uncancelled) packages for each customer. The number of items in this list may
3280 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3284 sub referral_cust_pkg {
3286 my $depth = @_ ? shift : 1;
3288 map { $_->unsuspended_pkgs }
3289 grep { $_->unsuspended_pkgs }
3290 $self->referral_cust_main($depth);
3293 =item referring_cust_main
3295 Returns the single cust_main record for the customer who referred this customer
3296 (referral_custnum), or false.
3300 sub referring_cust_main {
3302 return '' unless $self->referral_custnum;
3303 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3306 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3308 Applies a credit to this customer. If there is an error, returns the error,
3309 otherwise returns false.
3311 REASON can be a text string, an FS::reason object, or a scalar reference to
3312 a reasonnum. If a text string, it will be automatically inserted as a new
3313 reason, and a 'reason_type' option must be passed to indicate the
3314 FS::reason_type for the new reason.
3316 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3318 Any other options are passed to FS::cust_credit::insert.
3323 my( $self, $amount, $reason, %options ) = @_;
3325 my $cust_credit = new FS::cust_credit {
3326 'custnum' => $self->custnum,
3327 'amount' => $amount,
3330 if ( ref($reason) ) {
3332 if ( ref($reason) eq 'SCALAR' ) {
3333 $cust_credit->reasonnum( $$reason );
3335 $cust_credit->reasonnum( $reason->reasonnum );
3339 $cust_credit->set('reason', $reason)
3342 for (qw( addlinfo eventnum )) {
3343 $cust_credit->$_( delete $options{$_} )
3344 if exists($options{$_});
3347 $cust_credit->insert(%options);
3351 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3353 Creates a one-time charge for this customer. If there is an error, returns
3354 the error, otherwise returns false.
3356 New-style, with a hashref of options:
3358 my $error = $cust_main->charge(
3362 'start_date' => str2time('7/4/2009'),
3363 'pkg' => 'Description',
3364 'comment' => 'Comment',
3365 'additional' => [], #extra invoice detail
3366 'classnum' => 1, #pkg_class
3368 'setuptax' => '', # or 'Y' for tax exempt
3371 'taxclass' => 'Tax class',
3374 'taxproduct' => 2, #part_pkg_taxproduct
3375 'override' => {}, #XXX describe
3377 #will be filled in with the new object
3378 'cust_pkg_ref' => \$cust_pkg,
3380 #generate an invoice immediately
3382 'invoice_terms' => '', #with these terms
3388 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3394 my ( $amount, $quantity, $start_date, $classnum );
3395 my ( $pkg, $comment, $additional );
3396 my ( $setuptax, $taxclass ); #internal taxes
3397 my ( $taxproduct, $override ); #vendor (CCH) taxes
3399 my $cust_pkg_ref = '';
3400 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3401 if ( ref( $_[0] ) ) {
3402 $amount = $_[0]->{amount};
3403 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3404 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3405 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3406 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3407 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3408 : '$'. sprintf("%.2f",$amount);
3409 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3410 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3411 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3412 $additional = $_[0]->{additional} || [];
3413 $taxproduct = $_[0]->{taxproductnum};
3414 $override = { '' => $_[0]->{tax_override} };
3415 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3416 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3417 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3422 $pkg = @_ ? shift : 'One-time charge';
3423 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3425 $taxclass = @_ ? shift : '';
3429 local $SIG{HUP} = 'IGNORE';
3430 local $SIG{INT} = 'IGNORE';
3431 local $SIG{QUIT} = 'IGNORE';
3432 local $SIG{TERM} = 'IGNORE';
3433 local $SIG{TSTP} = 'IGNORE';
3434 local $SIG{PIPE} = 'IGNORE';
3436 my $oldAutoCommit = $FS::UID::AutoCommit;
3437 local $FS::UID::AutoCommit = 0;
3440 my $part_pkg = new FS::part_pkg ( {
3442 'comment' => $comment,
3446 'classnum' => ( $classnum ? $classnum : '' ),
3447 'setuptax' => $setuptax,
3448 'taxclass' => $taxclass,
3449 'taxproductnum' => $taxproduct,
3452 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3453 ( 0 .. @$additional - 1 )
3455 'additional_count' => scalar(@$additional),
3456 'setup_fee' => $amount,
3459 my $error = $part_pkg->insert( options => \%options,
3460 tax_overrides => $override,
3463 $dbh->rollback if $oldAutoCommit;
3467 my $pkgpart = $part_pkg->pkgpart;
3468 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3469 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3470 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3471 $error = $type_pkgs->insert;
3473 $dbh->rollback if $oldAutoCommit;
3478 my $cust_pkg = new FS::cust_pkg ( {
3479 'custnum' => $self->custnum,
3480 'pkgpart' => $pkgpart,
3481 'quantity' => $quantity,
3482 'start_date' => $start_date,
3483 'no_auto' => $no_auto,
3486 $error = $cust_pkg->insert;
3488 $dbh->rollback if $oldAutoCommit;
3490 } elsif ( $cust_pkg_ref ) {
3491 ${$cust_pkg_ref} = $cust_pkg;
3495 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3496 'pkg_list' => [ $cust_pkg ],
3499 $dbh->rollback if $oldAutoCommit;
3504 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3509 #=item charge_postal_fee
3511 #Applies a one time charge this customer. If there is an error,
3512 #returns the error, returns the cust_pkg charge object or false
3513 #if there was no charge.
3517 # This should be a customer event. For that to work requires that bill
3518 # also be a customer event.
3520 sub charge_postal_fee {
3523 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3524 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3526 my $cust_pkg = new FS::cust_pkg ( {
3527 'custnum' => $self->custnum,
3528 'pkgpart' => $pkgpart,
3532 my $error = $cust_pkg->insert;
3533 $error ? $error : $cust_pkg;
3536 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3538 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3540 Optionally, a list or hashref of additional arguments to the qsearch call can
3547 my $opt = ref($_[0]) ? shift : { @_ };
3549 #return $self->num_cust_bill unless wantarray || keys %$opt;
3551 $opt->{'table'} = 'cust_bill';
3552 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3553 $opt->{'hashref'}{'custnum'} = $self->custnum;
3554 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3556 map { $_ } #behavior of sort undefined in scalar context
3557 sort { $a->_date <=> $b->_date }
3561 =item open_cust_bill
3563 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3568 sub open_cust_bill {
3572 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3578 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3580 Returns all the statements (see L<FS::cust_statement>) for this customer.
3582 Optionally, a list or hashref of additional arguments to the qsearch call can
3587 sub cust_statement {
3589 my $opt = ref($_[0]) ? shift : { @_ };
3591 #return $self->num_cust_statement unless wantarray || keys %$opt;
3593 $opt->{'table'} = 'cust_statement';
3594 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3595 $opt->{'hashref'}{'custnum'} = $self->custnum;
3596 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3598 map { $_ } #behavior of sort undefined in scalar context
3599 sort { $a->_date <=> $b->_date }
3603 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3605 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3607 Optionally, a list or hashref of additional arguments to the qsearch call can
3608 be passed following the SVCDB.
3615 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3616 warn "$me svc_x requires a svcdb";
3619 my $opt = ref($_[0]) ? shift : { @_ };
3621 $opt->{'table'} = $svcdb;
3622 $opt->{'addl_from'} =
3623 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3624 ($opt->{'addl_from'} || '');
3626 my $custnum = $self->custnum;
3627 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3628 my $where = "cust_pkg.custnum = $custnum";
3630 my $extra_sql = $opt->{'extra_sql'} || '';
3631 if ( keys %{ $opt->{'hashref'} } ) {
3632 $extra_sql = " AND $where $extra_sql";
3635 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3636 $extra_sql = "WHERE $where AND $1";
3639 $extra_sql = "WHERE $where $extra_sql";
3642 $opt->{'extra_sql'} = $extra_sql;
3647 # required for use as an eventtable;
3650 $self->svc_x('svc_acct', @_);
3655 Returns all the credits (see L<FS::cust_credit>) for this customer.
3661 map { $_ } #return $self->num_cust_credit unless wantarray;
3662 sort { $a->_date <=> $b->_date }
3663 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3666 =item cust_credit_pkgnum
3668 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3669 package when using experimental package balances.
3673 sub cust_credit_pkgnum {
3674 my( $self, $pkgnum ) = @_;
3675 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3676 sort { $a->_date <=> $b->_date }
3677 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3678 'pkgnum' => $pkgnum,
3685 Returns all the payments (see L<FS::cust_pay>) for this customer.
3691 return $self->num_cust_pay unless wantarray;
3692 sort { $a->_date <=> $b->_date }
3693 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3698 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3699 called automatically when the cust_pay method is used in a scalar context.
3705 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3706 my $sth = dbh->prepare($sql) or die dbh->errstr;
3707 $sth->execute($self->custnum) or die $sth->errstr;
3708 $sth->fetchrow_arrayref->[0];
3711 =item cust_pay_pkgnum
3713 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3714 package when using experimental package balances.
3718 sub cust_pay_pkgnum {
3719 my( $self, $pkgnum ) = @_;
3720 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3721 sort { $a->_date <=> $b->_date }
3722 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3723 'pkgnum' => $pkgnum,
3730 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3736 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3737 sort { $a->_date <=> $b->_date }
3738 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3741 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3743 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3745 Optionally, a list or hashref of additional arguments to the qsearch call can
3750 sub cust_pay_batch {
3752 my $opt = ref($_[0]) ? shift : { @_ };
3754 #return $self->num_cust_statement unless wantarray || keys %$opt;
3756 $opt->{'table'} = 'cust_pay_batch';
3757 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3758 $opt->{'hashref'}{'custnum'} = $self->custnum;
3759 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3761 map { $_ } #behavior of sort undefined in scalar context
3762 sort { $a->paybatchnum <=> $b->paybatchnum }
3766 =item cust_pay_pending
3768 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3769 (without status "done").
3773 sub cust_pay_pending {
3775 return $self->num_cust_pay_pending unless wantarray;
3776 sort { $a->_date <=> $b->_date }
3777 qsearch( 'cust_pay_pending', {
3778 'custnum' => $self->custnum,
3779 'status' => { op=>'!=', value=>'done' },
3784 =item cust_pay_pending_attempt
3786 Returns all payment attempts / declined payments for this customer, as pending
3787 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3788 a corresponding payment (see L<FS::cust_pay>).
3792 sub cust_pay_pending_attempt {
3794 return $self->num_cust_pay_pending_attempt unless wantarray;
3795 sort { $a->_date <=> $b->_date }
3796 qsearch( 'cust_pay_pending', {
3797 'custnum' => $self->custnum,
3804 =item num_cust_pay_pending
3806 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3807 customer (without status "done"). Also called automatically when the
3808 cust_pay_pending method is used in a scalar context.
3812 sub num_cust_pay_pending {
3815 " SELECT COUNT(*) FROM cust_pay_pending ".
3816 " WHERE custnum = ? AND status != 'done' ",
3821 =item num_cust_pay_pending_attempt
3823 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3824 customer, with status "done" but without a corresp. Also called automatically when the
3825 cust_pay_pending method is used in a scalar context.
3829 sub num_cust_pay_pending_attempt {
3832 " SELECT COUNT(*) FROM cust_pay_pending ".
3833 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3840 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3846 map { $_ } #return $self->num_cust_refund unless wantarray;
3847 sort { $a->_date <=> $b->_date }
3848 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3851 =item display_custnum
3853 Returns the displayed customer number for this customer: agent_custid if
3854 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3858 sub display_custnum {
3860 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3861 return $self->agent_custid;
3863 return $self->custnum;
3869 Returns a name string for this customer, either "Company (Last, First)" or
3876 my $name = $self->contact;
3877 $name = $self->company. " ($name)" if $self->company;
3883 Returns a name string for this (service/shipping) contact, either
3884 "Company (Last, First)" or "Last, First".
3890 if ( $self->get('ship_last') ) {
3891 my $name = $self->ship_contact;
3892 $name = $self->ship_company. " ($name)" if $self->ship_company;
3901 Returns a name string for this customer, either "Company" or "First Last".
3907 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3910 =item ship_name_short
3912 Returns a name string for this (service/shipping) contact, either "Company"
3917 sub ship_name_short {
3919 if ( $self->get('ship_last') ) {
3920 $self->ship_company !~ /^\s*$/
3921 ? $self->ship_company
3922 : $self->ship_contact_firstlast;
3924 $self->name_company_or_firstlast;
3930 Returns this customer's full (billing) contact name only, "Last, First"
3936 $self->get('last'). ', '. $self->first;
3941 Returns this customer's full (shipping) contact name only, "Last, First"
3947 $self->get('ship_last')
3948 ? $self->get('ship_last'). ', '. $self->ship_first
3952 =item contact_firstlast
3954 Returns this customers full (billing) contact name only, "First Last".
3958 sub contact_firstlast {
3960 $self->first. ' '. $self->get('last');
3963 =item ship_contact_firstlast
3965 Returns this customer's full (shipping) contact name only, "First Last".
3969 sub ship_contact_firstlast {
3971 $self->get('ship_last')
3972 ? $self->first. ' '. $self->get('ship_last')
3973 : $self->contact_firstlast;
3978 Returns this customer's full country name
3984 code2country($self->country);
3987 =item geocode DATA_VENDOR
3989 Returns a value for the customer location as encoded by DATA_VENDOR.
3990 Currently this only makes sense for "CCH" as DATA_VENDOR.
3998 Returns a status string for this customer, currently:
4002 =item prospect - No packages have ever been ordered
4004 =item ordered - Recurring packages all are new (not yet billed).
4006 =item active - One or more recurring packages is active
4008 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4010 =item suspended - All non-cancelled recurring packages are suspended
4012 =item cancelled - All recurring packages are cancelled
4016 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4017 cust_main-status_module configuration option.
4021 sub status { shift->cust_status(@_); }
4025 for my $status ( FS::cust_main->statuses() ) {
4026 my $method = $status.'_sql';
4027 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4028 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4029 $sth->execute( ($self->custnum) x $numnum )
4030 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4031 return $status if $sth->fetchrow_arrayref->[0];
4035 =item ucfirst_cust_status
4037 =item ucfirst_status
4039 Returns the status with the first character capitalized.
4043 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4045 sub ucfirst_cust_status {
4047 ucfirst($self->cust_status);
4052 Returns a hex triplet color string for this customer's status.
4056 sub statuscolor { shift->cust_statuscolor(@_); }
4058 sub cust_statuscolor {
4060 __PACKAGE__->statuscolors->{$self->cust_status};
4065 Returns an array of hashes representing the customer's RT tickets.
4072 my $num = $conf->config('cust_main-max_tickets') || 10;
4075 if ( $conf->config('ticket_system') ) {
4076 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4078 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4082 foreach my $priority (
4083 $conf->config('ticket_system-custom_priority_field-values'), ''
4085 last if scalar(@tickets) >= $num;
4087 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4088 $num - scalar(@tickets),
4098 # Return services representing svc_accts in customer support packages
4099 sub support_services {
4101 my %packages = map { $_ => 1 } $conf->config('support_packages');
4103 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4104 grep { $_->part_svc->svcdb eq 'svc_acct' }
4105 map { $_->cust_svc }
4106 grep { exists $packages{ $_->pkgpart } }
4107 $self->ncancelled_pkgs;
4111 # Return a list of latitude/longitude for one of the services (if any)
4112 sub service_coordinates {
4116 grep { $_->latitude && $_->longitude }
4118 map { $_->cust_svc }
4119 $self->ncancelled_pkgs;
4121 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4126 Returns a masked version of the named field
4131 my ($self,$field) = @_;
4135 'x'x(length($self->getfield($field))-4).
4136 substr($self->getfield($field), (length($self->getfield($field))-4));
4142 =head1 CLASS METHODS
4148 Class method that returns the list of possible status strings for customers
4149 (see L<the status method|/status>). For example:
4151 @statuses = FS::cust_main->statuses();
4157 keys %{ $self->statuscolors };
4160 =item cust_status_sql
4162 Returns an SQL fragment to determine the status of a cust_main record, as a
4167 sub cust_status_sql {
4169 for my $status ( FS::cust_main->statuses() ) {
4170 my $method = $status.'_sql';
4171 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4180 Returns an SQL expression identifying prospective cust_main records (customers
4181 with no packages ever ordered)
4185 use vars qw($select_count_pkgs);
4186 $select_count_pkgs =
4187 "SELECT COUNT(*) FROM cust_pkg
4188 WHERE cust_pkg.custnum = cust_main.custnum";
4190 sub select_count_pkgs_sql {
4195 " 0 = ( $select_count_pkgs ) ";
4200 Returns an SQL expression identifying ordered cust_main records (customers with
4201 no active packages, but recurring packages not yet setup or one time charges
4207 FS::cust_main->none_active_sql.
4208 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4213 Returns an SQL expression identifying active cust_main records (customers with
4214 active recurring packages).
4219 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4222 =item none_active_sql
4224 Returns an SQL expression identifying cust_main records with no active
4225 recurring packages. This includes customers of status prospect, ordered,
4226 inactive, and suspended.
4230 sub none_active_sql {
4231 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4236 Returns an SQL expression identifying inactive cust_main records (customers with
4237 no active recurring packages, but otherwise unsuspended/uncancelled).
4242 FS::cust_main->none_active_sql.
4243 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4249 Returns an SQL expression identifying suspended cust_main records.
4254 sub suspended_sql { susp_sql(@_); }
4256 FS::cust_main->none_active_sql.
4257 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4263 Returns an SQL expression identifying cancelled cust_main records.
4267 sub cancel_sql { shift->cancelled_sql(@_); }
4270 =item uncancelled_sql
4272 Returns an SQL expression identifying un-cancelled cust_main records.
4276 sub uncancelled_sql { uncancel_sql(@_); }
4277 sub uncancel_sql { "
4278 ( 0 < ( $select_count_pkgs
4279 AND ( cust_pkg.cancel IS NULL
4280 OR cust_pkg.cancel = 0
4283 OR 0 = ( $select_count_pkgs )
4289 Returns an SQL fragment to retreive the balance.
4294 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4295 WHERE cust_bill.custnum = cust_main.custnum )
4296 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4297 WHERE cust_pay.custnum = cust_main.custnum )
4298 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4299 WHERE cust_credit.custnum = cust_main.custnum )
4300 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4301 WHERE cust_refund.custnum = cust_main.custnum )
4304 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4306 Returns an SQL fragment to retreive the balance for this customer, optionally
4307 considering invoices with date earlier than START_TIME, and not
4308 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4309 total_unapplied_payments).
4311 Times are specified as SQL fragments or numeric
4312 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4313 L<Date::Parse> for conversion functions. The empty string can be passed
4314 to disable that time constraint completely.
4316 Available options are:
4320 =item unapplied_date
4322 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)
4327 set to true to remove all customer comparison clauses, for totals
4332 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4337 JOIN clause (typically used with the total option)
4341 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4342 time will be ignored. Note that START_TIME and END_TIME only limit the date
4343 range for invoices and I<unapplied> payments, credits, and refunds.
4349 sub balance_date_sql {
4350 my( $class, $start, $end, %opt ) = @_;
4352 my $cutoff = $opt{'cutoff'};
4354 my $owed = FS::cust_bill->owed_sql($cutoff);
4355 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4356 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4357 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4359 my $j = $opt{'join'} || '';
4361 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4362 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4363 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4364 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4366 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4367 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4368 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4369 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4374 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4376 Returns an SQL fragment to retreive the total unapplied payments for this
4377 customer, only considering payments with date earlier than START_TIME, and
4378 optionally not later than END_TIME.
4380 Times are specified as SQL fragments or numeric
4381 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4382 L<Date::Parse> for conversion functions. The empty string can be passed
4383 to disable that time constraint completely.
4385 Available options are:
4389 sub unapplied_payments_date_sql {
4390 my( $class, $start, $end, %opt ) = @_;
4392 my $cutoff = $opt{'cutoff'};
4394 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4396 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4397 'unapplied_date'=>1 );
4399 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4402 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4404 Helper method for balance_date_sql; name (and usage) subject to change
4405 (suggestions welcome).
4407 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4408 cust_refund, cust_credit or cust_pay).
4410 If TABLE is "cust_bill" or the unapplied_date option is true, only
4411 considers records with date earlier than START_TIME, and optionally not
4412 later than END_TIME .
4416 sub _money_table_where {
4417 my( $class, $table, $start, $end, %opt ) = @_;
4420 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4421 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4422 push @where, "$table._date <= $start" if defined($start) && length($start);
4423 push @where, "$table._date > $end" if defined($end) && length($end);
4425 push @where, @{$opt{'where'}} if $opt{'where'};
4426 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4432 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4433 use FS::cust_main::Search;
4436 FS::cust_main::Search->search(@_);
4445 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4449 use FS::cust_main::Search;
4450 sub append_fuzzyfiles {
4451 #my( $first, $last, $company ) = @_;
4453 FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4455 use Fcntl qw(:flock);
4457 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4459 foreach my $field (@fuzzyfields) {
4464 open(CACHE,">>$dir/cust_main.$field")
4465 or die "can't open $dir/cust_main.$field: $!";
4466 flock(CACHE,LOCK_EX)
4467 or die "can't lock $dir/cust_main.$field: $!";
4469 print CACHE "$value\n";
4471 flock(CACHE,LOCK_UN)
4472 or die "can't unlock $dir/cust_main.$field: $!";
4487 #warn join('-',keys %$param);
4488 my $fh = $param->{filehandle};
4489 my $agentnum = $param->{agentnum};
4490 my $format = $param->{format};
4492 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4495 if ( $format eq 'simple' ) {
4496 @fields = qw( custnum agent_custid amount pkg );
4498 die "unknown format $format";
4501 eval "use Text::CSV_XS;";
4504 my $csv = new Text::CSV_XS;
4511 local $SIG{HUP} = 'IGNORE';
4512 local $SIG{INT} = 'IGNORE';
4513 local $SIG{QUIT} = 'IGNORE';
4514 local $SIG{TERM} = 'IGNORE';
4515 local $SIG{TSTP} = 'IGNORE';
4516 local $SIG{PIPE} = 'IGNORE';
4518 my $oldAutoCommit = $FS::UID::AutoCommit;
4519 local $FS::UID::AutoCommit = 0;
4522 #while ( $columns = $csv->getline($fh) ) {
4524 while ( defined($line=<$fh>) ) {
4526 $csv->parse($line) or do {
4527 $dbh->rollback if $oldAutoCommit;
4528 return "can't parse: ". $csv->error_input();
4531 my @columns = $csv->fields();
4532 #warn join('-',@columns);
4535 foreach my $field ( @fields ) {
4536 $row{$field} = shift @columns;
4539 if ( $row{custnum} && $row{agent_custid} ) {
4540 dbh->rollback if $oldAutoCommit;
4541 return "can't specify custnum with agent_custid $row{agent_custid}";
4545 if ( $row{agent_custid} && $agentnum ) {
4546 %hash = ( 'agent_custid' => $row{agent_custid},
4547 'agentnum' => $agentnum,
4551 if ( $row{custnum} ) {
4552 %hash = ( 'custnum' => $row{custnum} );
4555 unless ( scalar(keys %hash) ) {
4556 $dbh->rollback if $oldAutoCommit;
4557 return "can't find customer without custnum or agent_custid and agentnum";
4560 my $cust_main = qsearchs('cust_main', { %hash } );
4561 unless ( $cust_main ) {
4562 $dbh->rollback if $oldAutoCommit;
4563 my $custnum = $row{custnum} || $row{agent_custid};
4564 return "unknown custnum $custnum";
4567 if ( $row{'amount'} > 0 ) {
4568 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4570 $dbh->rollback if $oldAutoCommit;
4574 } elsif ( $row{'amount'} < 0 ) {
4575 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4578 $dbh->rollback if $oldAutoCommit;
4588 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4590 return "Empty file!" unless $imported;
4596 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4598 Deprecated. Use event notification and message templates
4599 (L<FS::msg_template>) instead.
4601 Sends a templated email notification to the customer (see L<Text::Template>).
4603 OPTIONS is a hash and may include
4605 I<from> - the email sender (default is invoice_from)
4607 I<to> - comma-separated scalar or arrayref of recipients
4608 (default is invoicing_list)
4610 I<subject> - The subject line of the sent email notification
4611 (default is "Notice from company_name")
4613 I<extra_fields> - a hashref of name/value pairs which will be substituted
4616 The following variables are vavailable in the template.
4618 I<$first> - the customer first name
4619 I<$last> - the customer last name
4620 I<$company> - the customer company
4621 I<$payby> - a description of the method of payment for the customer
4622 # would be nice to use FS::payby::shortname
4623 I<$payinfo> - the account information used to collect for this customer
4624 I<$expdate> - the expiration of the customer payment in seconds from epoch
4629 my ($self, $template, %options) = @_;
4631 return unless $conf->exists($template);
4633 my $from = $conf->config('invoice_from', $self->agentnum)
4634 if $conf->exists('invoice_from', $self->agentnum);
4635 $from = $options{from} if exists($options{from});
4637 my $to = join(',', $self->invoicing_list_emailonly);
4638 $to = $options{to} if exists($options{to});
4640 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4641 if $conf->exists('company_name', $self->agentnum);
4642 $subject = $options{subject} if exists($options{subject});
4644 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4645 SOURCE => [ map "$_\n",
4646 $conf->config($template)]
4648 or die "can't create new Text::Template object: Text::Template::ERROR";
4649 $notify_template->compile()
4650 or die "can't compile template: Text::Template::ERROR";
4652 $FS::notify_template::_template::company_name =
4653 $conf->config('company_name', $self->agentnum);
4654 $FS::notify_template::_template::company_address =
4655 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4657 my $paydate = $self->paydate || '2037-12-31';
4658 $FS::notify_template::_template::first = $self->first;
4659 $FS::notify_template::_template::last = $self->last;
4660 $FS::notify_template::_template::company = $self->company;
4661 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4662 my $payby = $self->payby;
4663 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4664 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4666 #credit cards expire at the end of the month/year of their exp date
4667 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4668 $FS::notify_template::_template::payby = 'credit card';
4669 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4670 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4672 }elsif ($payby eq 'COMP') {
4673 $FS::notify_template::_template::payby = 'complimentary account';
4675 $FS::notify_template::_template::payby = 'current method';
4677 $FS::notify_template::_template::expdate = $expire_time;
4679 for (keys %{$options{extra_fields}}){
4681 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4684 send_email(from => $from,
4686 subject => $subject,
4687 body => $notify_template->fill_in( PACKAGE =>
4688 'FS::notify_template::_template' ),
4693 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4695 Generates a templated notification to the customer (see L<Text::Template>).
4697 OPTIONS is a hash and may include
4699 I<extra_fields> - a hashref of name/value pairs which will be substituted
4700 into the template. These values may override values mentioned below
4701 and those from the customer record.
4703 The following variables are available in the template instead of or in addition
4704 to the fields of the customer record.
4706 I<$payby> - a description of the method of payment for the customer
4707 # would be nice to use FS::payby::shortname
4708 I<$payinfo> - the masked account information used to collect for this customer
4709 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4710 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4714 # a lot like cust_bill::print_latex
4715 sub generate_letter {
4716 my ($self, $template, %options) = @_;
4718 return unless $conf->exists($template);
4720 my $letter_template = new Text::Template
4722 SOURCE => [ map "$_\n", $conf->config($template)],
4723 DELIMITERS => [ '[@--', '--@]' ],
4725 or die "can't create new Text::Template object: Text::Template::ERROR";
4727 $letter_template->compile()
4728 or die "can't compile template: Text::Template::ERROR";
4730 my %letter_data = map { $_ => $self->$_ } $self->fields;
4731 $letter_data{payinfo} = $self->mask_payinfo;
4733 #my $paydate = $self->paydate || '2037-12-31';
4734 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4736 my $payby = $self->payby;
4737 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4738 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4740 #credit cards expire at the end of the month/year of their exp date
4741 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4742 $letter_data{payby} = 'credit card';
4743 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4744 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4746 }elsif ($payby eq 'COMP') {
4747 $letter_data{payby} = 'complimentary account';
4749 $letter_data{payby} = 'current method';
4751 $letter_data{expdate} = $expire_time;
4753 for (keys %{$options{extra_fields}}){
4754 $letter_data{$_} = $options{extra_fields}->{$_};
4757 unless(exists($letter_data{returnaddress})){
4758 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4759 $self->agent_template)
4761 if ( length($retadd) ) {
4762 $letter_data{returnaddress} = $retadd;
4763 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4764 $letter_data{returnaddress} =
4765 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4769 ( $conf->config('company_name', $self->agentnum),
4770 $conf->config('company_address', $self->agentnum),
4774 $letter_data{returnaddress} = '~';
4778 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4780 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4782 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4784 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4788 ) or die "can't open temp file: $!\n";
4789 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4790 or die "can't write temp file: $!\n";
4792 $letter_data{'logo_file'} = $lh->filename;
4794 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4798 ) or die "can't open temp file: $!\n";
4800 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4802 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4803 return ($1, $letter_data{'logo_file'});
4807 =item print_ps TEMPLATE
4809 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4815 my($file, $lfile) = $self->generate_letter(@_);
4816 my $ps = FS::Misc::generate_ps($file);
4817 unlink($file.'.tex');
4823 =item print TEMPLATE
4825 Prints the filled in template.
4827 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4831 sub queueable_print {
4834 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4835 or die "invalid customer number: " . $opt{custvnum};
4837 my $error = $self->print( $opt{template} );
4838 die $error if $error;
4842 my ($self, $template) = (shift, shift);
4843 do_print [ $self->print_ps($template) ];
4846 #these three subs should just go away once agent stuff is all config overrides
4848 sub agent_template {
4850 $self->_agent_plandata('agent_templatename');
4853 sub agent_invoice_from {
4855 $self->_agent_plandata('agent_invoice_from');
4858 sub _agent_plandata {
4859 my( $self, $option ) = @_;
4861 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4862 #agent-specific Conf
4864 use FS::part_event::Condition;
4866 my $agentnum = $self->agentnum;
4868 my $regexp = regexp_sql();
4870 my $part_event_option =
4872 'select' => 'part_event_option.*',
4873 'table' => 'part_event_option',
4875 LEFT JOIN part_event USING ( eventpart )
4876 LEFT JOIN part_event_option AS peo_agentnum
4877 ON ( part_event.eventpart = peo_agentnum.eventpart
4878 AND peo_agentnum.optionname = 'agentnum'
4879 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4881 LEFT JOIN part_event_condition
4882 ON ( part_event.eventpart = part_event_condition.eventpart
4883 AND part_event_condition.conditionname = 'cust_bill_age'
4885 LEFT JOIN part_event_condition_option
4886 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4887 AND part_event_condition_option.optionname = 'age'
4890 #'hashref' => { 'optionname' => $option },
4891 #'hashref' => { 'part_event_option.optionname' => $option },
4893 " WHERE part_event_option.optionname = ". dbh->quote($option).
4894 " AND action = 'cust_bill_send_agent' ".
4895 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4896 " AND peo_agentnum.optionname = 'agentnum' ".
4897 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4899 CASE WHEN part_event_condition_option.optionname IS NULL
4901 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4903 , part_event.weight".
4907 unless ( $part_event_option ) {
4908 return $self->agent->invoice_template || ''
4909 if $option eq 'agent_templatename';
4913 $part_event_option->optionvalue;
4917 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4919 Subroutine (not a method), designed to be called from the queue.
4921 Takes a list of options and values.
4923 Pulls up the customer record via the custnum option and calls bill_and_collect.
4928 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4930 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4931 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4933 $cust_main->bill_and_collect( %args );
4936 sub process_bill_and_collect {
4938 my $param = thaw(decode_base64(shift));
4939 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4940 or die "custnum '$param->{custnum}' not found!\n";
4941 $param->{'job'} = $job;
4942 $param->{'fatal'} = 1; # runs from job queue, will be caught
4943 $param->{'retry'} = 1;
4945 $cust_main->bill_and_collect( %$param );
4948 sub _upgrade_data { #class method
4949 my ($class, %opts) = @_;
4952 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4953 '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',
4955 # fix yyyy-m-dd formatted paydates
4956 if ( driver_name =~ /^mysql$/i ) {
4958 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4960 else { # the SQL standard
4962 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4965 foreach my $sql ( @statements ) {
4966 my $sth = dbh->prepare($sql) or die dbh->errstr;
4967 $sth->execute or die $sth->errstr;
4970 local($ignore_expired_card) = 1;
4971 local($ignore_illegal_zip) = 1;
4972 local($ignore_banned_card) = 1;
4973 local($skip_fuzzyfiles) = 1;
4974 $class->_upgrade_otaker(%opts);
4984 The delete method should possibly take an FS::cust_main object reference
4985 instead of a scalar customer number.
4987 Bill and collect options should probably be passed as references instead of a
4990 There should probably be a configuration file with a list of allowed credit
4993 No multiple currency support (probably a larger project than just this module).
4995 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4997 Birthdates rely on negative epoch values.
4999 The payby for card/check batches is broken. With mixed batching, bad
5002 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5006 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5007 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5008 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.