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;
72 # 1 is mostly method/subroutine entry and options
73 # 2 traces progress of some operations
74 # 3 is even more information including possibly sensitive data
76 $me = '[FS::cust_main]';
79 $ignore_expired_card = 0;
80 $ignore_illegal_zip = 0;
81 $ignore_banned_card = 0;
84 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
86 @encrypted_fields = ('payinfo', 'paycvv');
87 sub nohistory_fields { ('payinfo', 'paycvv'); }
89 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
91 #ask FS::UID to run this stuff for us later
92 #$FS::UID::callback{'FS::cust_main'} = sub {
93 install_callback FS::UID sub {
95 #yes, need it for stuff below (prolly should be cached)
100 my ( $hashref, $cache ) = @_;
101 if ( exists $hashref->{'pkgnum'} ) {
102 #@{ $self->{'_pkgnum'} } = ();
103 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
104 $self->{'_pkgnum'} = $subcache;
105 #push @{ $self->{'_pkgnum'} },
106 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
112 FS::cust_main - Object methods for cust_main records
118 $record = new FS::cust_main \%hash;
119 $record = new FS::cust_main { 'column' => 'value' };
121 $error = $record->insert;
123 $error = $new_record->replace($old_record);
125 $error = $record->delete;
127 $error = $record->check;
129 @cust_pkg = $record->all_pkgs;
131 @cust_pkg = $record->ncancelled_pkgs;
133 @cust_pkg = $record->suspended_pkgs;
135 $error = $record->bill;
136 $error = $record->bill %options;
137 $error = $record->bill 'time' => $time;
139 $error = $record->collect;
140 $error = $record->collect %options;
141 $error = $record->collect 'invoice_time' => $time,
146 An FS::cust_main object represents a customer. FS::cust_main inherits from
147 FS::Record. The following fields are currently supported:
153 Primary key (assigned automatically for new customers)
157 Agent (see L<FS::agent>)
161 Advertising source (see L<FS::part_referral>)
173 Cocial security number (optional)
189 (optional, see L<FS::cust_main_county>)
193 (see L<FS::cust_main_county>)
199 (see L<FS::cust_main_county>)
235 (optional, see L<FS::cust_main_county>)
239 (see L<FS::cust_main_county>)
245 (see L<FS::cust_main_county>)
261 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
265 Payment Information (See L<FS::payinfo_Mixin> for data format)
269 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
273 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
277 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
281 Start date month (maestro/solo cards only)
285 Start date year (maestro/solo cards only)
289 Issue number (maestro/solo cards only)
293 Name on card or billing name
297 IP address from which payment information was received
301 Tax exempt, empty or `Y'
305 Order taker (see L<FS::access_user>)
311 =item referral_custnum
313 Referring customer number
317 Enable individual CDR spooling, empty or `Y'
321 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
325 Discourage individual CDR printing, empty or `Y'
329 Allow self-service editing of ticket subjects, empty or 'Y'
339 Creates a new customer. To add the customer to the database, see L<"insert">.
341 Note that this stores the hash reference, not a distinct copy of the hash it
342 points to. You can ask the object for a copy with the I<hash> method.
346 sub table { 'cust_main'; }
348 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
350 Adds this customer to the database. If there is an error, returns the error,
351 otherwise returns false.
353 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
354 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
355 are inserted atomicly, or the transaction is rolled back. Passing an empty
356 hash reference is equivalent to not supplying this parameter. There should be
357 a better explanation of this, but until then, here's an example:
360 tie %hash, 'Tie::RefHash'; #this part is important
362 $cust_pkg => [ $svc_acct ],
365 $cust_main->insert( \%hash );
367 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
368 be set as the invoicing list (see L<"invoicing_list">). Errors return as
369 expected and rollback the entire transaction; it is not necessary to call
370 check_invoicing_list first. The invoicing_list is set after the records in the
371 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
372 invoicing_list destination to the newly-created svc_acct. Here's an example:
374 $cust_main->insert( {}, [ $email, 'POST' ] );
376 Currently available options are: I<depend_jobnum>, I<noexport>,
377 I<tax_exemption> and I<prospectnum>.
379 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
380 on the supplied jobnum (they will not run until the specific job completes).
381 This can be used to defer provisioning until some action completes (such
382 as running the customer's credit card successfully).
384 The I<noexport> option is deprecated. If I<noexport> is set true, no
385 provisioning jobs (exports) are scheduled. (You can schedule them later with
386 the B<reexport> method.)
388 The I<tax_exemption> option can be set to an arrayref of tax names.
389 FS::cust_main_exemption records will be created and inserted.
391 If I<prospectnum> is set, moves contacts and locations from that prospect.
397 my $cust_pkgs = @_ ? shift : {};
398 my $invoicing_list = @_ ? shift : '';
400 warn "$me insert called with options ".
401 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
404 local $SIG{HUP} = 'IGNORE';
405 local $SIG{INT} = 'IGNORE';
406 local $SIG{QUIT} = 'IGNORE';
407 local $SIG{TERM} = 'IGNORE';
408 local $SIG{TSTP} = 'IGNORE';
409 local $SIG{PIPE} = 'IGNORE';
411 my $oldAutoCommit = $FS::UID::AutoCommit;
412 local $FS::UID::AutoCommit = 0;
415 my $prepay_identifier = '';
416 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
418 if ( $self->payby eq 'PREPAY' ) {
420 $self->payby('BILL');
421 $prepay_identifier = $self->payinfo;
424 warn " looking up prepaid card $prepay_identifier\n"
427 my $error = $self->get_prepay( $prepay_identifier,
428 'amount_ref' => \$amount,
429 'seconds_ref' => \$seconds,
430 'upbytes_ref' => \$upbytes,
431 'downbytes_ref' => \$downbytes,
432 'totalbytes_ref' => \$totalbytes,
435 $dbh->rollback if $oldAutoCommit;
436 #return "error applying prepaid card (transaction rolled back): $error";
440 $payby = 'PREP' if $amount;
442 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
445 $self->payby('BILL');
446 $amount = $self->paid;
450 warn " inserting $self\n"
453 $self->signupdate(time) unless $self->signupdate;
455 $self->auto_agent_custid()
456 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
458 my $error = $self->SUPER::insert;
460 $dbh->rollback if $oldAutoCommit;
461 #return "inserting cust_main record (transaction rolled back): $error";
465 warn " setting invoicing list\n"
468 if ( $invoicing_list ) {
469 $error = $self->check_invoicing_list( $invoicing_list );
471 $dbh->rollback if $oldAutoCommit;
472 #return "checking invoicing_list (transaction rolled back): $error";
475 $self->invoicing_list( $invoicing_list );
478 warn " setting customer tags\n"
481 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
482 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
483 'custnum' => $self->custnum };
484 my $error = $cust_tag->insert;
486 $dbh->rollback if $oldAutoCommit;
491 my $prospectnum = delete $options{'prospectnum'};
492 if ( $prospectnum ) {
494 warn " moving contacts and locations from prospect $prospectnum\n"
498 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
499 unless ( $prospect_main ) {
500 $dbh->rollback if $oldAutoCommit;
501 return "Unknown prospectnum $prospectnum";
503 $prospect_main->custnum($self->custnum);
504 $prospect_main->disabled('Y');
505 my $error = $prospect_main->replace;
507 $dbh->rollback if $oldAutoCommit;
511 my @contact = $prospect_main->contact;
512 my @cust_location = $prospect_main->cust_location;
513 my @qual = $prospect_main->qual;
515 foreach my $r ( @contact, @cust_location, @qual ) {
517 $r->custnum($self->custnum);
518 my $error = $r->replace;
520 $dbh->rollback if $oldAutoCommit;
527 warn " setting cust_main_exemption\n"
530 my $tax_exemption = delete $options{'tax_exemption'};
531 if ( $tax_exemption ) {
532 foreach my $taxname ( @$tax_exemption ) {
533 my $cust_main_exemption = new FS::cust_main_exemption {
534 'custnum' => $self->custnum,
535 'taxname' => $taxname,
537 my $error = $cust_main_exemption->insert;
539 $dbh->rollback if $oldAutoCommit;
540 return "inserting cust_main_exemption (transaction rolled back): $error";
545 if ( $self->can('start_copy_skel') ) {
546 my $error = $self->start_copy_skel;
548 $dbh->rollback if $oldAutoCommit;
553 warn " ordering packages\n"
556 $error = $self->order_pkgs( $cust_pkgs,
558 'seconds_ref' => \$seconds,
559 'upbytes_ref' => \$upbytes,
560 'downbytes_ref' => \$downbytes,
561 'totalbytes_ref' => \$totalbytes,
564 $dbh->rollback if $oldAutoCommit;
569 $dbh->rollback if $oldAutoCommit;
570 return "No svc_acct record to apply pre-paid time";
572 if ( $upbytes || $downbytes || $totalbytes ) {
573 $dbh->rollback if $oldAutoCommit;
574 return "No svc_acct record to apply pre-paid data";
578 warn " inserting initial $payby payment of $amount\n"
580 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
582 $dbh->rollback if $oldAutoCommit;
583 return "inserting payment (transaction rolled back): $error";
587 unless ( $import || $skip_fuzzyfiles ) {
588 warn " queueing fuzzyfiles update\n"
590 $error = $self->queue_fuzzyfiles_update;
592 $dbh->rollback if $oldAutoCommit;
593 return "updating fuzzy search cache: $error";
598 warn " exporting\n" if $DEBUG > 1;
600 my $export_args = $options{'export_args'} || [];
603 map qsearch( 'part_export', {exportnum=>$_} ),
604 $conf->config('cust_main-exports'); #, $agentnum
606 foreach my $part_export ( @part_export ) {
607 my $error = $part_export->export_insert($self, @$export_args);
609 $dbh->rollback if $oldAutoCommit;
610 return "exporting to ". $part_export->exporttype.
611 " (transaction rolled back): $error";
615 #foreach my $depend_jobnum ( @$depend_jobnums ) {
616 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
618 # foreach my $jobnum ( @jobnums ) {
619 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
620 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
622 # my $error = $queue->depend_insert($depend_jobnum);
624 # $dbh->rollback if $oldAutoCommit;
625 # return "error queuing job dependancy: $error";
632 #if ( exists $options{'jobnums'} ) {
633 # push @{ $options{'jobnums'} }, @jobnums;
636 warn " insert complete; committing transaction\n"
639 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
644 use File::CounterFile;
645 sub auto_agent_custid {
648 my $format = $conf->config('cust_main-auto_agent_custid');
650 if ( $format eq '1YMMXXXXXXXX' ) {
652 my $counter = new File::CounterFile 'cust_main.agent_custid';
655 my $ym = 100000000000 + time2str('%y%m00000000', time);
656 if ( $ym > $counter->value ) {
657 $counter->{'value'} = $agent_custid = $ym;
658 $counter->{'updated'} = 1;
660 $agent_custid = $counter->inc;
666 die "Unknown cust_main-auto_agent_custid format: $format";
669 $self->agent_custid($agent_custid);
673 =item PACKAGE METHODS
675 Documentation on customer package methods has been moved to
676 L<FS::cust_main::Packages>.
678 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
680 Recharges this (existing) customer with the specified prepaid card (see
681 L<FS::prepay_credit>), specified either by I<identifier> or as an
682 FS::prepay_credit object. If there is an error, returns the error, otherwise
685 Optionally, five scalar references can be passed as well. They will have their
686 values filled in with the amount, number of seconds, and number of upload,
687 download, and total bytes applied by this prepaid card.
691 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
692 #the only place that uses these args
693 sub recharge_prepay {
694 my( $self, $prepay_credit, $amountref, $secondsref,
695 $upbytesref, $downbytesref, $totalbytesref ) = @_;
697 local $SIG{HUP} = 'IGNORE';
698 local $SIG{INT} = 'IGNORE';
699 local $SIG{QUIT} = 'IGNORE';
700 local $SIG{TERM} = 'IGNORE';
701 local $SIG{TSTP} = 'IGNORE';
702 local $SIG{PIPE} = 'IGNORE';
704 my $oldAutoCommit = $FS::UID::AutoCommit;
705 local $FS::UID::AutoCommit = 0;
708 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
710 my $error = $self->get_prepay( $prepay_credit,
711 'amount_ref' => \$amount,
712 'seconds_ref' => \$seconds,
713 'upbytes_ref' => \$upbytes,
714 'downbytes_ref' => \$downbytes,
715 'totalbytes_ref' => \$totalbytes,
717 || $self->increment_seconds($seconds)
718 || $self->increment_upbytes($upbytes)
719 || $self->increment_downbytes($downbytes)
720 || $self->increment_totalbytes($totalbytes)
721 || $self->insert_cust_pay_prepay( $amount,
723 ? $prepay_credit->identifier
728 $dbh->rollback if $oldAutoCommit;
732 if ( defined($amountref) ) { $$amountref = $amount; }
733 if ( defined($secondsref) ) { $$secondsref = $seconds; }
734 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
735 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
736 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
738 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
743 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
745 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
746 specified either by I<identifier> or as an FS::prepay_credit object.
748 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
749 incremented by the values of the prepaid card.
751 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
752 check or set this customer's I<agentnum>.
754 If there is an error, returns the error, otherwise returns false.
760 my( $self, $prepay_credit, %opt ) = @_;
762 local $SIG{HUP} = 'IGNORE';
763 local $SIG{INT} = 'IGNORE';
764 local $SIG{QUIT} = 'IGNORE';
765 local $SIG{TERM} = 'IGNORE';
766 local $SIG{TSTP} = 'IGNORE';
767 local $SIG{PIPE} = 'IGNORE';
769 my $oldAutoCommit = $FS::UID::AutoCommit;
770 local $FS::UID::AutoCommit = 0;
773 unless ( ref($prepay_credit) ) {
775 my $identifier = $prepay_credit;
777 $prepay_credit = qsearchs(
779 { 'identifier' => $identifier },
784 unless ( $prepay_credit ) {
785 $dbh->rollback if $oldAutoCommit;
786 return "Invalid prepaid card: ". $identifier;
791 if ( $prepay_credit->agentnum ) {
792 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
793 $dbh->rollback if $oldAutoCommit;
794 return "prepaid card not valid for agent ". $self->agentnum;
796 $self->agentnum($prepay_credit->agentnum);
799 my $error = $prepay_credit->delete;
801 $dbh->rollback if $oldAutoCommit;
802 return "removing prepay_credit (transaction rolled back): $error";
805 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
806 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
808 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
813 =item increment_upbytes SECONDS
815 Updates this customer's single or primary account (see L<FS::svc_acct>) by
816 the specified number of upbytes. If there is an error, returns the error,
817 otherwise returns false.
821 sub increment_upbytes {
822 _increment_column( shift, 'upbytes', @_);
825 =item increment_downbytes SECONDS
827 Updates this customer's single or primary account (see L<FS::svc_acct>) by
828 the specified number of downbytes. If there is an error, returns the error,
829 otherwise returns false.
833 sub increment_downbytes {
834 _increment_column( shift, 'downbytes', @_);
837 =item increment_totalbytes SECONDS
839 Updates this customer's single or primary account (see L<FS::svc_acct>) by
840 the specified number of totalbytes. If there is an error, returns the error,
841 otherwise returns false.
845 sub increment_totalbytes {
846 _increment_column( shift, 'totalbytes', @_);
849 =item increment_seconds SECONDS
851 Updates this customer's single or primary account (see L<FS::svc_acct>) by
852 the specified number of seconds. If there is an error, returns the error,
853 otherwise returns false.
857 sub increment_seconds {
858 _increment_column( shift, 'seconds', @_);
861 =item _increment_column AMOUNT
863 Updates this customer's single or primary account (see L<FS::svc_acct>) by
864 the specified number of seconds or bytes. If there is an error, returns
865 the error, otherwise returns false.
869 sub _increment_column {
870 my( $self, $column, $amount ) = @_;
871 warn "$me increment_column called: $column, $amount\n"
874 return '' unless $amount;
876 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
877 $self->ncancelled_pkgs;
880 return 'No packages with primary or single services found'.
881 ' to apply pre-paid time';
882 } elsif ( scalar(@cust_pkg) > 1 ) {
883 #maybe have a way to specify the package/account?
884 return 'Multiple packages found to apply pre-paid time';
887 my $cust_pkg = $cust_pkg[0];
888 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
892 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
895 return 'No account found to apply pre-paid time';
896 } elsif ( scalar(@cust_svc) > 1 ) {
897 return 'Multiple accounts found to apply pre-paid time';
900 my $svc_acct = $cust_svc[0]->svc_x;
901 warn " found service svcnum ". $svc_acct->pkgnum.
902 ' ('. $svc_acct->email. ")\n"
905 $column = "increment_$column";
906 $svc_acct->$column($amount);
910 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
912 Inserts a prepayment in the specified amount for this customer. An optional
913 second argument can specify the prepayment identifier for tracking purposes.
914 If there is an error, returns the error, otherwise returns false.
918 sub insert_cust_pay_prepay {
919 shift->insert_cust_pay('PREP', @_);
922 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
924 Inserts a cash payment in the specified amount for this customer. An optional
925 second argument can specify the payment identifier for tracking purposes.
926 If there is an error, returns the error, otherwise returns false.
930 sub insert_cust_pay_cash {
931 shift->insert_cust_pay('CASH', @_);
934 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
936 Inserts a Western Union payment in the specified amount for this customer. An
937 optional second argument can specify the prepayment identifier for tracking
938 purposes. If there is an error, returns the error, otherwise returns false.
942 sub insert_cust_pay_west {
943 shift->insert_cust_pay('WEST', @_);
946 sub insert_cust_pay {
947 my( $self, $payby, $amount ) = splice(@_, 0, 3);
948 my $payinfo = scalar(@_) ? shift : '';
950 my $cust_pay = new FS::cust_pay {
951 'custnum' => $self->custnum,
952 'paid' => sprintf('%.2f', $amount),
953 #'_date' => #date the prepaid card was purchased???
955 'payinfo' => $payinfo,
963 This method is deprecated. See the I<depend_jobnum> option to the insert and
964 order_pkgs methods for a better way to defer provisioning.
966 Re-schedules all exports by calling the B<reexport> method of all associated
967 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
968 otherwise returns false.
975 carp "WARNING: FS::cust_main::reexport is deprectated; ".
976 "use the depend_jobnum option to insert or order_pkgs to delay export";
978 local $SIG{HUP} = 'IGNORE';
979 local $SIG{INT} = 'IGNORE';
980 local $SIG{QUIT} = 'IGNORE';
981 local $SIG{TERM} = 'IGNORE';
982 local $SIG{TSTP} = 'IGNORE';
983 local $SIG{PIPE} = 'IGNORE';
985 my $oldAutoCommit = $FS::UID::AutoCommit;
986 local $FS::UID::AutoCommit = 0;
989 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
990 my $error = $cust_pkg->reexport;
992 $dbh->rollback if $oldAutoCommit;
997 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1002 =item delete [ OPTION => VALUE ... ]
1004 This deletes the customer. If there is an error, returns the error, otherwise
1007 This will completely remove all traces of the customer record. This is not
1008 what you want when a customer cancels service; for that, cancel all of the
1009 customer's packages (see L</cancel>).
1011 If the customer has any uncancelled packages, you need to pass a new (valid)
1012 customer number for those packages to be transferred to, as the "new_customer"
1013 option. Cancelled packages will be deleted. Did I mention that this is NOT
1014 what you want when a customer cancels service and that you really should be
1015 looking at L<FS::cust_pkg/cancel>?
1017 You can't delete a customer with invoices (see L<FS::cust_bill>),
1018 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1019 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1020 set the "delete_financials" option to a true value.
1025 my( $self, %opt ) = @_;
1027 local $SIG{HUP} = 'IGNORE';
1028 local $SIG{INT} = 'IGNORE';
1029 local $SIG{QUIT} = 'IGNORE';
1030 local $SIG{TERM} = 'IGNORE';
1031 local $SIG{TSTP} = 'IGNORE';
1032 local $SIG{PIPE} = 'IGNORE';
1034 my $oldAutoCommit = $FS::UID::AutoCommit;
1035 local $FS::UID::AutoCommit = 0;
1038 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1039 $dbh->rollback if $oldAutoCommit;
1040 return "Can't delete a master agent customer";
1043 #use FS::access_user
1044 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1045 $dbh->rollback if $oldAutoCommit;
1046 return "Can't delete a master employee customer";
1049 tie my %financial_tables, 'Tie::IxHash',
1050 'cust_bill' => 'invoices',
1051 'cust_statement' => 'statements',
1052 'cust_credit' => 'credits',
1053 'cust_pay' => 'payments',
1054 'cust_refund' => 'refunds',
1057 foreach my $table ( keys %financial_tables ) {
1059 my @records = $self->$table();
1061 if ( @records && ! $opt{'delete_financials'} ) {
1062 $dbh->rollback if $oldAutoCommit;
1063 return "Can't delete a customer with ". $financial_tables{$table};
1066 foreach my $record ( @records ) {
1067 my $error = $record->delete;
1069 $dbh->rollback if $oldAutoCommit;
1070 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1076 my @cust_pkg = $self->ncancelled_pkgs;
1078 my $new_custnum = $opt{'new_custnum'};
1079 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1080 $dbh->rollback if $oldAutoCommit;
1081 return "Invalid new customer number: $new_custnum";
1083 foreach my $cust_pkg ( @cust_pkg ) {
1084 my %hash = $cust_pkg->hash;
1085 $hash{'custnum'} = $new_custnum;
1086 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1087 my $error = $new_cust_pkg->replace($cust_pkg,
1088 options => { $cust_pkg->options },
1091 $dbh->rollback if $oldAutoCommit;
1096 my @cancelled_cust_pkg = $self->all_pkgs;
1097 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1098 my $error = $cust_pkg->delete;
1100 $dbh->rollback if $oldAutoCommit;
1105 #cust_tax_adjustment in financials?
1106 #cust_pay_pending? ouch
1108 foreach my $table (qw(
1109 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1110 cust_location cust_main_note cust_tax_adjustment
1111 cust_pay_void cust_pay_batch queue cust_tax_exempt
1113 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1114 my $error = $record->delete;
1116 $dbh->rollback if $oldAutoCommit;
1122 my $sth = $dbh->prepare(
1123 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1125 my $errstr = $dbh->errstr;
1126 $dbh->rollback if $oldAutoCommit;
1129 $sth->execute($self->custnum) or do {
1130 my $errstr = $sth->errstr;
1131 $dbh->rollback if $oldAutoCommit;
1137 my $ticket_dbh = '';
1138 if ($conf->config('ticket_system') eq 'RT_Internal') {
1140 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1141 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1142 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1143 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1146 if ( $ticket_dbh ) {
1148 my $ticket_sth = $ticket_dbh->prepare(
1149 'DELETE FROM Links WHERE Target = ?'
1151 my $errstr = $ticket_dbh->errstr;
1152 $dbh->rollback if $oldAutoCommit;
1155 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1157 my $errstr = $ticket_sth->errstr;
1158 $dbh->rollback if $oldAutoCommit;
1162 #check and see if the customer is the only link on the ticket, and
1163 #if so, set the ticket to deleted status in RT?
1164 #maybe someday, for now this will at least fix tickets not displaying
1168 #delete the customer record
1170 my $error = $self->SUPER::delete;
1172 $dbh->rollback if $oldAutoCommit;
1176 # cust_main exports!
1178 #my $export_args = $options{'export_args'} || [];
1181 map qsearch( 'part_export', {exportnum=>$_} ),
1182 $conf->config('cust_main-exports'); #, $agentnum
1184 foreach my $part_export ( @part_export ) {
1185 my $error = $part_export->export_delete( $self ); #, @$export_args);
1187 $dbh->rollback if $oldAutoCommit;
1188 return "exporting to ". $part_export->exporttype.
1189 " (transaction rolled back): $error";
1193 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1198 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1200 This merges this customer into the provided new custnum, and then deletes the
1201 customer. If there is an error, returns the error, otherwise returns false.
1203 The source customer's name, company name, phone numbers, agent,
1204 referring customer, customer class, advertising source, order taker, and
1205 billing information (except balance) are discarded.
1207 All packages are moved to the target customer. Packages with package locations
1208 are preserved. Packages without package locations are moved to a new package
1209 location with the source customer's service/shipping address.
1211 All invoices, statements, payments, credits and refunds are moved to the target
1212 customer. The source customer's balance is added to the target customer.
1214 All notes, attachments, tickets and customer tags are moved to the target
1217 Change history is not currently moved.
1222 my( $self, $new_custnum, %opt ) = @_;
1224 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1226 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1227 return "Invalid new customer number: $new_custnum";
1230 local $SIG{HUP} = 'IGNORE';
1231 local $SIG{INT} = 'IGNORE';
1232 local $SIG{QUIT} = 'IGNORE';
1233 local $SIG{TERM} = 'IGNORE';
1234 local $SIG{TSTP} = 'IGNORE';
1235 local $SIG{PIPE} = 'IGNORE';
1237 my $oldAutoCommit = $FS::UID::AutoCommit;
1238 local $FS::UID::AutoCommit = 0;
1241 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1242 $dbh->rollback if $oldAutoCommit;
1243 return "Can't merge a master agent customer";
1246 #use FS::access_user
1247 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1248 $dbh->rollback if $oldAutoCommit;
1249 return "Can't merge a master employee customer";
1252 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1253 'status' => { op=>'!=', value=>'done' },
1257 $dbh->rollback if $oldAutoCommit;
1258 return "Can't merge a customer with pending payments";
1261 tie my %financial_tables, 'Tie::IxHash',
1262 'cust_bill' => 'invoices',
1263 'cust_statement' => 'statements',
1264 'cust_credit' => 'credits',
1265 'cust_pay' => 'payments',
1266 'cust_pay_void' => 'voided payments',
1267 'cust_refund' => 'refunds',
1270 foreach my $table ( keys %financial_tables ) {
1272 my @records = $self->$table();
1274 foreach my $record ( @records ) {
1275 $record->custnum($new_custnum);
1276 my $error = $record->replace;
1278 $dbh->rollback if $oldAutoCommit;
1279 return "Error merging ". $financial_tables{$table}. ": $error\n";
1285 my $name = $self->ship_name;
1287 my $locationnum = '';
1288 foreach my $cust_pkg ( $self->all_pkgs ) {
1289 $cust_pkg->custnum($new_custnum);
1291 unless ( $cust_pkg->locationnum ) {
1292 unless ( $locationnum ) {
1293 my $cust_location = new FS::cust_location {
1294 $self->location_hash,
1295 'custnum' => $new_custnum,
1297 my $error = $cust_location->insert;
1299 $dbh->rollback if $oldAutoCommit;
1302 $locationnum = $cust_location->locationnum;
1304 $cust_pkg->locationnum($locationnum);
1307 my $error = $cust_pkg->replace;
1309 $dbh->rollback if $oldAutoCommit;
1313 # add customer (ship) name to svc_phone.phone_name if blank
1314 my @cust_svc = $cust_pkg->cust_svc;
1315 foreach my $cust_svc (@cust_svc) {
1316 my($label, $value, $svcdb) = $cust_svc->label;
1317 next unless $svcdb eq 'svc_phone';
1318 my $svc_phone = $cust_svc->svc_x;
1319 next if $svc_phone->phone_name;
1320 $svc_phone->phone_name($name);
1321 my $error = $svc_phone->replace;
1323 $dbh->rollback if $oldAutoCommit;
1331 # cust_tax_exempt (texas tax exemptions)
1332 # cust_recon (some sort of not-well understood thing for OnPac)
1334 #these are moved over
1335 foreach my $table (qw(
1336 cust_tag cust_location contact cust_attachment cust_main_note
1337 cust_tax_adjustment cust_pay_batch queue
1339 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1340 $record->custnum($new_custnum);
1341 my $error = $record->replace;
1343 $dbh->rollback if $oldAutoCommit;
1349 #these aren't preserved
1350 foreach my $table (qw(
1351 cust_main_exemption cust_main_invoice
1353 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1354 my $error = $record->delete;
1356 $dbh->rollback if $oldAutoCommit;
1363 my $sth = $dbh->prepare(
1364 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1366 my $errstr = $dbh->errstr;
1367 $dbh->rollback if $oldAutoCommit;
1370 $sth->execute($new_custnum, $self->custnum) or do {
1371 my $errstr = $sth->errstr;
1372 $dbh->rollback if $oldAutoCommit;
1378 my $ticket_dbh = '';
1379 if ($conf->config('ticket_system') eq 'RT_Internal') {
1381 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1382 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1383 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1384 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1387 if ( $ticket_dbh ) {
1389 my $ticket_sth = $ticket_dbh->prepare(
1390 'UPDATE Links SET Target = ? WHERE Target = ?'
1392 my $errstr = $ticket_dbh->errstr;
1393 $dbh->rollback if $oldAutoCommit;
1396 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1397 'freeside://freeside/cust_main/'.$self->custnum)
1399 my $errstr = $ticket_sth->errstr;
1400 $dbh->rollback if $oldAutoCommit;
1406 #delete the customer record
1408 my $error = $self->delete;
1410 $dbh->rollback if $oldAutoCommit;
1414 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1419 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1422 Replaces the OLD_RECORD with this one in the database. If there is an error,
1423 returns the error, otherwise returns false.
1425 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1426 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1427 expected and rollback the entire transaction; it is not necessary to call
1428 check_invoicing_list first. Here's an example:
1430 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1432 Currently available options are: I<tax_exemption>.
1434 The I<tax_exemption> option can be set to an arrayref of tax names.
1435 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1442 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1444 : $self->replace_old;
1448 warn "$me replace called\n"
1451 my $curuser = $FS::CurrentUser::CurrentUser;
1452 if ( $self->payby eq 'COMP'
1453 && $self->payby ne $old->payby
1454 && ! $curuser->access_right('Complimentary customer')
1457 return "You are not permitted to create complimentary accounts.";
1460 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1461 && $conf->exists('enable_taxproducts')
1464 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1466 $self->set('geocode', '')
1467 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1468 && length($self->get($pre.'zip')) >= 10;
1471 local($ignore_expired_card) = 1
1472 if $old->payby =~ /^(CARD|DCRD)$/
1473 && $self->payby =~ /^(CARD|DCRD)$/
1474 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1476 local($ignore_banned_card) = 1
1477 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1478 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1479 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1481 local $SIG{HUP} = 'IGNORE';
1482 local $SIG{INT} = 'IGNORE';
1483 local $SIG{QUIT} = 'IGNORE';
1484 local $SIG{TERM} = 'IGNORE';
1485 local $SIG{TSTP} = 'IGNORE';
1486 local $SIG{PIPE} = 'IGNORE';
1488 my $oldAutoCommit = $FS::UID::AutoCommit;
1489 local $FS::UID::AutoCommit = 0;
1492 my $error = $self->SUPER::replace($old);
1495 $dbh->rollback if $oldAutoCommit;
1499 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1500 my $invoicing_list = shift @param;
1501 $error = $self->check_invoicing_list( $invoicing_list );
1503 $dbh->rollback if $oldAutoCommit;
1506 $self->invoicing_list( $invoicing_list );
1509 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1511 #this could be more efficient than deleting and re-inserting, if it matters
1512 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1513 my $error = $cust_tag->delete;
1515 $dbh->rollback if $oldAutoCommit;
1519 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1520 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1521 'custnum' => $self->custnum };
1522 my $error = $cust_tag->insert;
1524 $dbh->rollback if $oldAutoCommit;
1531 my %options = @param;
1533 my $tax_exemption = delete $options{'tax_exemption'};
1534 if ( $tax_exemption ) {
1536 my %cust_main_exemption =
1537 map { $_->taxname => $_ }
1538 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1540 foreach my $taxname ( @$tax_exemption ) {
1542 next if delete $cust_main_exemption{$taxname};
1544 my $cust_main_exemption = new FS::cust_main_exemption {
1545 'custnum' => $self->custnum,
1546 'taxname' => $taxname,
1548 my $error = $cust_main_exemption->insert;
1550 $dbh->rollback if $oldAutoCommit;
1551 return "inserting cust_main_exemption (transaction rolled back): $error";
1555 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1556 my $error = $cust_main_exemption->delete;
1558 $dbh->rollback if $oldAutoCommit;
1559 return "deleting cust_main_exemption (transaction rolled back): $error";
1565 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1566 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1567 && $self->get('payinfo') !~ /^99\d{14}$/
1569 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1574 # card/check/lec info has changed, want to retry realtime_ invoice events
1575 my $error = $self->retry_realtime;
1577 $dbh->rollback if $oldAutoCommit;
1582 unless ( $import || $skip_fuzzyfiles ) {
1583 $error = $self->queue_fuzzyfiles_update;
1585 $dbh->rollback if $oldAutoCommit;
1586 return "updating fuzzy search cache: $error";
1590 # cust_main exports!
1592 my $export_args = $options{'export_args'} || [];
1595 map qsearch( 'part_export', {exportnum=>$_} ),
1596 $conf->config('cust_main-exports'); #, $agentnum
1598 foreach my $part_export ( @part_export ) {
1599 my $error = $part_export->export_replace( $self, $old, @$export_args);
1601 $dbh->rollback if $oldAutoCommit;
1602 return "exporting to ". $part_export->exporttype.
1603 " (transaction rolled back): $error";
1607 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1612 =item queue_fuzzyfiles_update
1614 Used by insert & replace to update the fuzzy search cache
1618 sub queue_fuzzyfiles_update {
1621 local $SIG{HUP} = 'IGNORE';
1622 local $SIG{INT} = 'IGNORE';
1623 local $SIG{QUIT} = 'IGNORE';
1624 local $SIG{TERM} = 'IGNORE';
1625 local $SIG{TSTP} = 'IGNORE';
1626 local $SIG{PIPE} = 'IGNORE';
1628 my $oldAutoCommit = $FS::UID::AutoCommit;
1629 local $FS::UID::AutoCommit = 0;
1632 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1633 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1635 $dbh->rollback if $oldAutoCommit;
1636 return "queueing job (transaction rolled back): $error";
1639 if ( $self->ship_last ) {
1640 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1641 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1643 $dbh->rollback if $oldAutoCommit;
1644 return "queueing job (transaction rolled back): $error";
1648 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1655 Checks all fields to make sure this is a valid customer record. If there is
1656 an error, returns the error, otherwise returns false. Called by the insert
1657 and replace methods.
1664 warn "$me check BEFORE: \n". $self->_dump
1668 $self->ut_numbern('custnum')
1669 || $self->ut_number('agentnum')
1670 || $self->ut_textn('agent_custid')
1671 || $self->ut_number('refnum')
1672 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1673 || $self->ut_textn('custbatch')
1674 || $self->ut_name('last')
1675 || $self->ut_name('first')
1676 || $self->ut_snumbern('birthdate')
1677 || $self->ut_snumbern('signupdate')
1678 || $self->ut_textn('company')
1679 || $self->ut_text('address1')
1680 || $self->ut_textn('address2')
1681 || $self->ut_text('city')
1682 || $self->ut_textn('county')
1683 || $self->ut_textn('state')
1684 || $self->ut_country('country')
1685 || $self->ut_anything('comments')
1686 || $self->ut_numbern('referral_custnum')
1687 || $self->ut_textn('stateid')
1688 || $self->ut_textn('stateid_state')
1689 || $self->ut_textn('invoice_terms')
1690 || $self->ut_alphan('geocode')
1691 || $self->ut_floatn('cdr_termination_percentage')
1692 || $self->ut_floatn('credit_limit')
1693 || $self->ut_numbern('billday')
1694 || $self->ut_enum('edit_subject', [ '', 'Y' ] )
1697 #barf. need message catalogs. i18n. etc.
1698 $error .= "Please select an advertising source."
1699 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1700 return $error if $error;
1702 return "Unknown agent"
1703 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1705 return "Unknown refnum"
1706 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1708 return "Unknown referring custnum: ". $self->referral_custnum
1709 unless ! $self->referral_custnum
1710 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1712 if ( $self->censustract ne '' ) {
1713 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1714 or return "Illegal census tract: ". $self->censustract;
1716 $self->censustract("$1.$2");
1719 if ( $self->ss eq '' ) {
1724 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1725 or return "Illegal social security number: ". $self->ss;
1726 $self->ss("$1-$2-$3");
1730 # bad idea to disable, causes billing to fail because of no tax rates later
1731 # except we don't fail any more
1732 unless ( $import ) {
1733 unless ( qsearch('cust_main_county', {
1734 'country' => $self->country,
1737 return "Unknown state/county/country: ".
1738 $self->state. "/". $self->county. "/". $self->country
1739 unless qsearch('cust_main_county',{
1740 'state' => $self->state,
1741 'county' => $self->county,
1742 'country' => $self->country,
1748 $self->ut_phonen('daytime', $self->country)
1749 || $self->ut_phonen('night', $self->country)
1750 || $self->ut_phonen('fax', $self->country)
1752 return $error if $error;
1754 unless ( $ignore_illegal_zip ) {
1755 $error = $self->ut_zip('zip', $self->country);
1756 return $error if $error;
1759 if ( $conf->exists('cust_main-require_phone')
1760 && ! length($self->daytime) && ! length($self->night)
1763 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1765 : FS::Msgcat::_gettext('daytime');
1766 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1768 : FS::Msgcat::_gettext('night');
1770 return "$daytime_label or $night_label is required"
1774 if ( $self->has_ship_address
1775 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1776 $self->addr_fields )
1780 $self->ut_name('ship_last')
1781 || $self->ut_name('ship_first')
1782 || $self->ut_textn('ship_company')
1783 || $self->ut_text('ship_address1')
1784 || $self->ut_textn('ship_address2')
1785 || $self->ut_text('ship_city')
1786 || $self->ut_textn('ship_county')
1787 || $self->ut_textn('ship_state')
1788 || $self->ut_country('ship_country')
1790 return $error if $error;
1792 #false laziness with above
1793 unless ( qsearchs('cust_main_county', {
1794 'country' => $self->ship_country,
1797 return "Unknown ship_state/ship_county/ship_country: ".
1798 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1799 unless qsearch('cust_main_county',{
1800 'state' => $self->ship_state,
1801 'county' => $self->ship_county,
1802 'country' => $self->ship_country,
1808 $self->ut_phonen('ship_daytime', $self->ship_country)
1809 || $self->ut_phonen('ship_night', $self->ship_country)
1810 || $self->ut_phonen('ship_fax', $self->ship_country)
1812 return $error if $error;
1814 unless ( $ignore_illegal_zip ) {
1815 $error = $self->ut_zip('ship_zip', $self->ship_country);
1816 return $error if $error;
1818 return "Unit # is required."
1819 if $self->ship_address2 =~ /^\s*$/
1820 && $conf->exists('cust_main-require_address2');
1822 } else { # ship_ info eq billing info, so don't store dup info in database
1824 $self->setfield("ship_$_", '')
1825 foreach $self->addr_fields;
1827 return "Unit # is required."
1828 if $self->address2 =~ /^\s*$/
1829 && $conf->exists('cust_main-require_address2');
1833 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1834 # or return "Illegal payby: ". $self->payby;
1836 FS::payby->can_payby($self->table, $self->payby)
1837 or return "Illegal payby: ". $self->payby;
1839 $error = $self->ut_numbern('paystart_month')
1840 || $self->ut_numbern('paystart_year')
1841 || $self->ut_numbern('payissue')
1842 || $self->ut_textn('paytype')
1844 return $error if $error;
1846 if ( $self->payip eq '' ) {
1849 $error = $self->ut_ip('payip');
1850 return $error if $error;
1853 # If it is encrypted and the private key is not availaible then we can't
1854 # check the credit card.
1855 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1857 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1859 my $payinfo = $self->payinfo;
1860 $payinfo =~ s/\D//g;
1861 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1862 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1864 $self->payinfo($payinfo);
1866 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1868 return gettext('unknown_card_type')
1869 if $self->payinfo !~ /^99\d{14}$/ #token
1870 && cardtype($self->payinfo) eq "Unknown";
1872 unless ( $ignore_banned_card ) {
1873 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1875 if ( $ban->bantype eq 'warn' ) {
1876 #or others depending on value of $ban->reason ?
1877 return '_duplicate_card'.
1878 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1879 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1880 ' (ban# '. $ban->bannum. ')'
1881 unless $self->override_ban_warn;
1883 return 'Banned credit card: banned on '.
1884 time2str('%a %h %o at %r', $ban->_date).
1885 ' by '. $ban->otaker.
1886 ' (ban# '. $ban->bannum. ')';
1891 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1892 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1893 $self->paycvv =~ /^(\d{4})$/
1894 or return "CVV2 (CID) for American Express cards is four digits.";
1897 $self->paycvv =~ /^(\d{3})$/
1898 or return "CVV2 (CVC2/CID) is three digits.";
1905 my $cardtype = cardtype($payinfo);
1906 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1908 return "Start date or issue number is required for $cardtype cards"
1909 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1911 return "Start month must be between 1 and 12"
1912 if $self->paystart_month
1913 and $self->paystart_month < 1 || $self->paystart_month > 12;
1915 return "Start year must be 1990 or later"
1916 if $self->paystart_year
1917 and $self->paystart_year < 1990;
1919 return "Issue number must be beween 1 and 99"
1921 and $self->payissue < 1 || $self->payissue > 99;
1924 $self->paystart_month('');
1925 $self->paystart_year('');
1926 $self->payissue('');
1929 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1931 my $payinfo = $self->payinfo;
1932 $payinfo =~ s/[^\d\@\.]//g;
1933 if ( $conf->exists('cust_main-require-bank-branch') ) {
1934 $payinfo =~ /^(\d+)\@(\d+)\.(\d+)$/ or return 'invalid echeck account@branch.bank';
1935 $payinfo = "$1\@$2.$3";
1936 } elsif ( $conf->exists('echeck-no_routing') ) {
1937 $payinfo =~ /^(\d+)\@(\d*)$/ or return 'invalid echeck account';
1938 $payinfo = "$1\@$2";
1939 } elsif ( $conf->exists('echeck-nonus') ) {
1940 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1941 $payinfo = "$1\@$2";
1943 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1944 $payinfo = "$1\@$2";
1946 $self->payinfo($payinfo);
1949 unless ( $ignore_banned_card ) {
1950 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1952 if ( $ban->bantype eq 'warn' ) {
1953 #or others depending on value of $ban->reason ?
1954 return '_duplicate_ach' unless $self->override_ban_warn;
1956 return 'Banned ACH account: banned on '.
1957 time2str('%a %h %o at %r', $ban->_date).
1958 ' by '. $ban->otaker.
1959 ' (ban# '. $ban->bannum. ')';
1964 } elsif ( $self->payby eq 'LECB' ) {
1966 my $payinfo = $self->payinfo;
1967 $payinfo =~ s/\D//g;
1968 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1970 $self->payinfo($payinfo);
1973 } elsif ( $self->payby eq 'BILL' ) {
1975 $error = $self->ut_textn('payinfo');
1976 return "Illegal P.O. number: ". $self->payinfo if $error;
1979 } elsif ( $self->payby eq 'COMP' ) {
1981 my $curuser = $FS::CurrentUser::CurrentUser;
1982 if ( ! $self->custnum
1983 && ! $curuser->access_right('Complimentary customer')
1986 return "You are not permitted to create complimentary accounts."
1989 $error = $self->ut_textn('payinfo');
1990 return "Illegal comp account issuer: ". $self->payinfo if $error;
1993 } elsif ( $self->payby eq 'PREPAY' ) {
1995 my $payinfo = $self->payinfo;
1996 $payinfo =~ s/\W//g; #anything else would just confuse things
1997 $self->payinfo($payinfo);
1998 $error = $self->ut_alpha('payinfo');
1999 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2000 return "Unknown prepayment identifier"
2001 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2006 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2007 return "Expiration date required"
2008 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2012 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2013 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2014 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2015 ( $m, $y ) = ( $2, "19$1" );
2016 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2017 ( $m, $y ) = ( $3, "20$2" );
2019 return "Illegal expiration date: ". $self->paydate;
2021 $m = sprintf('%02d',$m);
2022 $self->paydate("$y-$m-01");
2023 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2024 return gettext('expired_card')
2026 && !$ignore_expired_card
2027 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2030 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2031 ( ! $conf->exists('require_cardname')
2032 || $self->payby !~ /^(CARD|DCRD)$/ )
2034 $self->payname( $self->first. " ". $self->getfield('last') );
2036 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2037 or return gettext('illegal_name'). " payname: ". $self->payname;
2041 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2042 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2046 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2048 warn "$me check AFTER: \n". $self->_dump
2051 $self->SUPER::check;
2056 Returns a list of fields which have ship_ duplicates.
2061 qw( last first company
2062 address1 address2 city county state zip country
2067 =item has_ship_address
2069 Returns true if this customer record has a separate shipping address.
2073 sub has_ship_address {
2075 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2080 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2081 city, county, state, zip, country, and geocode. The shipping address is used if present.
2087 Returns all locations (see L<FS::cust_location>) for this customer.
2093 qsearch('cust_location', { 'custnum' => $self->custnum } );
2098 Returns all contacts (see L<FS::contact>) for this customer.
2102 #already used :/ sub contact {
2105 qsearch('contact', { 'custnum' => $self->custnum } );
2110 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2111 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2112 on success or a list of errors.
2118 grep { $_->unsuspend } $self->suspended_pkgs;
2123 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2125 Returns a list: an empty list on success or a list of errors.
2131 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2134 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2136 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2137 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2138 of a list of pkgparts; the hashref has the following keys:
2142 =item pkgparts - listref of pkgparts
2144 =item (other options are passed to the suspend method)
2149 Returns a list: an empty list on success or a list of errors.
2153 sub suspend_if_pkgpart {
2155 my (@pkgparts, %opt);
2156 if (ref($_[0]) eq 'HASH'){
2157 @pkgparts = @{$_[0]{pkgparts}};
2162 grep { $_->suspend(%opt) }
2163 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2164 $self->unsuspended_pkgs;
2167 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2169 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2170 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2171 instead of a list of pkgparts; the hashref has the following keys:
2175 =item pkgparts - listref of pkgparts
2177 =item (other options are passed to the suspend method)
2181 Returns a list: an empty list on success or a list of errors.
2185 sub suspend_unless_pkgpart {
2187 my (@pkgparts, %opt);
2188 if (ref($_[0]) eq 'HASH'){
2189 @pkgparts = @{$_[0]{pkgparts}};
2194 grep { $_->suspend(%opt) }
2195 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2196 $self->unsuspended_pkgs;
2199 =item cancel [ OPTION => VALUE ... ]
2201 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2203 Available options are:
2207 =item quiet - can be set true to supress email cancellation notices.
2209 =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.
2211 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2213 =item nobill - can be set true to skip billing if it might otherwise be done.
2217 Always returns a list: an empty list on success or a list of errors.
2221 # nb that dates are not specified as valid options to this method
2224 my( $self, %opt ) = @_;
2226 warn "$me cancel called on customer ". $self->custnum. " with options ".
2227 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2230 return ( 'access denied' )
2231 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2233 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2235 #should try decryption (we might have the private key)
2236 # and if not maybe queue a job for the server that does?
2237 return ( "Can't (yet) ban encrypted credit cards" )
2238 if $self->is_encrypted($self->payinfo);
2240 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2241 my $error = $ban->insert;
2242 return ( $error ) if $error;
2246 my @pkgs = $self->ncancelled_pkgs;
2248 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2250 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2251 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2255 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2256 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2259 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2262 sub _banned_pay_hashref {
2273 'payby' => $payby2ban{$self->payby},
2274 'payinfo' => $self->payinfo,
2275 #don't ever *search* on reason! #'reason' =>
2279 sub _new_banned_pay_hashref {
2281 my $hr = $self->_banned_pay_hashref;
2282 $hr->{payinfo} = md5_base64($hr->{payinfo});
2288 Returns all notes (see L<FS::cust_main_note>) for this customer.
2293 my($self,$orderby_classnum) = (shift,shift);
2294 my $orderby = "_DATE DESC";
2295 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2296 qsearch( 'cust_main_note',
2297 { 'custnum' => $self->custnum },
2299 "ORDER BY $orderby",
2305 Returns the agent (see L<FS::agent>) for this customer.
2311 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2316 Returns the agent name (see L<FS::agent>) for this customer.
2322 $self->agent->agent;
2327 Returns any tags associated with this customer, as FS::cust_tag objects,
2328 or an empty list if there are no tags.
2334 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2339 Returns any tags associated with this customer, as FS::part_tag objects,
2340 or an empty list if there are no tags.
2346 map $_->part_tag, $self->cust_tag;
2352 Returns the customer class, as an FS::cust_class object, or the empty string
2353 if there is no customer class.
2359 if ( $self->classnum ) {
2360 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2368 Returns the customer category name, or the empty string if there is no customer
2375 my $cust_class = $self->cust_class;
2377 ? $cust_class->categoryname
2383 Returns the customer class name, or the empty string if there is no customer
2390 my $cust_class = $self->cust_class;
2392 ? $cust_class->classname
2396 =item BILLING METHODS
2398 Documentation on billing methods has been moved to
2399 L<FS::cust_main::Billing>.
2401 =item REALTIME BILLING METHODS
2403 Documentation on realtime billing methods has been moved to
2404 L<FS::cust_main::Billing_Realtime>.
2408 Removes the I<paycvv> field from the database directly.
2410 If there is an error, returns the error, otherwise returns false.
2416 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2417 or return dbh->errstr;
2418 $sth->execute($self->custnum)
2419 or return $sth->errstr;
2424 =item batch_card OPTION => VALUE...
2426 Adds a payment for this invoice to the pending credit card batch (see
2427 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2428 runs the payment using a realtime gateway.
2433 my ($self, %options) = @_;
2436 if (exists($options{amount})) {
2437 $amount = $options{amount};
2439 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2441 return '' unless $amount > 0;
2443 my $invnum = delete $options{invnum};
2444 my $payby = $options{payby} || $self->payby; #still dubious
2446 if ($options{'realtime'}) {
2447 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2453 my $oldAutoCommit = $FS::UID::AutoCommit;
2454 local $FS::UID::AutoCommit = 0;
2457 #this needs to handle mysql as well as Pg, like svc_acct.pm
2458 #(make it into a common function if folks need to do batching with mysql)
2459 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2460 or return "Cannot lock pay_batch: " . $dbh->errstr;
2464 'payby' => FS::payby->payby2payment($payby),
2467 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2469 unless ( $pay_batch ) {
2470 $pay_batch = new FS::pay_batch \%pay_batch;
2471 my $error = $pay_batch->insert;
2473 $dbh->rollback if $oldAutoCommit;
2474 die "error creating new batch: $error\n";
2478 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2479 'batchnum' => $pay_batch->batchnum,
2480 'custnum' => $self->custnum,
2483 foreach (qw( address1 address2 city state zip country payby payinfo paydate
2485 $options{$_} = '' unless exists($options{$_});
2488 my $cust_pay_batch = new FS::cust_pay_batch ( {
2489 'batchnum' => $pay_batch->batchnum,
2490 'invnum' => $invnum || 0, # is there a better value?
2491 # this field should be
2493 # cust_bill_pay_batch now
2494 'custnum' => $self->custnum,
2495 'last' => $self->getfield('last'),
2496 'first' => $self->getfield('first'),
2497 'address1' => $options{address1} || $self->address1,
2498 'address2' => $options{address2} || $self->address2,
2499 'city' => $options{city} || $self->city,
2500 'state' => $options{state} || $self->state,
2501 'zip' => $options{zip} || $self->zip,
2502 'country' => $options{country} || $self->country,
2503 'payby' => $options{payby} || $self->payby,
2504 'payinfo' => $options{payinfo} || $self->payinfo,
2505 'exp' => $options{paydate} || $self->paydate,
2506 'payname' => $options{payname} || $self->payname,
2507 'amount' => $amount, # consolidating
2510 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2511 if $old_cust_pay_batch;
2514 if ($old_cust_pay_batch) {
2515 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2517 $error = $cust_pay_batch->insert;
2521 $dbh->rollback if $oldAutoCommit;
2525 my $unapplied = $self->total_unapplied_credits
2526 + $self->total_unapplied_payments
2527 + $self->in_transit_payments;
2528 foreach my $cust_bill ($self->open_cust_bill) {
2529 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2530 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2531 'invnum' => $cust_bill->invnum,
2532 'paybatchnum' => $cust_pay_batch->paybatchnum,
2533 'amount' => $cust_bill->owed,
2536 if ($unapplied >= $cust_bill_pay_batch->amount){
2537 $unapplied -= $cust_bill_pay_batch->amount;
2540 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2541 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2543 $error = $cust_bill_pay_batch->insert;
2545 $dbh->rollback if $oldAutoCommit;
2550 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2556 Returns the total owed for this customer on all invoices
2557 (see L<FS::cust_bill/owed>).
2563 $self->total_owed_date(2145859200); #12/31/2037
2566 =item total_owed_date TIME
2568 Returns the total owed for this customer on all invoices with date earlier than
2569 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2570 see L<Time::Local> and L<Date::Parse> for conversion functions.
2574 sub total_owed_date {
2578 my $custnum = $self->custnum;
2580 my $owed_sql = FS::cust_bill->owed_sql;
2583 SELECT SUM($owed_sql) FROM cust_bill
2584 WHERE custnum = $custnum
2588 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2592 =item total_owed_pkgnum PKGNUM
2594 Returns the total owed on all invoices for this customer's specific package
2595 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2599 sub total_owed_pkgnum {
2600 my( $self, $pkgnum ) = @_;
2601 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2604 =item total_owed_date_pkgnum TIME PKGNUM
2606 Returns the total owed for this customer's specific package when using
2607 experimental package balances on all invoices with date earlier than
2608 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2609 see L<Time::Local> and L<Date::Parse> for conversion functions.
2613 sub total_owed_date_pkgnum {
2614 my( $self, $time, $pkgnum ) = @_;
2617 foreach my $cust_bill (
2618 grep { $_->_date <= $time }
2619 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2621 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2623 sprintf( "%.2f", $total_bill );
2629 Returns the total amount of all payments.
2636 $total += $_->paid foreach $self->cust_pay;
2637 sprintf( "%.2f", $total );
2640 =item total_unapplied_credits
2642 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2643 customer. See L<FS::cust_credit/credited>.
2645 =item total_credited
2647 Old name for total_unapplied_credits. Don't use.
2651 sub total_credited {
2652 #carp "total_credited deprecated, use total_unapplied_credits";
2653 shift->total_unapplied_credits(@_);
2656 sub total_unapplied_credits {
2659 my $custnum = $self->custnum;
2661 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2664 SELECT SUM($unapplied_sql) FROM cust_credit
2665 WHERE custnum = $custnum
2668 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2672 =item total_unapplied_credits_pkgnum PKGNUM
2674 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2675 customer. See L<FS::cust_credit/credited>.
2679 sub total_unapplied_credits_pkgnum {
2680 my( $self, $pkgnum ) = @_;
2681 my $total_credit = 0;
2682 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2683 sprintf( "%.2f", $total_credit );
2687 =item total_unapplied_payments
2689 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2690 See L<FS::cust_pay/unapplied>.
2694 sub total_unapplied_payments {
2697 my $custnum = $self->custnum;
2699 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2702 SELECT SUM($unapplied_sql) FROM cust_pay
2703 WHERE custnum = $custnum
2706 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2710 =item total_unapplied_payments_pkgnum PKGNUM
2712 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2713 specific package when using experimental package balances. See
2714 L<FS::cust_pay/unapplied>.
2718 sub total_unapplied_payments_pkgnum {
2719 my( $self, $pkgnum ) = @_;
2720 my $total_unapplied = 0;
2721 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2722 sprintf( "%.2f", $total_unapplied );
2726 =item total_unapplied_refunds
2728 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2729 customer. See L<FS::cust_refund/unapplied>.
2733 sub total_unapplied_refunds {
2735 my $custnum = $self->custnum;
2737 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2740 SELECT SUM($unapplied_sql) FROM cust_refund
2741 WHERE custnum = $custnum
2744 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2750 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2751 total_unapplied_credits minus total_unapplied_payments).
2757 $self->balance_date_range;
2760 =item balance_date TIME
2762 Returns the balance for this customer, only considering invoices with date
2763 earlier than TIME (total_owed_date minus total_credited minus
2764 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2765 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2772 $self->balance_date_range(shift);
2775 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2777 Returns the balance for this customer, optionally considering invoices with
2778 date earlier than START_TIME, and not later than END_TIME
2779 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2781 Times are specified as SQL fragments or numeric
2782 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2783 L<Date::Parse> for conversion functions. The empty string can be passed
2784 to disable that time constraint completely.
2786 Available options are:
2790 =item unapplied_date
2792 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)
2798 sub balance_date_range {
2800 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2801 ') FROM cust_main WHERE custnum='. $self->custnum;
2802 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2805 =item balance_pkgnum PKGNUM
2807 Returns the balance for this customer's specific package when using
2808 experimental package balances (total_owed plus total_unrefunded, minus
2809 total_unapplied_credits minus total_unapplied_payments)
2813 sub balance_pkgnum {
2814 my( $self, $pkgnum ) = @_;
2817 $self->total_owed_pkgnum($pkgnum)
2818 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2819 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2820 - $self->total_unapplied_credits_pkgnum($pkgnum)
2821 - $self->total_unapplied_payments_pkgnum($pkgnum)
2825 =item in_transit_payments
2827 Returns the total of requests for payments for this customer pending in
2828 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2832 sub in_transit_payments {
2834 my $in_transit_payments = 0;
2835 foreach my $pay_batch ( qsearch('pay_batch', {
2838 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2839 'batchnum' => $pay_batch->batchnum,
2840 'custnum' => $self->custnum,
2842 $in_transit_payments += $cust_pay_batch->amount;
2845 sprintf( "%.2f", $in_transit_payments );
2850 Returns a hash of useful information for making a payment.
2860 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2861 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2862 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2866 For credit card transactions:
2878 For electronic check transactions:
2893 $return{balance} = $self->balance;
2895 $return{payname} = $self->payname
2896 || ( $self->first. ' '. $self->get('last') );
2898 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
2900 $return{payby} = $self->payby;
2901 $return{stateid_state} = $self->stateid_state;
2903 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2904 $return{card_type} = cardtype($self->payinfo);
2905 $return{payinfo} = $self->paymask;
2907 @return{'month', 'year'} = $self->paydate_monthyear;
2911 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2912 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2913 $return{payinfo1} = $payinfo1;
2914 $return{payinfo2} = $payinfo2;
2915 $return{paytype} = $self->paytype;
2916 $return{paystate} = $self->paystate;
2920 #doubleclick protection
2922 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2928 =item paydate_monthyear
2930 Returns a two-element list consisting of the month and year of this customer's
2931 paydate (credit card expiration date for CARD customers)
2935 sub paydate_monthyear {
2937 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2939 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2948 Returns the exact time in seconds corresponding to the payment method
2949 expiration date. For CARD/DCRD customers this is the end of the month;
2950 for others (COMP is the only other payby that uses paydate) it's the start.
2951 Returns 0 if the paydate is empty or set to the far future.
2957 my ($month, $year) = $self->paydate_monthyear;
2958 return 0 if !$year or $year >= 2037;
2959 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2961 if ( $month == 13 ) {
2965 return timelocal(0,0,0,1,$month-1,$year) - 1;
2968 return timelocal(0,0,0,1,$month-1,$year);
2972 =item paydate_epoch_sql
2974 Class method. Returns an SQL expression to obtain the payment expiration date
2975 as a number of seconds.
2979 # Special expiration date behavior for non-CARD/DCRD customers has been
2980 # carefully preserved. Do we really use that?
2981 sub paydate_epoch_sql {
2983 my $table = shift || 'cust_main';
2984 my ($case1, $case2);
2985 if ( driver_name eq 'Pg' ) {
2986 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2987 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2989 elsif ( lc(driver_name) eq 'mysql' ) {
2990 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2991 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2994 return "CASE WHEN $table.payby IN('CARD','DCRD')
3000 =item tax_exemption TAXNAME
3005 my( $self, $taxname ) = @_;
3007 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3008 'taxname' => $taxname,
3013 =item cust_main_exemption
3017 sub cust_main_exemption {
3019 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3022 =item invoicing_list [ ARRAYREF ]
3024 If an arguement is given, sets these email addresses as invoice recipients
3025 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3026 (except as warnings), so use check_invoicing_list first.
3028 Returns a list of email addresses (with svcnum entries expanded).
3030 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3031 check it without disturbing anything by passing nothing.
3033 This interface may change in the future.
3037 sub invoicing_list {
3038 my( $self, $arrayref ) = @_;
3041 my @cust_main_invoice;
3042 if ( $self->custnum ) {
3043 @cust_main_invoice =
3044 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3046 @cust_main_invoice = ();
3048 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3049 #warn $cust_main_invoice->destnum;
3050 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3051 #warn $cust_main_invoice->destnum;
3052 my $error = $cust_main_invoice->delete;
3053 warn $error if $error;
3056 if ( $self->custnum ) {
3057 @cust_main_invoice =
3058 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3060 @cust_main_invoice = ();
3062 my %seen = map { $_->address => 1 } @cust_main_invoice;
3063 foreach my $address ( @{$arrayref} ) {
3064 next if exists $seen{$address} && $seen{$address};
3065 $seen{$address} = 1;
3066 my $cust_main_invoice = new FS::cust_main_invoice ( {
3067 'custnum' => $self->custnum,
3070 my $error = $cust_main_invoice->insert;
3071 warn $error if $error;
3075 if ( $self->custnum ) {
3077 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3084 =item check_invoicing_list ARRAYREF
3086 Checks these arguements as valid input for the invoicing_list method. If there
3087 is an error, returns the error, otherwise returns false.
3091 sub check_invoicing_list {
3092 my( $self, $arrayref ) = @_;
3094 foreach my $address ( @$arrayref ) {
3096 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3097 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3100 my $cust_main_invoice = new FS::cust_main_invoice ( {
3101 'custnum' => $self->custnum,
3104 my $error = $self->custnum
3105 ? $cust_main_invoice->check
3106 : $cust_main_invoice->checkdest
3108 return $error if $error;
3112 return "Email address required"
3113 if $conf->exists('cust_main-require_invoicing_list_email')
3114 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3119 =item set_default_invoicing_list
3121 Sets the invoicing list to all accounts associated with this customer,
3122 overwriting any previous invoicing list.
3126 sub set_default_invoicing_list {
3128 $self->invoicing_list($self->all_emails);
3133 Returns the email addresses of all accounts provisioned for this customer.
3140 foreach my $cust_pkg ( $self->all_pkgs ) {
3141 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3143 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3144 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3146 $list{$_}=1 foreach map { $_->email } @svc_acct;
3151 =item invoicing_list_addpost
3153 Adds postal invoicing to this customer. If this customer is already configured
3154 to receive postal invoices, does nothing.
3158 sub invoicing_list_addpost {
3160 return if grep { $_ eq 'POST' } $self->invoicing_list;
3161 my @invoicing_list = $self->invoicing_list;
3162 push @invoicing_list, 'POST';
3163 $self->invoicing_list(\@invoicing_list);
3166 =item invoicing_list_emailonly
3168 Returns the list of email invoice recipients (invoicing_list without non-email
3169 destinations such as POST and FAX).
3173 sub invoicing_list_emailonly {
3175 warn "$me invoicing_list_emailonly called"
3177 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3180 =item invoicing_list_emailonly_scalar
3182 Returns the list of email invoice recipients (invoicing_list without non-email
3183 destinations such as POST and FAX) as a comma-separated scalar.
3187 sub invoicing_list_emailonly_scalar {
3189 warn "$me invoicing_list_emailonly_scalar called"
3191 join(', ', $self->invoicing_list_emailonly);
3194 =item referral_custnum_cust_main
3196 Returns the customer who referred this customer (or the empty string, if
3197 this customer was not referred).
3199 Note the difference with referral_cust_main method: This method,
3200 referral_custnum_cust_main returns the single customer (if any) who referred
3201 this customer, while referral_cust_main returns an array of customers referred
3206 sub referral_custnum_cust_main {
3208 return '' unless $self->referral_custnum;
3209 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3212 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3214 Returns an array of customers referred by this customer (referral_custnum set
3215 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3216 customers referred by customers referred by this customer and so on, inclusive.
3217 The default behavior is DEPTH 1 (no recursion).
3219 Note the difference with referral_custnum_cust_main method: This method,
3220 referral_cust_main, returns an array of customers referred BY this customer,
3221 while referral_custnum_cust_main returns the single customer (if any) who
3222 referred this customer.
3226 sub referral_cust_main {
3228 my $depth = @_ ? shift : 1;
3229 my $exclude = @_ ? shift : {};
3232 map { $exclude->{$_->custnum}++; $_; }
3233 grep { ! $exclude->{ $_->custnum } }
3234 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3238 map { $_->referral_cust_main($depth-1, $exclude) }
3245 =item referral_cust_main_ncancelled
3247 Same as referral_cust_main, except only returns customers with uncancelled
3252 sub referral_cust_main_ncancelled {
3254 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3257 =item referral_cust_pkg [ DEPTH ]
3259 Like referral_cust_main, except returns a flat list of all unsuspended (and
3260 uncancelled) packages for each customer. The number of items in this list may
3261 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3265 sub referral_cust_pkg {
3267 my $depth = @_ ? shift : 1;
3269 map { $_->unsuspended_pkgs }
3270 grep { $_->unsuspended_pkgs }
3271 $self->referral_cust_main($depth);
3274 =item referring_cust_main
3276 Returns the single cust_main record for the customer who referred this customer
3277 (referral_custnum), or false.
3281 sub referring_cust_main {
3283 return '' unless $self->referral_custnum;
3284 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3287 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3289 Applies a credit to this customer. If there is an error, returns the error,
3290 otherwise returns false.
3292 REASON can be a text string, an FS::reason object, or a scalar reference to
3293 a reasonnum. If a text string, it will be automatically inserted as a new
3294 reason, and a 'reason_type' option must be passed to indicate the
3295 FS::reason_type for the new reason.
3297 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3299 Any other options are passed to FS::cust_credit::insert.
3304 my( $self, $amount, $reason, %options ) = @_;
3306 my $cust_credit = new FS::cust_credit {
3307 'custnum' => $self->custnum,
3308 'amount' => $amount,
3311 if ( ref($reason) ) {
3313 if ( ref($reason) eq 'SCALAR' ) {
3314 $cust_credit->reasonnum( $$reason );
3316 $cust_credit->reasonnum( $reason->reasonnum );
3320 $cust_credit->set('reason', $reason)
3323 for (qw( addlinfo eventnum )) {
3324 $cust_credit->$_( delete $options{$_} )
3325 if exists($options{$_});
3328 $cust_credit->insert(%options);
3332 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3334 Creates a one-time charge for this customer. If there is an error, returns
3335 the error, otherwise returns false.
3337 New-style, with a hashref of options:
3339 my $error = $cust_main->charge(
3343 'start_date' => str2time('7/4/2009'),
3344 'pkg' => 'Description',
3345 'comment' => 'Comment',
3346 'additional' => [], #extra invoice detail
3347 'classnum' => 1, #pkg_class
3349 'setuptax' => '', # or 'Y' for tax exempt
3352 'taxclass' => 'Tax class',
3355 'taxproduct' => 2, #part_pkg_taxproduct
3356 'override' => {}, #XXX describe
3358 #will be filled in with the new object
3359 'cust_pkg_ref' => \$cust_pkg,
3361 #generate an invoice immediately
3363 'invoice_terms' => '', #with these terms
3369 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3375 my ( $amount, $quantity, $start_date, $classnum );
3376 my ( $pkg, $comment, $additional );
3377 my ( $setuptax, $taxclass ); #internal taxes
3378 my ( $taxproduct, $override ); #vendor (CCH) taxes
3380 my $cust_pkg_ref = '';
3381 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3382 if ( ref( $_[0] ) ) {
3383 $amount = $_[0]->{amount};
3384 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3385 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3386 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3387 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3388 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3389 : '$'. sprintf("%.2f",$amount);
3390 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3391 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3392 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3393 $additional = $_[0]->{additional} || [];
3394 $taxproduct = $_[0]->{taxproductnum};
3395 $override = { '' => $_[0]->{tax_override} };
3396 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3397 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3398 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3403 $pkg = @_ ? shift : 'One-time charge';
3404 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3406 $taxclass = @_ ? shift : '';
3410 local $SIG{HUP} = 'IGNORE';
3411 local $SIG{INT} = 'IGNORE';
3412 local $SIG{QUIT} = 'IGNORE';
3413 local $SIG{TERM} = 'IGNORE';
3414 local $SIG{TSTP} = 'IGNORE';
3415 local $SIG{PIPE} = 'IGNORE';
3417 my $oldAutoCommit = $FS::UID::AutoCommit;
3418 local $FS::UID::AutoCommit = 0;
3421 my $part_pkg = new FS::part_pkg ( {
3423 'comment' => $comment,
3427 'classnum' => ( $classnum ? $classnum : '' ),
3428 'setuptax' => $setuptax,
3429 'taxclass' => $taxclass,
3430 'taxproductnum' => $taxproduct,
3433 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3434 ( 0 .. @$additional - 1 )
3436 'additional_count' => scalar(@$additional),
3437 'setup_fee' => $amount,
3440 my $error = $part_pkg->insert( options => \%options,
3441 tax_overrides => $override,
3444 $dbh->rollback if $oldAutoCommit;
3448 my $pkgpart = $part_pkg->pkgpart;
3449 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3450 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3451 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3452 $error = $type_pkgs->insert;
3454 $dbh->rollback if $oldAutoCommit;
3459 my $cust_pkg = new FS::cust_pkg ( {
3460 'custnum' => $self->custnum,
3461 'pkgpart' => $pkgpart,
3462 'quantity' => $quantity,
3463 'start_date' => $start_date,
3464 'no_auto' => $no_auto,
3467 $error = $cust_pkg->insert;
3469 $dbh->rollback if $oldAutoCommit;
3471 } elsif ( $cust_pkg_ref ) {
3472 ${$cust_pkg_ref} = $cust_pkg;
3476 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3477 'pkg_list' => [ $cust_pkg ],
3480 $dbh->rollback if $oldAutoCommit;
3485 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3490 #=item charge_postal_fee
3492 #Applies a one time charge this customer. If there is an error,
3493 #returns the error, returns the cust_pkg charge object or false
3494 #if there was no charge.
3498 # This should be a customer event. For that to work requires that bill
3499 # also be a customer event.
3501 sub charge_postal_fee {
3504 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3505 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3507 my $cust_pkg = new FS::cust_pkg ( {
3508 'custnum' => $self->custnum,
3509 'pkgpart' => $pkgpart,
3513 my $error = $cust_pkg->insert;
3514 $error ? $error : $cust_pkg;
3517 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3519 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3521 Optionally, a list or hashref of additional arguments to the qsearch call can
3528 my $opt = ref($_[0]) ? shift : { @_ };
3530 #return $self->num_cust_bill unless wantarray || keys %$opt;
3532 $opt->{'table'} = 'cust_bill';
3533 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3534 $opt->{'hashref'}{'custnum'} = $self->custnum;
3535 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3537 map { $_ } #behavior of sort undefined in scalar context
3538 sort { $a->_date <=> $b->_date }
3542 =item open_cust_bill
3544 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3549 sub open_cust_bill {
3553 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3559 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3561 Returns all the statements (see L<FS::cust_statement>) for this customer.
3563 Optionally, a list or hashref of additional arguments to the qsearch call can
3568 sub cust_statement {
3570 my $opt = ref($_[0]) ? shift : { @_ };
3572 #return $self->num_cust_statement unless wantarray || keys %$opt;
3574 $opt->{'table'} = 'cust_statement';
3575 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3576 $opt->{'hashref'}{'custnum'} = $self->custnum;
3577 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3579 map { $_ } #behavior of sort undefined in scalar context
3580 sort { $a->_date <=> $b->_date }
3586 Returns all the credits (see L<FS::cust_credit>) for this customer.
3592 map { $_ } #return $self->num_cust_credit unless wantarray;
3593 sort { $a->_date <=> $b->_date }
3594 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3597 =item cust_credit_pkgnum
3599 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3600 package when using experimental package balances.
3604 sub cust_credit_pkgnum {
3605 my( $self, $pkgnum ) = @_;
3606 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3607 sort { $a->_date <=> $b->_date }
3608 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3609 'pkgnum' => $pkgnum,
3616 Returns all the payments (see L<FS::cust_pay>) for this customer.
3622 return $self->num_cust_pay unless wantarray;
3623 sort { $a->_date <=> $b->_date }
3624 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3629 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3630 called automatically when the cust_pay method is used in a scalar context.
3636 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3637 my $sth = dbh->prepare($sql) or die dbh->errstr;
3638 $sth->execute($self->custnum) or die $sth->errstr;
3639 $sth->fetchrow_arrayref->[0];
3642 =item cust_pay_pkgnum
3644 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3645 package when using experimental package balances.
3649 sub cust_pay_pkgnum {
3650 my( $self, $pkgnum ) = @_;
3651 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3652 sort { $a->_date <=> $b->_date }
3653 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3654 'pkgnum' => $pkgnum,
3661 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3667 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3668 sort { $a->_date <=> $b->_date }
3669 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3672 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3674 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3676 Optionally, a list or hashref of additional arguments to the qsearch call can
3681 sub cust_pay_batch {
3683 my $opt = ref($_[0]) ? shift : { @_ };
3685 #return $self->num_cust_statement unless wantarray || keys %$opt;
3687 $opt->{'table'} = 'cust_pay_batch';
3688 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3689 $opt->{'hashref'}{'custnum'} = $self->custnum;
3690 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3692 map { $_ } #behavior of sort undefined in scalar context
3693 sort { $a->paybatchnum <=> $b->paybatchnum }
3697 =item cust_pay_pending
3699 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3700 (without status "done").
3704 sub cust_pay_pending {
3706 return $self->num_cust_pay_pending unless wantarray;
3707 sort { $a->_date <=> $b->_date }
3708 qsearch( 'cust_pay_pending', {
3709 'custnum' => $self->custnum,
3710 'status' => { op=>'!=', value=>'done' },
3715 =item cust_pay_pending_attempt
3717 Returns all payment attempts / declined payments for this customer, as pending
3718 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3719 a corresponding payment (see L<FS::cust_pay>).
3723 sub cust_pay_pending_attempt {
3725 return $self->num_cust_pay_pending_attempt unless wantarray;
3726 sort { $a->_date <=> $b->_date }
3727 qsearch( 'cust_pay_pending', {
3728 'custnum' => $self->custnum,
3735 =item num_cust_pay_pending
3737 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3738 customer (without status "done"). Also called automatically when the
3739 cust_pay_pending method is used in a scalar context.
3743 sub num_cust_pay_pending {
3746 " SELECT COUNT(*) FROM cust_pay_pending ".
3747 " WHERE custnum = ? AND status != 'done' ",
3752 =item num_cust_pay_pending_attempt
3754 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3755 customer, with status "done" but without a corresp. Also called automatically when the
3756 cust_pay_pending method is used in a scalar context.
3760 sub num_cust_pay_pending_attempt {
3763 " SELECT COUNT(*) FROM cust_pay_pending ".
3764 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3771 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3777 map { $_ } #return $self->num_cust_refund unless wantarray;
3778 sort { $a->_date <=> $b->_date }
3779 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3782 =item display_custnum
3784 Returns the displayed customer number for this customer: agent_custid if
3785 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3789 sub display_custnum {
3791 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3792 return $self->agent_custid;
3794 return $self->custnum;
3800 Returns a name string for this customer, either "Company (Last, First)" or
3807 my $name = $self->contact;
3808 $name = $self->company. " ($name)" if $self->company;
3814 Returns a name string for this (service/shipping) contact, either
3815 "Company (Last, First)" or "Last, First".
3821 if ( $self->get('ship_last') ) {
3822 my $name = $self->ship_contact;
3823 $name = $self->ship_company. " ($name)" if $self->ship_company;
3832 Returns a name string for this customer, either "Company" or "First Last".
3838 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3841 =item ship_name_short
3843 Returns a name string for this (service/shipping) contact, either "Company"
3848 sub ship_name_short {
3850 if ( $self->get('ship_last') ) {
3851 $self->ship_company !~ /^\s*$/
3852 ? $self->ship_company
3853 : $self->ship_contact_firstlast;
3855 $self->name_company_or_firstlast;
3861 Returns this customer's full (billing) contact name only, "Last, First"
3867 $self->get('last'). ', '. $self->first;
3872 Returns this customer's full (shipping) contact name only, "Last, First"
3878 $self->get('ship_last')
3879 ? $self->get('ship_last'). ', '. $self->ship_first
3883 =item contact_firstlast
3885 Returns this customers full (billing) contact name only, "First Last".
3889 sub contact_firstlast {
3891 $self->first. ' '. $self->get('last');
3894 =item ship_contact_firstlast
3896 Returns this customer's full (shipping) contact name only, "First Last".
3900 sub ship_contact_firstlast {
3902 $self->get('ship_last')
3903 ? $self->first. ' '. $self->get('ship_last')
3904 : $self->contact_firstlast;
3909 Returns this customer's full country name
3915 code2country($self->country);
3918 =item geocode DATA_VENDOR
3920 Returns a value for the customer location as encoded by DATA_VENDOR.
3921 Currently this only makes sense for "CCH" as DATA_VENDOR.
3929 Returns a status string for this customer, currently:
3933 =item prospect - No packages have ever been ordered
3935 =item ordered - Recurring packages all are new (not yet billed).
3937 =item active - One or more recurring packages is active
3939 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3941 =item suspended - All non-cancelled recurring packages are suspended
3943 =item cancelled - All recurring packages are cancelled
3947 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3948 cust_main-status_module configuration option.
3952 sub status { shift->cust_status(@_); }
3956 for my $status ( FS::cust_main->statuses() ) {
3957 my $method = $status.'_sql';
3958 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3959 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3960 $sth->execute( ($self->custnum) x $numnum )
3961 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3962 return $status if $sth->fetchrow_arrayref->[0];
3966 =item ucfirst_cust_status
3968 =item ucfirst_status
3970 Returns the status with the first character capitalized.
3974 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
3976 sub ucfirst_cust_status {
3978 ucfirst($self->cust_status);
3983 Returns a hex triplet color string for this customer's status.
3987 sub statuscolor { shift->cust_statuscolor(@_); }
3989 sub cust_statuscolor {
3991 __PACKAGE__->statuscolors->{$self->cust_status};
3996 Returns an array of hashes representing the customer's RT tickets.
4003 my $num = $conf->config('cust_main-max_tickets') || 10;
4006 if ( $conf->config('ticket_system') ) {
4007 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4009 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4013 foreach my $priority (
4014 $conf->config('ticket_system-custom_priority_field-values'), ''
4016 last if scalar(@tickets) >= $num;
4018 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4019 $num - scalar(@tickets),
4029 # Return services representing svc_accts in customer support packages
4030 sub support_services {
4032 my %packages = map { $_ => 1 } $conf->config('support_packages');
4034 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4035 grep { $_->part_svc->svcdb eq 'svc_acct' }
4036 map { $_->cust_svc }
4037 grep { exists $packages{ $_->pkgpart } }
4038 $self->ncancelled_pkgs;
4042 # Return a list of latitude/longitude for one of the services (if any)
4043 sub service_coordinates {
4047 grep { $_->latitude && $_->longitude }
4049 map { $_->cust_svc }
4050 $self->ncancelled_pkgs;
4052 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4057 Returns a masked version of the named field
4062 my ($self,$field) = @_;
4066 'x'x(length($self->getfield($field))-4).
4067 substr($self->getfield($field), (length($self->getfield($field))-4));
4073 =head1 CLASS METHODS
4079 Class method that returns the list of possible status strings for customers
4080 (see L<the status method|/status>). For example:
4082 @statuses = FS::cust_main->statuses();
4088 keys %{ $self->statuscolors };
4091 =item cust_status_sql
4093 Returns an SQL fragment to determine the status of a cust_main record, as a
4098 sub cust_status_sql {
4100 for my $status ( FS::cust_main->statuses() ) {
4101 my $method = $status.'_sql';
4102 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4111 Returns an SQL expression identifying prospective cust_main records (customers
4112 with no packages ever ordered)
4116 use vars qw($select_count_pkgs);
4117 $select_count_pkgs =
4118 "SELECT COUNT(*) FROM cust_pkg
4119 WHERE cust_pkg.custnum = cust_main.custnum";
4121 sub select_count_pkgs_sql {
4126 " 0 = ( $select_count_pkgs ) ";
4131 Returns an SQL expression identifying ordered cust_main records (customers with
4132 no active packages, but recurring packages not yet setup or one time charges
4138 FS::cust_main->none_active_sql.
4139 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4144 Returns an SQL expression identifying active cust_main records (customers with
4145 active recurring packages).
4150 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4153 =item none_active_sql
4155 Returns an SQL expression identifying cust_main records with no active
4156 recurring packages. This includes customers of status prospect, ordered,
4157 inactive, and suspended.
4161 sub none_active_sql {
4162 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4167 Returns an SQL expression identifying inactive cust_main records (customers with
4168 no active recurring packages, but otherwise unsuspended/uncancelled).
4173 FS::cust_main->none_active_sql.
4174 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4180 Returns an SQL expression identifying suspended cust_main records.
4185 sub suspended_sql { susp_sql(@_); }
4187 FS::cust_main->none_active_sql.
4188 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4194 Returns an SQL expression identifying cancelled cust_main records.
4198 sub cancel_sql { shift->cancelled_sql(@_); }
4201 =item uncancelled_sql
4203 Returns an SQL expression identifying un-cancelled cust_main records.
4207 sub uncancelled_sql { uncancel_sql(@_); }
4208 sub uncancel_sql { "
4209 ( 0 < ( $select_count_pkgs
4210 AND ( cust_pkg.cancel IS NULL
4211 OR cust_pkg.cancel = 0
4214 OR 0 = ( $select_count_pkgs )
4220 Returns an SQL fragment to retreive the balance.
4225 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4226 WHERE cust_bill.custnum = cust_main.custnum )
4227 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4228 WHERE cust_pay.custnum = cust_main.custnum )
4229 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4230 WHERE cust_credit.custnum = cust_main.custnum )
4231 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4232 WHERE cust_refund.custnum = cust_main.custnum )
4235 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4237 Returns an SQL fragment to retreive the balance for this customer, optionally
4238 considering invoices with date earlier than START_TIME, and not
4239 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4240 total_unapplied_payments).
4242 Times are specified as SQL fragments or numeric
4243 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4244 L<Date::Parse> for conversion functions. The empty string can be passed
4245 to disable that time constraint completely.
4247 Available options are:
4251 =item unapplied_date
4253 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)
4258 set to true to remove all customer comparison clauses, for totals
4263 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4268 JOIN clause (typically used with the total option)
4272 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4273 time will be ignored. Note that START_TIME and END_TIME only limit the date
4274 range for invoices and I<unapplied> payments, credits, and refunds.
4280 sub balance_date_sql {
4281 my( $class, $start, $end, %opt ) = @_;
4283 my $cutoff = $opt{'cutoff'};
4285 my $owed = FS::cust_bill->owed_sql($cutoff);
4286 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4287 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4288 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4290 my $j = $opt{'join'} || '';
4292 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4293 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4294 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4295 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4297 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4298 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4299 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4300 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4305 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4307 Returns an SQL fragment to retreive the total unapplied payments for this
4308 customer, only considering payments with date earlier than START_TIME, and
4309 optionally not later than END_TIME.
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 sub unapplied_payments_date_sql {
4321 my( $class, $start, $end, %opt ) = @_;
4323 my $cutoff = $opt{'cutoff'};
4325 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4327 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4328 'unapplied_date'=>1 );
4330 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4333 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4335 Helper method for balance_date_sql; name (and usage) subject to change
4336 (suggestions welcome).
4338 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4339 cust_refund, cust_credit or cust_pay).
4341 If TABLE is "cust_bill" or the unapplied_date option is true, only
4342 considers records with date earlier than START_TIME, and optionally not
4343 later than END_TIME .
4347 sub _money_table_where {
4348 my( $class, $table, $start, $end, %opt ) = @_;
4351 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4352 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4353 push @where, "$table._date <= $start" if defined($start) && length($start);
4354 push @where, "$table._date > $end" if defined($end) && length($end);
4356 push @where, @{$opt{'where'}} if $opt{'where'};
4357 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4363 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4364 use FS::cust_main::Search;
4367 FS::cust_main::Search->search(@_);
4376 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4380 use FS::cust_main::Search;
4381 sub append_fuzzyfiles {
4382 #my( $first, $last, $company ) = @_;
4384 FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4386 use Fcntl qw(:flock);
4388 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4390 foreach my $field (@fuzzyfields) {
4395 open(CACHE,">>$dir/cust_main.$field")
4396 or die "can't open $dir/cust_main.$field: $!";
4397 flock(CACHE,LOCK_EX)
4398 or die "can't lock $dir/cust_main.$field: $!";
4400 print CACHE "$value\n";
4402 flock(CACHE,LOCK_UN)
4403 or die "can't unlock $dir/cust_main.$field: $!";
4418 #warn join('-',keys %$param);
4419 my $fh = $param->{filehandle};
4420 my $agentnum = $param->{agentnum};
4421 my $format = $param->{format};
4423 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4426 if ( $format eq 'simple' ) {
4427 @fields = qw( custnum agent_custid amount pkg );
4429 die "unknown format $format";
4432 eval "use Text::CSV_XS;";
4435 my $csv = new Text::CSV_XS;
4442 local $SIG{HUP} = 'IGNORE';
4443 local $SIG{INT} = 'IGNORE';
4444 local $SIG{QUIT} = 'IGNORE';
4445 local $SIG{TERM} = 'IGNORE';
4446 local $SIG{TSTP} = 'IGNORE';
4447 local $SIG{PIPE} = 'IGNORE';
4449 my $oldAutoCommit = $FS::UID::AutoCommit;
4450 local $FS::UID::AutoCommit = 0;
4453 #while ( $columns = $csv->getline($fh) ) {
4455 while ( defined($line=<$fh>) ) {
4457 $csv->parse($line) or do {
4458 $dbh->rollback if $oldAutoCommit;
4459 return "can't parse: ". $csv->error_input();
4462 my @columns = $csv->fields();
4463 #warn join('-',@columns);
4466 foreach my $field ( @fields ) {
4467 $row{$field} = shift @columns;
4470 if ( $row{custnum} && $row{agent_custid} ) {
4471 dbh->rollback if $oldAutoCommit;
4472 return "can't specify custnum with agent_custid $row{agent_custid}";
4476 if ( $row{agent_custid} && $agentnum ) {
4477 %hash = ( 'agent_custid' => $row{agent_custid},
4478 'agentnum' => $agentnum,
4482 if ( $row{custnum} ) {
4483 %hash = ( 'custnum' => $row{custnum} );
4486 unless ( scalar(keys %hash) ) {
4487 $dbh->rollback if $oldAutoCommit;
4488 return "can't find customer without custnum or agent_custid and agentnum";
4491 my $cust_main = qsearchs('cust_main', { %hash } );
4492 unless ( $cust_main ) {
4493 $dbh->rollback if $oldAutoCommit;
4494 my $custnum = $row{custnum} || $row{agent_custid};
4495 return "unknown custnum $custnum";
4498 if ( $row{'amount'} > 0 ) {
4499 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4501 $dbh->rollback if $oldAutoCommit;
4505 } elsif ( $row{'amount'} < 0 ) {
4506 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4509 $dbh->rollback if $oldAutoCommit;
4519 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4521 return "Empty file!" unless $imported;
4527 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4529 Deprecated. Use event notification and message templates
4530 (L<FS::msg_template>) instead.
4532 Sends a templated email notification to the customer (see L<Text::Template>).
4534 OPTIONS is a hash and may include
4536 I<from> - the email sender (default is invoice_from)
4538 I<to> - comma-separated scalar or arrayref of recipients
4539 (default is invoicing_list)
4541 I<subject> - The subject line of the sent email notification
4542 (default is "Notice from company_name")
4544 I<extra_fields> - a hashref of name/value pairs which will be substituted
4547 The following variables are vavailable in the template.
4549 I<$first> - the customer first name
4550 I<$last> - the customer last name
4551 I<$company> - the customer company
4552 I<$payby> - a description of the method of payment for the customer
4553 # would be nice to use FS::payby::shortname
4554 I<$payinfo> - the account information used to collect for this customer
4555 I<$expdate> - the expiration of the customer payment in seconds from epoch
4560 my ($self, $template, %options) = @_;
4562 return unless $conf->exists($template);
4564 my $from = $conf->config('invoice_from', $self->agentnum)
4565 if $conf->exists('invoice_from', $self->agentnum);
4566 $from = $options{from} if exists($options{from});
4568 my $to = join(',', $self->invoicing_list_emailonly);
4569 $to = $options{to} if exists($options{to});
4571 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4572 if $conf->exists('company_name', $self->agentnum);
4573 $subject = $options{subject} if exists($options{subject});
4575 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4576 SOURCE => [ map "$_\n",
4577 $conf->config($template)]
4579 or die "can't create new Text::Template object: Text::Template::ERROR";
4580 $notify_template->compile()
4581 or die "can't compile template: Text::Template::ERROR";
4583 $FS::notify_template::_template::company_name =
4584 $conf->config('company_name', $self->agentnum);
4585 $FS::notify_template::_template::company_address =
4586 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4588 my $paydate = $self->paydate || '2037-12-31';
4589 $FS::notify_template::_template::first = $self->first;
4590 $FS::notify_template::_template::last = $self->last;
4591 $FS::notify_template::_template::company = $self->company;
4592 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4593 my $payby = $self->payby;
4594 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4595 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4597 #credit cards expire at the end of the month/year of their exp date
4598 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4599 $FS::notify_template::_template::payby = 'credit card';
4600 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4601 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4603 }elsif ($payby eq 'COMP') {
4604 $FS::notify_template::_template::payby = 'complimentary account';
4606 $FS::notify_template::_template::payby = 'current method';
4608 $FS::notify_template::_template::expdate = $expire_time;
4610 for (keys %{$options{extra_fields}}){
4612 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4615 send_email(from => $from,
4617 subject => $subject,
4618 body => $notify_template->fill_in( PACKAGE =>
4619 'FS::notify_template::_template' ),
4624 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4626 Generates a templated notification to the customer (see L<Text::Template>).
4628 OPTIONS is a hash and may include
4630 I<extra_fields> - a hashref of name/value pairs which will be substituted
4631 into the template. These values may override values mentioned below
4632 and those from the customer record.
4634 The following variables are available in the template instead of or in addition
4635 to the fields of the customer record.
4637 I<$payby> - a description of the method of payment for the customer
4638 # would be nice to use FS::payby::shortname
4639 I<$payinfo> - the masked account information used to collect for this customer
4640 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4641 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4645 # a lot like cust_bill::print_latex
4646 sub generate_letter {
4647 my ($self, $template, %options) = @_;
4649 return unless $conf->exists($template);
4651 my $letter_template = new Text::Template
4653 SOURCE => [ map "$_\n", $conf->config($template)],
4654 DELIMITERS => [ '[@--', '--@]' ],
4656 or die "can't create new Text::Template object: Text::Template::ERROR";
4658 $letter_template->compile()
4659 or die "can't compile template: Text::Template::ERROR";
4661 my %letter_data = map { $_ => $self->$_ } $self->fields;
4662 $letter_data{payinfo} = $self->mask_payinfo;
4664 #my $paydate = $self->paydate || '2037-12-31';
4665 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4667 my $payby = $self->payby;
4668 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4669 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4671 #credit cards expire at the end of the month/year of their exp date
4672 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4673 $letter_data{payby} = 'credit card';
4674 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4675 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4677 }elsif ($payby eq 'COMP') {
4678 $letter_data{payby} = 'complimentary account';
4680 $letter_data{payby} = 'current method';
4682 $letter_data{expdate} = $expire_time;
4684 for (keys %{$options{extra_fields}}){
4685 $letter_data{$_} = $options{extra_fields}->{$_};
4688 unless(exists($letter_data{returnaddress})){
4689 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4690 $self->agent_template)
4692 if ( length($retadd) ) {
4693 $letter_data{returnaddress} = $retadd;
4694 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4695 $letter_data{returnaddress} =
4696 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4700 ( $conf->config('company_name', $self->agentnum),
4701 $conf->config('company_address', $self->agentnum),
4705 $letter_data{returnaddress} = '~';
4709 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4711 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4713 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4715 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4719 ) or die "can't open temp file: $!\n";
4720 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4721 or die "can't write temp file: $!\n";
4723 $letter_data{'logo_file'} = $lh->filename;
4725 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4729 ) or die "can't open temp file: $!\n";
4731 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4733 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4734 return ($1, $letter_data{'logo_file'});
4738 =item print_ps TEMPLATE
4740 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4746 my($file, $lfile) = $self->generate_letter(@_);
4747 my $ps = FS::Misc::generate_ps($file);
4748 unlink($file.'.tex');
4754 =item print TEMPLATE
4756 Prints the filled in template.
4758 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4762 sub queueable_print {
4765 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4766 or die "invalid customer number: " . $opt{custvnum};
4768 my $error = $self->print( $opt{template} );
4769 die $error if $error;
4773 my ($self, $template) = (shift, shift);
4774 do_print [ $self->print_ps($template) ];
4777 #these three subs should just go away once agent stuff is all config overrides
4779 sub agent_template {
4781 $self->_agent_plandata('agent_templatename');
4784 sub agent_invoice_from {
4786 $self->_agent_plandata('agent_invoice_from');
4789 sub _agent_plandata {
4790 my( $self, $option ) = @_;
4792 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4793 #agent-specific Conf
4795 use FS::part_event::Condition;
4797 my $agentnum = $self->agentnum;
4799 my $regexp = regexp_sql();
4801 my $part_event_option =
4803 'select' => 'part_event_option.*',
4804 'table' => 'part_event_option',
4806 LEFT JOIN part_event USING ( eventpart )
4807 LEFT JOIN part_event_option AS peo_agentnum
4808 ON ( part_event.eventpart = peo_agentnum.eventpart
4809 AND peo_agentnum.optionname = 'agentnum'
4810 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4812 LEFT JOIN part_event_condition
4813 ON ( part_event.eventpart = part_event_condition.eventpart
4814 AND part_event_condition.conditionname = 'cust_bill_age'
4816 LEFT JOIN part_event_condition_option
4817 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4818 AND part_event_condition_option.optionname = 'age'
4821 #'hashref' => { 'optionname' => $option },
4822 #'hashref' => { 'part_event_option.optionname' => $option },
4824 " WHERE part_event_option.optionname = ". dbh->quote($option).
4825 " AND action = 'cust_bill_send_agent' ".
4826 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4827 " AND peo_agentnum.optionname = 'agentnum' ".
4828 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4830 CASE WHEN part_event_condition_option.optionname IS NULL
4832 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4834 , part_event.weight".
4838 unless ( $part_event_option ) {
4839 return $self->agent->invoice_template || ''
4840 if $option eq 'agent_templatename';
4844 $part_event_option->optionvalue;
4848 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4850 Subroutine (not a method), designed to be called from the queue.
4852 Takes a list of options and values.
4854 Pulls up the customer record via the custnum option and calls bill_and_collect.
4859 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4861 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4862 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4864 $cust_main->bill_and_collect( %args );
4867 sub process_bill_and_collect {
4869 my $param = thaw(decode_base64(shift));
4870 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4871 or die "custnum '$param->{custnum}' not found!\n";
4872 $param->{'job'} = $job;
4873 $param->{'fatal'} = 1; # runs from job queue, will be caught
4874 $param->{'retry'} = 1;
4876 $cust_main->bill_and_collect( %$param );
4879 sub _upgrade_data { #class method
4880 my ($class, %opts) = @_;
4883 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4884 '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',
4886 # fix yyyy-m-dd formatted paydates
4887 if ( driver_name =~ /^mysql$/i ) {
4889 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4891 else { # the SQL standard
4893 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4896 foreach my $sql ( @statements ) {
4897 my $sth = dbh->prepare($sql) or die dbh->errstr;
4898 $sth->execute or die $sth->errstr;
4901 local($ignore_expired_card) = 1;
4902 local($ignore_illegal_zip) = 1;
4903 local($ignore_banned_card) = 1;
4904 local($skip_fuzzyfiles) = 1;
4905 $class->_upgrade_otaker(%opts);
4915 The delete method should possibly take an FS::cust_main object reference
4916 instead of a scalar customer number.
4918 Bill and collect options should probably be passed as references instead of a
4921 There should probably be a configuration file with a list of allowed credit
4924 No multiple currency support (probably a larger project than just this module).
4926 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4928 Birthdates rely on negative epoch values.
4930 The payby for card/check batches is broken. With mixed batching, bad
4933 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4937 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4938 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4939 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.