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);
43 use FS::legacy_cust_bill;
45 use FS::cust_pay_pending;
46 use FS::cust_pay_void;
47 use FS::cust_pay_batch;
50 use FS::part_referral;
51 use FS::cust_main_county;
52 use FS::cust_location;
54 use FS::cust_main_exemption;
55 use FS::cust_tax_adjustment;
56 use FS::cust_tax_location;
58 use FS::cust_main_invoice;
60 use FS::prepay_credit;
66 use FS::payment_gateway;
67 use FS::agent_payment_gateway;
69 use FS::cust_main_note;
70 use FS::cust_attachment;
74 # 1 is mostly method/subroutine entry and options
75 # 2 traces progress of some operations
76 # 3 is even more information including possibly sensitive data
78 $me = '[FS::cust_main]';
81 $ignore_expired_card = 0;
82 $ignore_illegal_zip = 0;
83 $ignore_banned_card = 0;
86 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
88 @encrypted_fields = ('payinfo', 'paycvv');
89 sub nohistory_fields { ('payinfo', 'paycvv'); }
91 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
93 #ask FS::UID to run this stuff for us later
94 #$FS::UID::callback{'FS::cust_main'} = sub {
95 install_callback FS::UID sub {
97 #yes, need it for stuff below (prolly should be cached)
102 my ( $hashref, $cache ) = @_;
103 if ( exists $hashref->{'pkgnum'} ) {
104 #@{ $self->{'_pkgnum'} } = ();
105 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
106 $self->{'_pkgnum'} = $subcache;
107 #push @{ $self->{'_pkgnum'} },
108 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
114 FS::cust_main - Object methods for cust_main records
120 $record = new FS::cust_main \%hash;
121 $record = new FS::cust_main { 'column' => 'value' };
123 $error = $record->insert;
125 $error = $new_record->replace($old_record);
127 $error = $record->delete;
129 $error = $record->check;
131 @cust_pkg = $record->all_pkgs;
133 @cust_pkg = $record->ncancelled_pkgs;
135 @cust_pkg = $record->suspended_pkgs;
137 $error = $record->bill;
138 $error = $record->bill %options;
139 $error = $record->bill 'time' => $time;
141 $error = $record->collect;
142 $error = $record->collect %options;
143 $error = $record->collect 'invoice_time' => $time,
148 An FS::cust_main object represents a customer. FS::cust_main inherits from
149 FS::Record. The following fields are currently supported:
155 Primary key (assigned automatically for new customers)
159 Agent (see L<FS::agent>)
163 Advertising source (see L<FS::part_referral>)
175 Cocial security number (optional)
191 (optional, see L<FS::cust_main_county>)
195 (see L<FS::cust_main_county>)
201 (see L<FS::cust_main_county>)
241 (optional, see L<FS::cust_main_county>)
245 (see L<FS::cust_main_county>)
251 (see L<FS::cust_main_county>)
271 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
275 Payment Information (See L<FS::payinfo_Mixin> for data format)
279 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
283 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
287 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
291 Start date month (maestro/solo cards only)
295 Start date year (maestro/solo cards only)
299 Issue number (maestro/solo cards only)
303 Name on card or billing name
307 IP address from which payment information was received
311 Tax exempt, empty or `Y'
315 Order taker (see L<FS::access_user>)
321 =item referral_custnum
323 Referring customer number
327 Enable individual CDR spooling, empty or `Y'
331 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
335 Discourage individual CDR printing, empty or `Y'
339 Allow self-service editing of ticket subjects, empty or 'Y'
341 =item calling_list_exempt
343 Do not call, empty or 'Y'
353 Creates a new customer. To add the customer to the database, see L<"insert">.
355 Note that this stores the hash reference, not a distinct copy of the hash it
356 points to. You can ask the object for a copy with the I<hash> method.
360 sub table { 'cust_main'; }
362 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
364 Adds this customer to the database. If there is an error, returns the error,
365 otherwise returns false.
367 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
368 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
369 are inserted atomicly, or the transaction is rolled back. Passing an empty
370 hash reference is equivalent to not supplying this parameter. There should be
371 a better explanation of this, but until then, here's an example:
374 tie %hash, 'Tie::RefHash'; #this part is important
376 $cust_pkg => [ $svc_acct ],
379 $cust_main->insert( \%hash );
381 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
382 be set as the invoicing list (see L<"invoicing_list">). Errors return as
383 expected and rollback the entire transaction; it is not necessary to call
384 check_invoicing_list first. The invoicing_list is set after the records in the
385 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
386 invoicing_list destination to the newly-created svc_acct. Here's an example:
388 $cust_main->insert( {}, [ $email, 'POST' ] );
390 Currently available options are: I<depend_jobnum>, I<noexport>,
391 I<tax_exemption> and I<prospectnum>.
393 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
394 on the supplied jobnum (they will not run until the specific job completes).
395 This can be used to defer provisioning until some action completes (such
396 as running the customer's credit card successfully).
398 The I<noexport> option is deprecated. If I<noexport> is set true, no
399 provisioning jobs (exports) are scheduled. (You can schedule them later with
400 the B<reexport> method.)
402 The I<tax_exemption> option can be set to an arrayref of tax names.
403 FS::cust_main_exemption records will be created and inserted.
405 If I<prospectnum> is set, moves contacts and locations from that prospect.
411 my $cust_pkgs = @_ ? shift : {};
412 my $invoicing_list = @_ ? shift : '';
414 warn "$me insert called with options ".
415 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
418 local $SIG{HUP} = 'IGNORE';
419 local $SIG{INT} = 'IGNORE';
420 local $SIG{QUIT} = 'IGNORE';
421 local $SIG{TERM} = 'IGNORE';
422 local $SIG{TSTP} = 'IGNORE';
423 local $SIG{PIPE} = 'IGNORE';
425 my $oldAutoCommit = $FS::UID::AutoCommit;
426 local $FS::UID::AutoCommit = 0;
429 my $prepay_identifier = '';
430 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
432 if ( $self->payby eq 'PREPAY' ) {
434 $self->payby('BILL');
435 $prepay_identifier = $self->payinfo;
438 warn " looking up prepaid card $prepay_identifier\n"
441 my $error = $self->get_prepay( $prepay_identifier,
442 'amount_ref' => \$amount,
443 'seconds_ref' => \$seconds,
444 'upbytes_ref' => \$upbytes,
445 'downbytes_ref' => \$downbytes,
446 'totalbytes_ref' => \$totalbytes,
449 $dbh->rollback if $oldAutoCommit;
450 #return "error applying prepaid card (transaction rolled back): $error";
454 $payby = 'PREP' if $amount;
456 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
459 $self->payby('BILL');
460 $amount = $self->paid;
464 warn " inserting $self\n"
467 $self->signupdate(time) unless $self->signupdate;
469 $self->auto_agent_custid()
470 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
472 my $error = $self->SUPER::insert;
474 $dbh->rollback if $oldAutoCommit;
475 #return "inserting cust_main record (transaction rolled back): $error";
479 warn " setting invoicing list\n"
482 if ( $invoicing_list ) {
483 $error = $self->check_invoicing_list( $invoicing_list );
485 $dbh->rollback if $oldAutoCommit;
486 #return "checking invoicing_list (transaction rolled back): $error";
489 $self->invoicing_list( $invoicing_list );
492 warn " setting customer tags\n"
495 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
496 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
497 'custnum' => $self->custnum };
498 my $error = $cust_tag->insert;
500 $dbh->rollback if $oldAutoCommit;
505 my $prospectnum = delete $options{'prospectnum'};
506 if ( $prospectnum ) {
508 warn " moving contacts and locations from prospect $prospectnum\n"
512 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
513 unless ( $prospect_main ) {
514 $dbh->rollback if $oldAutoCommit;
515 return "Unknown prospectnum $prospectnum";
517 $prospect_main->custnum($self->custnum);
518 $prospect_main->disabled('Y');
519 my $error = $prospect_main->replace;
521 $dbh->rollback if $oldAutoCommit;
525 my @contact = $prospect_main->contact;
526 my @cust_location = $prospect_main->cust_location;
527 my @qual = $prospect_main->qual;
529 foreach my $r ( @contact, @cust_location, @qual ) {
531 $r->custnum($self->custnum);
532 my $error = $r->replace;
534 $dbh->rollback if $oldAutoCommit;
541 warn " setting cust_main_exemption\n"
544 my $tax_exemption = delete $options{'tax_exemption'};
545 if ( $tax_exemption ) {
546 foreach my $taxname ( @$tax_exemption ) {
547 my $cust_main_exemption = new FS::cust_main_exemption {
548 'custnum' => $self->custnum,
549 'taxname' => $taxname,
551 my $error = $cust_main_exemption->insert;
553 $dbh->rollback if $oldAutoCommit;
554 return "inserting cust_main_exemption (transaction rolled back): $error";
559 if ( $self->can('start_copy_skel') ) {
560 my $error = $self->start_copy_skel;
562 $dbh->rollback if $oldAutoCommit;
567 warn " ordering packages\n"
570 $error = $self->order_pkgs( $cust_pkgs,
572 'seconds_ref' => \$seconds,
573 'upbytes_ref' => \$upbytes,
574 'downbytes_ref' => \$downbytes,
575 'totalbytes_ref' => \$totalbytes,
578 $dbh->rollback if $oldAutoCommit;
583 $dbh->rollback if $oldAutoCommit;
584 return "No svc_acct record to apply pre-paid time";
586 if ( $upbytes || $downbytes || $totalbytes ) {
587 $dbh->rollback if $oldAutoCommit;
588 return "No svc_acct record to apply pre-paid data";
592 warn " inserting initial $payby payment of $amount\n"
594 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
596 $dbh->rollback if $oldAutoCommit;
597 return "inserting payment (transaction rolled back): $error";
601 unless ( $import || $skip_fuzzyfiles ) {
602 warn " queueing fuzzyfiles update\n"
604 $error = $self->queue_fuzzyfiles_update;
606 $dbh->rollback if $oldAutoCommit;
607 return "updating fuzzy search cache: $error";
612 warn " exporting\n" if $DEBUG > 1;
614 my $export_args = $options{'export_args'} || [];
617 map qsearch( 'part_export', {exportnum=>$_} ),
618 $conf->config('cust_main-exports'); #, $agentnum
620 foreach my $part_export ( @part_export ) {
621 my $error = $part_export->export_insert($self, @$export_args);
623 $dbh->rollback if $oldAutoCommit;
624 return "exporting to ". $part_export->exporttype.
625 " (transaction rolled back): $error";
629 #foreach my $depend_jobnum ( @$depend_jobnums ) {
630 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
632 # foreach my $jobnum ( @jobnums ) {
633 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
634 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
636 # my $error = $queue->depend_insert($depend_jobnum);
638 # $dbh->rollback if $oldAutoCommit;
639 # return "error queuing job dependancy: $error";
646 #if ( exists $options{'jobnums'} ) {
647 # push @{ $options{'jobnums'} }, @jobnums;
650 warn " insert complete; committing transaction\n"
653 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
658 use File::CounterFile;
659 sub auto_agent_custid {
662 my $format = $conf->config('cust_main-auto_agent_custid');
664 if ( $format eq '1YMMXXXXXXXX' ) {
666 my $counter = new File::CounterFile 'cust_main.agent_custid';
669 my $ym = 100000000000 + time2str('%y%m00000000', time);
670 if ( $ym > $counter->value ) {
671 $counter->{'value'} = $agent_custid = $ym;
672 $counter->{'updated'} = 1;
674 $agent_custid = $counter->inc;
679 } elsif ( $format eq '1001XXXXXXXX' ) {
681 my $counter = new File::CounterFile 'cust_main.agent_custid';
684 $agent_custid = '1001'. $counter->inc;
689 die "Unknown cust_main-auto_agent_custid format: $format";
692 $self->agent_custid($agent_custid);
696 =item PACKAGE METHODS
698 Documentation on customer package methods has been moved to
699 L<FS::cust_main::Packages>.
701 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
703 Recharges this (existing) customer with the specified prepaid card (see
704 L<FS::prepay_credit>), specified either by I<identifier> or as an
705 FS::prepay_credit object. If there is an error, returns the error, otherwise
708 Optionally, five scalar references can be passed as well. They will have their
709 values filled in with the amount, number of seconds, and number of upload,
710 download, and total bytes applied by this prepaid card.
714 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
715 #the only place that uses these args
716 sub recharge_prepay {
717 my( $self, $prepay_credit, $amountref, $secondsref,
718 $upbytesref, $downbytesref, $totalbytesref ) = @_;
720 local $SIG{HUP} = 'IGNORE';
721 local $SIG{INT} = 'IGNORE';
722 local $SIG{QUIT} = 'IGNORE';
723 local $SIG{TERM} = 'IGNORE';
724 local $SIG{TSTP} = 'IGNORE';
725 local $SIG{PIPE} = 'IGNORE';
727 my $oldAutoCommit = $FS::UID::AutoCommit;
728 local $FS::UID::AutoCommit = 0;
731 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
733 my $error = $self->get_prepay( $prepay_credit,
734 'amount_ref' => \$amount,
735 'seconds_ref' => \$seconds,
736 'upbytes_ref' => \$upbytes,
737 'downbytes_ref' => \$downbytes,
738 'totalbytes_ref' => \$totalbytes,
740 || $self->increment_seconds($seconds)
741 || $self->increment_upbytes($upbytes)
742 || $self->increment_downbytes($downbytes)
743 || $self->increment_totalbytes($totalbytes)
744 || $self->insert_cust_pay_prepay( $amount,
746 ? $prepay_credit->identifier
751 $dbh->rollback if $oldAutoCommit;
755 if ( defined($amountref) ) { $$amountref = $amount; }
756 if ( defined($secondsref) ) { $$secondsref = $seconds; }
757 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
758 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
759 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
761 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
766 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
768 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
769 specified either by I<identifier> or as an FS::prepay_credit object.
771 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
772 incremented by the values of the prepaid card.
774 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
775 check or set this customer's I<agentnum>.
777 If there is an error, returns the error, otherwise returns false.
783 my( $self, $prepay_credit, %opt ) = @_;
785 local $SIG{HUP} = 'IGNORE';
786 local $SIG{INT} = 'IGNORE';
787 local $SIG{QUIT} = 'IGNORE';
788 local $SIG{TERM} = 'IGNORE';
789 local $SIG{TSTP} = 'IGNORE';
790 local $SIG{PIPE} = 'IGNORE';
792 my $oldAutoCommit = $FS::UID::AutoCommit;
793 local $FS::UID::AutoCommit = 0;
796 unless ( ref($prepay_credit) ) {
798 my $identifier = $prepay_credit;
800 $prepay_credit = qsearchs(
802 { 'identifier' => $identifier },
807 unless ( $prepay_credit ) {
808 $dbh->rollback if $oldAutoCommit;
809 return "Invalid prepaid card: ". $identifier;
814 if ( $prepay_credit->agentnum ) {
815 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
816 $dbh->rollback if $oldAutoCommit;
817 return "prepaid card not valid for agent ". $self->agentnum;
819 $self->agentnum($prepay_credit->agentnum);
822 my $error = $prepay_credit->delete;
824 $dbh->rollback if $oldAutoCommit;
825 return "removing prepay_credit (transaction rolled back): $error";
828 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
829 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
831 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
836 =item increment_upbytes SECONDS
838 Updates this customer's single or primary account (see L<FS::svc_acct>) by
839 the specified number of upbytes. If there is an error, returns the error,
840 otherwise returns false.
844 sub increment_upbytes {
845 _increment_column( shift, 'upbytes', @_);
848 =item increment_downbytes SECONDS
850 Updates this customer's single or primary account (see L<FS::svc_acct>) by
851 the specified number of downbytes. If there is an error, returns the error,
852 otherwise returns false.
856 sub increment_downbytes {
857 _increment_column( shift, 'downbytes', @_);
860 =item increment_totalbytes SECONDS
862 Updates this customer's single or primary account (see L<FS::svc_acct>) by
863 the specified number of totalbytes. If there is an error, returns the error,
864 otherwise returns false.
868 sub increment_totalbytes {
869 _increment_column( shift, 'totalbytes', @_);
872 =item increment_seconds SECONDS
874 Updates this customer's single or primary account (see L<FS::svc_acct>) by
875 the specified number of seconds. If there is an error, returns the error,
876 otherwise returns false.
880 sub increment_seconds {
881 _increment_column( shift, 'seconds', @_);
884 =item _increment_column AMOUNT
886 Updates this customer's single or primary account (see L<FS::svc_acct>) by
887 the specified number of seconds or bytes. If there is an error, returns
888 the error, otherwise returns false.
892 sub _increment_column {
893 my( $self, $column, $amount ) = @_;
894 warn "$me increment_column called: $column, $amount\n"
897 return '' unless $amount;
899 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
900 $self->ncancelled_pkgs;
903 return 'No packages with primary or single services found'.
904 ' to apply pre-paid time';
905 } elsif ( scalar(@cust_pkg) > 1 ) {
906 #maybe have a way to specify the package/account?
907 return 'Multiple packages found to apply pre-paid time';
910 my $cust_pkg = $cust_pkg[0];
911 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
915 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
918 return 'No account found to apply pre-paid time';
919 } elsif ( scalar(@cust_svc) > 1 ) {
920 return 'Multiple accounts found to apply pre-paid time';
923 my $svc_acct = $cust_svc[0]->svc_x;
924 warn " found service svcnum ". $svc_acct->pkgnum.
925 ' ('. $svc_acct->email. ")\n"
928 $column = "increment_$column";
929 $svc_acct->$column($amount);
933 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
935 Inserts a prepayment in the specified amount for this customer. An optional
936 second argument can specify the prepayment identifier for tracking purposes.
937 If there is an error, returns the error, otherwise returns false.
941 sub insert_cust_pay_prepay {
942 shift->insert_cust_pay('PREP', @_);
945 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
947 Inserts a cash payment in the specified amount for this customer. An optional
948 second argument can specify the payment identifier for tracking purposes.
949 If there is an error, returns the error, otherwise returns false.
953 sub insert_cust_pay_cash {
954 shift->insert_cust_pay('CASH', @_);
957 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
959 Inserts a Western Union payment in the specified amount for this customer. An
960 optional second argument can specify the prepayment identifier for tracking
961 purposes. If there is an error, returns the error, otherwise returns false.
965 sub insert_cust_pay_west {
966 shift->insert_cust_pay('WEST', @_);
969 sub insert_cust_pay {
970 my( $self, $payby, $amount ) = splice(@_, 0, 3);
971 my $payinfo = scalar(@_) ? shift : '';
973 my $cust_pay = new FS::cust_pay {
974 'custnum' => $self->custnum,
975 'paid' => sprintf('%.2f', $amount),
976 #'_date' => #date the prepaid card was purchased???
978 'payinfo' => $payinfo,
986 This method is deprecated. See the I<depend_jobnum> option to the insert and
987 order_pkgs methods for a better way to defer provisioning.
989 Re-schedules all exports by calling the B<reexport> method of all associated
990 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
991 otherwise returns false.
998 carp "WARNING: FS::cust_main::reexport is deprectated; ".
999 "use the depend_jobnum option to insert or order_pkgs to delay export";
1001 local $SIG{HUP} = 'IGNORE';
1002 local $SIG{INT} = 'IGNORE';
1003 local $SIG{QUIT} = 'IGNORE';
1004 local $SIG{TERM} = 'IGNORE';
1005 local $SIG{TSTP} = 'IGNORE';
1006 local $SIG{PIPE} = 'IGNORE';
1008 my $oldAutoCommit = $FS::UID::AutoCommit;
1009 local $FS::UID::AutoCommit = 0;
1012 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1013 my $error = $cust_pkg->reexport;
1015 $dbh->rollback if $oldAutoCommit;
1020 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1025 =item delete [ OPTION => VALUE ... ]
1027 This deletes the customer. If there is an error, returns the error, otherwise
1030 This will completely remove all traces of the customer record. This is not
1031 what you want when a customer cancels service; for that, cancel all of the
1032 customer's packages (see L</cancel>).
1034 If the customer has any uncancelled packages, you need to pass a new (valid)
1035 customer number for those packages to be transferred to, as the "new_customer"
1036 option. Cancelled packages will be deleted. Did I mention that this is NOT
1037 what you want when a customer cancels service and that you really should be
1038 looking at L<FS::cust_pkg/cancel>?
1040 You can't delete a customer with invoices (see L<FS::cust_bill>),
1041 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1042 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1043 set the "delete_financials" option to a true value.
1048 my( $self, %opt ) = @_;
1050 local $SIG{HUP} = 'IGNORE';
1051 local $SIG{INT} = 'IGNORE';
1052 local $SIG{QUIT} = 'IGNORE';
1053 local $SIG{TERM} = 'IGNORE';
1054 local $SIG{TSTP} = 'IGNORE';
1055 local $SIG{PIPE} = 'IGNORE';
1057 my $oldAutoCommit = $FS::UID::AutoCommit;
1058 local $FS::UID::AutoCommit = 0;
1061 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1062 $dbh->rollback if $oldAutoCommit;
1063 return "Can't delete a master agent customer";
1066 #use FS::access_user
1067 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1068 $dbh->rollback if $oldAutoCommit;
1069 return "Can't delete a master employee customer";
1072 tie my %financial_tables, 'Tie::IxHash',
1073 'cust_bill' => 'invoices',
1074 'cust_statement' => 'statements',
1075 'cust_credit' => 'credits',
1076 'cust_pay' => 'payments',
1077 'cust_refund' => 'refunds',
1080 foreach my $table ( keys %financial_tables ) {
1082 my @records = $self->$table();
1084 if ( @records && ! $opt{'delete_financials'} ) {
1085 $dbh->rollback if $oldAutoCommit;
1086 return "Can't delete a customer with ". $financial_tables{$table};
1089 foreach my $record ( @records ) {
1090 my $error = $record->delete;
1092 $dbh->rollback if $oldAutoCommit;
1093 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1099 my @cust_pkg = $self->ncancelled_pkgs;
1101 my $new_custnum = $opt{'new_custnum'};
1102 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1103 $dbh->rollback if $oldAutoCommit;
1104 return "Invalid new customer number: $new_custnum";
1106 foreach my $cust_pkg ( @cust_pkg ) {
1107 my %hash = $cust_pkg->hash;
1108 $hash{'custnum'} = $new_custnum;
1109 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1110 my $error = $new_cust_pkg->replace($cust_pkg,
1111 options => { $cust_pkg->options },
1114 $dbh->rollback if $oldAutoCommit;
1119 my @cancelled_cust_pkg = $self->all_pkgs;
1120 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1121 my $error = $cust_pkg->delete;
1123 $dbh->rollback if $oldAutoCommit;
1128 #cust_tax_adjustment in financials?
1129 #cust_pay_pending? ouch
1131 foreach my $table (qw(
1132 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1133 cust_location cust_main_note cust_tax_adjustment
1134 cust_pay_void cust_pay_batch queue cust_tax_exempt
1136 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1137 my $error = $record->delete;
1139 $dbh->rollback if $oldAutoCommit;
1145 my $sth = $dbh->prepare(
1146 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1148 my $errstr = $dbh->errstr;
1149 $dbh->rollback if $oldAutoCommit;
1152 $sth->execute($self->custnum) or do {
1153 my $errstr = $sth->errstr;
1154 $dbh->rollback if $oldAutoCommit;
1160 my $ticket_dbh = '';
1161 if ($conf->config('ticket_system') eq 'RT_Internal') {
1163 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1164 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1165 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1166 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1169 if ( $ticket_dbh ) {
1171 my $ticket_sth = $ticket_dbh->prepare(
1172 'DELETE FROM Links WHERE Target = ?'
1174 my $errstr = $ticket_dbh->errstr;
1175 $dbh->rollback if $oldAutoCommit;
1178 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1180 my $errstr = $ticket_sth->errstr;
1181 $dbh->rollback if $oldAutoCommit;
1185 #check and see if the customer is the only link on the ticket, and
1186 #if so, set the ticket to deleted status in RT?
1187 #maybe someday, for now this will at least fix tickets not displaying
1191 #delete the customer record
1193 my $error = $self->SUPER::delete;
1195 $dbh->rollback if $oldAutoCommit;
1199 # cust_main exports!
1201 #my $export_args = $options{'export_args'} || [];
1204 map qsearch( 'part_export', {exportnum=>$_} ),
1205 $conf->config('cust_main-exports'); #, $agentnum
1207 foreach my $part_export ( @part_export ) {
1208 my $error = $part_export->export_delete( $self ); #, @$export_args);
1210 $dbh->rollback if $oldAutoCommit;
1211 return "exporting to ". $part_export->exporttype.
1212 " (transaction rolled back): $error";
1216 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1221 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1223 This merges this customer into the provided new custnum, and then deletes the
1224 customer. If there is an error, returns the error, otherwise returns false.
1226 The source customer's name, company name, phone numbers, agent,
1227 referring customer, customer class, advertising source, order taker, and
1228 billing information (except balance) are discarded.
1230 All packages are moved to the target customer. Packages with package locations
1231 are preserved. Packages without package locations are moved to a new package
1232 location with the source customer's service/shipping address.
1234 All invoices, statements, payments, credits and refunds are moved to the target
1235 customer. The source customer's balance is added to the target customer.
1237 All notes, attachments, tickets and customer tags are moved to the target
1240 Change history is not currently moved.
1245 my( $self, $new_custnum, %opt ) = @_;
1247 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1249 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1250 return "Invalid new customer number: $new_custnum";
1253 local $SIG{HUP} = 'IGNORE';
1254 local $SIG{INT} = 'IGNORE';
1255 local $SIG{QUIT} = 'IGNORE';
1256 local $SIG{TERM} = 'IGNORE';
1257 local $SIG{TSTP} = 'IGNORE';
1258 local $SIG{PIPE} = 'IGNORE';
1260 my $oldAutoCommit = $FS::UID::AutoCommit;
1261 local $FS::UID::AutoCommit = 0;
1264 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1265 $dbh->rollback if $oldAutoCommit;
1266 return "Can't merge a master agent customer";
1269 #use FS::access_user
1270 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1271 $dbh->rollback if $oldAutoCommit;
1272 return "Can't merge a master employee customer";
1275 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1276 'status' => { op=>'!=', value=>'done' },
1280 $dbh->rollback if $oldAutoCommit;
1281 return "Can't merge a customer with pending payments";
1284 tie my %financial_tables, 'Tie::IxHash',
1285 'cust_bill' => 'invoices',
1286 'cust_statement' => 'statements',
1287 'cust_credit' => 'credits',
1288 'cust_pay' => 'payments',
1289 'cust_pay_void' => 'voided payments',
1290 'cust_refund' => 'refunds',
1293 foreach my $table ( keys %financial_tables ) {
1295 my @records = $self->$table();
1297 foreach my $record ( @records ) {
1298 $record->custnum($new_custnum);
1299 my $error = $record->replace;
1301 $dbh->rollback if $oldAutoCommit;
1302 return "Error merging ". $financial_tables{$table}. ": $error\n";
1308 my $name = $self->ship_name;
1310 my $locationnum = '';
1311 foreach my $cust_pkg ( $self->all_pkgs ) {
1312 $cust_pkg->custnum($new_custnum);
1314 unless ( $cust_pkg->locationnum ) {
1315 unless ( $locationnum ) {
1316 my $cust_location = new FS::cust_location {
1317 $self->location_hash,
1318 'custnum' => $new_custnum,
1320 my $error = $cust_location->insert;
1322 $dbh->rollback if $oldAutoCommit;
1325 $locationnum = $cust_location->locationnum;
1327 $cust_pkg->locationnum($locationnum);
1330 my $error = $cust_pkg->replace;
1332 $dbh->rollback if $oldAutoCommit;
1336 # add customer (ship) name to svc_phone.phone_name if blank
1337 my @cust_svc = $cust_pkg->cust_svc;
1338 foreach my $cust_svc (@cust_svc) {
1339 my($label, $value, $svcdb) = $cust_svc->label;
1340 next unless $svcdb eq 'svc_phone';
1341 my $svc_phone = $cust_svc->svc_x;
1342 next if $svc_phone->phone_name;
1343 $svc_phone->phone_name($name);
1344 my $error = $svc_phone->replace;
1346 $dbh->rollback if $oldAutoCommit;
1354 # cust_tax_exempt (texas tax exemptions)
1355 # cust_recon (some sort of not-well understood thing for OnPac)
1357 #these are moved over
1358 foreach my $table (qw(
1359 cust_tag cust_location contact cust_attachment cust_main_note
1360 cust_tax_adjustment cust_pay_batch queue
1362 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1363 $record->custnum($new_custnum);
1364 my $error = $record->replace;
1366 $dbh->rollback if $oldAutoCommit;
1372 #these aren't preserved
1373 foreach my $table (qw(
1374 cust_main_exemption cust_main_invoice
1376 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1377 my $error = $record->delete;
1379 $dbh->rollback if $oldAutoCommit;
1386 my $sth = $dbh->prepare(
1387 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1389 my $errstr = $dbh->errstr;
1390 $dbh->rollback if $oldAutoCommit;
1393 $sth->execute($new_custnum, $self->custnum) or do {
1394 my $errstr = $sth->errstr;
1395 $dbh->rollback if $oldAutoCommit;
1401 my $ticket_dbh = '';
1402 if ($conf->config('ticket_system') eq 'RT_Internal') {
1404 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1405 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1406 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1407 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1410 if ( $ticket_dbh ) {
1412 my $ticket_sth = $ticket_dbh->prepare(
1413 'UPDATE Links SET Target = ? WHERE Target = ?'
1415 my $errstr = $ticket_dbh->errstr;
1416 $dbh->rollback if $oldAutoCommit;
1419 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1420 'freeside://freeside/cust_main/'.$self->custnum)
1422 my $errstr = $ticket_sth->errstr;
1423 $dbh->rollback if $oldAutoCommit;
1429 #delete the customer record
1431 my $error = $self->delete;
1433 $dbh->rollback if $oldAutoCommit;
1437 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1442 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1445 Replaces the OLD_RECORD with this one in the database. If there is an error,
1446 returns the error, otherwise returns false.
1448 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1449 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1450 expected and rollback the entire transaction; it is not necessary to call
1451 check_invoicing_list first. Here's an example:
1453 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1455 Currently available options are: I<tax_exemption>.
1457 The I<tax_exemption> option can be set to an arrayref of tax names.
1458 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1465 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1467 : $self->replace_old;
1471 warn "$me replace called\n"
1474 my $curuser = $FS::CurrentUser::CurrentUser;
1475 if ( $self->payby eq 'COMP'
1476 && $self->payby ne $old->payby
1477 && ! $curuser->access_right('Complimentary customer')
1480 return "You are not permitted to create complimentary accounts.";
1483 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1484 && $conf->exists('enable_taxproducts')
1487 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1489 $self->set('geocode', '')
1490 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1491 && length($self->get($pre.'zip')) >= 10;
1494 local($ignore_expired_card) = 1
1495 if $old->payby =~ /^(CARD|DCRD)$/
1496 && $self->payby =~ /^(CARD|DCRD)$/
1497 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1499 local($ignore_banned_card) = 1
1500 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1501 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1502 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1504 local $SIG{HUP} = 'IGNORE';
1505 local $SIG{INT} = 'IGNORE';
1506 local $SIG{QUIT} = 'IGNORE';
1507 local $SIG{TERM} = 'IGNORE';
1508 local $SIG{TSTP} = 'IGNORE';
1509 local $SIG{PIPE} = 'IGNORE';
1511 my $oldAutoCommit = $FS::UID::AutoCommit;
1512 local $FS::UID::AutoCommit = 0;
1515 my $error = $self->SUPER::replace($old);
1518 $dbh->rollback if $oldAutoCommit;
1522 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1523 my $invoicing_list = shift @param;
1524 $error = $self->check_invoicing_list( $invoicing_list );
1526 $dbh->rollback if $oldAutoCommit;
1529 $self->invoicing_list( $invoicing_list );
1532 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1534 #this could be more efficient than deleting and re-inserting, if it matters
1535 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1536 my $error = $cust_tag->delete;
1538 $dbh->rollback if $oldAutoCommit;
1542 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1543 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1544 'custnum' => $self->custnum };
1545 my $error = $cust_tag->insert;
1547 $dbh->rollback if $oldAutoCommit;
1554 my %options = @param;
1556 my $tax_exemption = delete $options{'tax_exemption'};
1557 if ( $tax_exemption ) {
1559 my %cust_main_exemption =
1560 map { $_->taxname => $_ }
1561 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1563 foreach my $taxname ( @$tax_exemption ) {
1565 next if delete $cust_main_exemption{$taxname};
1567 my $cust_main_exemption = new FS::cust_main_exemption {
1568 'custnum' => $self->custnum,
1569 'taxname' => $taxname,
1571 my $error = $cust_main_exemption->insert;
1573 $dbh->rollback if $oldAutoCommit;
1574 return "inserting cust_main_exemption (transaction rolled back): $error";
1578 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1579 my $error = $cust_main_exemption->delete;
1581 $dbh->rollback if $oldAutoCommit;
1582 return "deleting cust_main_exemption (transaction rolled back): $error";
1588 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1589 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1590 && $self->get('payinfo') !~ /^99\d{14}$/
1592 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1597 # card/check/lec info has changed, want to retry realtime_ invoice events
1598 my $error = $self->retry_realtime;
1600 $dbh->rollback if $oldAutoCommit;
1605 unless ( $import || $skip_fuzzyfiles ) {
1606 $error = $self->queue_fuzzyfiles_update;
1608 $dbh->rollback if $oldAutoCommit;
1609 return "updating fuzzy search cache: $error";
1613 # cust_main exports!
1615 my $export_args = $options{'export_args'} || [];
1618 map qsearch( 'part_export', {exportnum=>$_} ),
1619 $conf->config('cust_main-exports'); #, $agentnum
1621 foreach my $part_export ( @part_export ) {
1622 my $error = $part_export->export_replace( $self, $old, @$export_args);
1624 $dbh->rollback if $oldAutoCommit;
1625 return "exporting to ". $part_export->exporttype.
1626 " (transaction rolled back): $error";
1630 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1635 =item queue_fuzzyfiles_update
1637 Used by insert & replace to update the fuzzy search cache
1641 sub queue_fuzzyfiles_update {
1644 local $SIG{HUP} = 'IGNORE';
1645 local $SIG{INT} = 'IGNORE';
1646 local $SIG{QUIT} = 'IGNORE';
1647 local $SIG{TERM} = 'IGNORE';
1648 local $SIG{TSTP} = 'IGNORE';
1649 local $SIG{PIPE} = 'IGNORE';
1651 my $oldAutoCommit = $FS::UID::AutoCommit;
1652 local $FS::UID::AutoCommit = 0;
1655 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1656 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1658 $dbh->rollback if $oldAutoCommit;
1659 return "queueing job (transaction rolled back): $error";
1662 if ( $self->ship_last ) {
1663 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1664 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1666 $dbh->rollback if $oldAutoCommit;
1667 return "queueing job (transaction rolled back): $error";
1671 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1678 Checks all fields to make sure this is a valid customer record. If there is
1679 an error, returns the error, otherwise returns false. Called by the insert
1680 and replace methods.
1687 warn "$me check BEFORE: \n". $self->_dump
1691 $self->ut_numbern('custnum')
1692 || $self->ut_number('agentnum')
1693 || $self->ut_textn('agent_custid')
1694 || $self->ut_number('refnum')
1695 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1696 || $self->ut_textn('custbatch')
1697 || $self->ut_name('last')
1698 || $self->ut_name('first')
1699 || $self->ut_snumbern('birthdate')
1700 || $self->ut_snumbern('signupdate')
1701 || $self->ut_textn('company')
1702 || $self->ut_text('address1')
1703 || $self->ut_textn('address2')
1704 || $self->ut_text('city')
1705 || $self->ut_textn('county')
1706 || $self->ut_textn('state')
1707 || $self->ut_country('country')
1708 || $self->ut_anything('comments')
1709 || $self->ut_numbern('referral_custnum')
1710 || $self->ut_textn('stateid')
1711 || $self->ut_textn('stateid_state')
1712 || $self->ut_textn('invoice_terms')
1713 || $self->ut_alphan('geocode')
1714 || $self->ut_floatn('cdr_termination_percentage')
1715 || $self->ut_floatn('credit_limit')
1716 || $self->ut_numbern('billday')
1717 || $self->ut_enum('edit_subject', [ '', 'Y' ] )
1718 || $self->ut_enum('calling_list_exempt', [ '', 'Y' ] )
1719 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1722 #barf. need message catalogs. i18n. etc.
1723 $error .= "Please select an advertising source."
1724 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1725 return $error if $error;
1727 return "Unknown agent"
1728 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1730 return "Unknown refnum"
1731 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1733 return "Unknown referring custnum: ". $self->referral_custnum
1734 unless ! $self->referral_custnum
1735 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1737 if ( $self->censustract ne '' ) {
1738 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1739 or return "Illegal census tract: ". $self->censustract;
1741 $self->censustract("$1.$2");
1744 if ( $self->ss eq '' ) {
1749 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1750 or return "Illegal social security number: ". $self->ss;
1751 $self->ss("$1-$2-$3");
1755 # bad idea to disable, causes billing to fail because of no tax rates later
1756 # except we don't fail any more
1757 unless ( $import ) {
1758 unless ( qsearch('cust_main_county', {
1759 'country' => $self->country,
1762 return "Unknown state/county/country: ".
1763 $self->state. "/". $self->county. "/". $self->country
1764 unless qsearch('cust_main_county',{
1765 'state' => $self->state,
1766 'county' => $self->county,
1767 'country' => $self->country,
1773 $self->ut_phonen('daytime', $self->country)
1774 || $self->ut_phonen('night', $self->country)
1775 || $self->ut_phonen('fax', $self->country)
1776 || $self->ut_phonen('mobile', $self->country)
1778 return $error if $error;
1780 unless ( $ignore_illegal_zip ) {
1781 $error = $self->ut_zip('zip', $self->country);
1782 return $error if $error;
1785 if ( $conf->exists('cust_main-require_phone')
1786 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1789 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1791 : FS::Msgcat::_gettext('daytime');
1792 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1794 : FS::Msgcat::_gettext('night');
1796 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1798 : FS::Msgcat::_gettext('mobile');
1800 return "$daytime_label, $night_label or $mobile_label is required"
1804 if ( $self->has_ship_address
1805 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1806 $self->addr_fields )
1810 $self->ut_name('ship_last')
1811 || $self->ut_name('ship_first')
1812 || $self->ut_textn('ship_company')
1813 || $self->ut_text('ship_address1')
1814 || $self->ut_textn('ship_address2')
1815 || $self->ut_text('ship_city')
1816 || $self->ut_textn('ship_county')
1817 || $self->ut_textn('ship_state')
1818 || $self->ut_country('ship_country')
1820 return $error if $error;
1822 #false laziness with above
1823 unless ( qsearchs('cust_main_county', {
1824 'country' => $self->ship_country,
1827 return "Unknown ship_state/ship_county/ship_country: ".
1828 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1829 unless qsearch('cust_main_county',{
1830 'state' => $self->ship_state,
1831 'county' => $self->ship_county,
1832 'country' => $self->ship_country,
1838 $self->ut_phonen('ship_daytime', $self->ship_country)
1839 || $self->ut_phonen('ship_night', $self->ship_country)
1840 || $self->ut_phonen('ship_fax', $self->ship_country)
1841 || $self->ut_phonen('ship_mobile', $self->ship_country)
1843 return $error if $error;
1845 unless ( $ignore_illegal_zip ) {
1846 $error = $self->ut_zip('ship_zip', $self->ship_country);
1847 return $error if $error;
1849 return "Unit # is required."
1850 if $self->ship_address2 =~ /^\s*$/
1851 && $conf->exists('cust_main-require_address2');
1853 } else { # ship_ info eq billing info, so don't store dup info in database
1855 $self->setfield("ship_$_", '')
1856 foreach $self->addr_fields;
1858 return "Unit # is required."
1859 if $self->address2 =~ /^\s*$/
1860 && $conf->exists('cust_main-require_address2');
1864 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1865 # or return "Illegal payby: ". $self->payby;
1867 FS::payby->can_payby($self->table, $self->payby)
1868 or return "Illegal payby: ". $self->payby;
1870 $error = $self->ut_numbern('paystart_month')
1871 || $self->ut_numbern('paystart_year')
1872 || $self->ut_numbern('payissue')
1873 || $self->ut_textn('paytype')
1875 return $error if $error;
1877 if ( $self->payip eq '' ) {
1880 $error = $self->ut_ip('payip');
1881 return $error if $error;
1884 # If it is encrypted and the private key is not availaible then we can't
1885 # check the credit card.
1886 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1888 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1890 my $payinfo = $self->payinfo;
1891 $payinfo =~ s/\D//g;
1892 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1893 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1895 $self->payinfo($payinfo);
1897 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1899 return gettext('unknown_card_type')
1900 if $self->payinfo !~ /^99\d{14}$/ #token
1901 && cardtype($self->payinfo) eq "Unknown";
1903 unless ( $ignore_banned_card ) {
1904 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1906 if ( $ban->bantype eq 'warn' ) {
1907 #or others depending on value of $ban->reason ?
1908 return '_duplicate_card'.
1909 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1910 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1911 ' (ban# '. $ban->bannum. ')'
1912 unless $self->override_ban_warn;
1914 return 'Banned credit card: banned on '.
1915 time2str('%a %h %o at %r', $ban->_date).
1916 ' by '. $ban->otaker.
1917 ' (ban# '. $ban->bannum. ')';
1922 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1923 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1924 $self->paycvv =~ /^(\d{4})$/
1925 or return "CVV2 (CID) for American Express cards is four digits.";
1928 $self->paycvv =~ /^(\d{3})$/
1929 or return "CVV2 (CVC2/CID) is three digits.";
1936 my $cardtype = cardtype($payinfo);
1937 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1939 return "Start date or issue number is required for $cardtype cards"
1940 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1942 return "Start month must be between 1 and 12"
1943 if $self->paystart_month
1944 and $self->paystart_month < 1 || $self->paystart_month > 12;
1946 return "Start year must be 1990 or later"
1947 if $self->paystart_year
1948 and $self->paystart_year < 1990;
1950 return "Issue number must be beween 1 and 99"
1952 and $self->payissue < 1 || $self->payissue > 99;
1955 $self->paystart_month('');
1956 $self->paystart_year('');
1957 $self->payissue('');
1960 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1962 my $payinfo = $self->payinfo;
1963 $payinfo =~ s/[^\d\@\.]//g;
1964 if ( $conf->exists('cust_main-require-bank-branch') ) {
1965 $payinfo =~ /^(\d+)\@(\d+)\.(\d+)$/ or return 'invalid echeck account@branch.bank';
1966 $payinfo = "$1\@$2.$3";
1967 } elsif ( $conf->exists('echeck-nonus') ) {
1968 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1969 $payinfo = "$1\@$2";
1971 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1972 $payinfo = "$1\@$2";
1974 $self->payinfo($payinfo);
1977 unless ( $ignore_banned_card ) {
1978 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1980 if ( $ban->bantype eq 'warn' ) {
1981 #or others depending on value of $ban->reason ?
1982 return '_duplicate_ach' unless $self->override_ban_warn;
1984 return 'Banned ACH account: banned on '.
1985 time2str('%a %h %o at %r', $ban->_date).
1986 ' by '. $ban->otaker.
1987 ' (ban# '. $ban->bannum. ')';
1992 } elsif ( $self->payby eq 'LECB' ) {
1994 my $payinfo = $self->payinfo;
1995 $payinfo =~ s/\D//g;
1996 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1998 $self->payinfo($payinfo);
2001 } elsif ( $self->payby eq 'BILL' ) {
2003 $error = $self->ut_textn('payinfo');
2004 return "Illegal P.O. number: ". $self->payinfo if $error;
2007 } elsif ( $self->payby eq 'COMP' ) {
2009 my $curuser = $FS::CurrentUser::CurrentUser;
2010 if ( ! $self->custnum
2011 && ! $curuser->access_right('Complimentary customer')
2014 return "You are not permitted to create complimentary accounts."
2017 $error = $self->ut_textn('payinfo');
2018 return "Illegal comp account issuer: ". $self->payinfo if $error;
2021 } elsif ( $self->payby eq 'PREPAY' ) {
2023 my $payinfo = $self->payinfo;
2024 $payinfo =~ s/\W//g; #anything else would just confuse things
2025 $self->payinfo($payinfo);
2026 $error = $self->ut_alpha('payinfo');
2027 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2028 return "Unknown prepayment identifier"
2029 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2034 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2035 return "Expiration date required"
2036 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2040 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2041 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2042 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2043 ( $m, $y ) = ( $2, "19$1" );
2044 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2045 ( $m, $y ) = ( $3, "20$2" );
2047 return "Illegal expiration date: ". $self->paydate;
2049 $m = sprintf('%02d',$m);
2050 $self->paydate("$y-$m-01");
2051 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2052 return gettext('expired_card')
2054 && !$ignore_expired_card
2055 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2058 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2059 ( ! $conf->exists('require_cardname')
2060 || $self->payby !~ /^(CARD|DCRD)$/ )
2062 $self->payname( $self->first. " ". $self->getfield('last') );
2064 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2065 or return gettext('illegal_name'). " payname: ". $self->payname;
2069 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2070 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2074 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2076 warn "$me check AFTER: \n". $self->_dump
2079 $self->SUPER::check;
2084 Returns a list of fields which have ship_ duplicates.
2089 qw( last first company
2090 address1 address2 city county state zip country
2091 daytime night fax mobile
2095 =item has_ship_address
2097 Returns true if this customer record has a separate shipping address.
2101 sub has_ship_address {
2103 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2108 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2109 city, county, state, zip, country, and geocode. The shipping address is used if present.
2115 Returns all locations (see L<FS::cust_location>) for this customer.
2121 qsearch('cust_location', { 'custnum' => $self->custnum } );
2126 Returns all contacts (see L<FS::contact>) for this customer.
2130 #already used :/ sub contact {
2133 qsearch('contact', { 'custnum' => $self->custnum } );
2138 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2139 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2140 on success or a list of errors.
2146 grep { $_->unsuspend } $self->suspended_pkgs;
2151 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2153 Returns a list: an empty list on success or a list of errors.
2159 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2162 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2164 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2165 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2166 of a list of pkgparts; the hashref has the following keys:
2170 =item pkgparts - listref of pkgparts
2172 =item (other options are passed to the suspend method)
2177 Returns a list: an empty list on success or a list of errors.
2181 sub suspend_if_pkgpart {
2183 my (@pkgparts, %opt);
2184 if (ref($_[0]) eq 'HASH'){
2185 @pkgparts = @{$_[0]{pkgparts}};
2190 grep { $_->suspend(%opt) }
2191 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2192 $self->unsuspended_pkgs;
2195 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2197 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2198 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2199 instead of a list of pkgparts; the hashref has the following keys:
2203 =item pkgparts - listref of pkgparts
2205 =item (other options are passed to the suspend method)
2209 Returns a list: an empty list on success or a list of errors.
2213 sub suspend_unless_pkgpart {
2215 my (@pkgparts, %opt);
2216 if (ref($_[0]) eq 'HASH'){
2217 @pkgparts = @{$_[0]{pkgparts}};
2222 grep { $_->suspend(%opt) }
2223 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2224 $self->unsuspended_pkgs;
2227 =item cancel [ OPTION => VALUE ... ]
2229 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2231 Available options are:
2235 =item quiet - can be set true to supress email cancellation notices.
2237 =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.
2239 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2241 =item nobill - can be set true to skip billing if it might otherwise be done.
2245 Always returns a list: an empty list on success or a list of errors.
2249 # nb that dates are not specified as valid options to this method
2252 my( $self, %opt ) = @_;
2254 warn "$me cancel called on customer ". $self->custnum. " with options ".
2255 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2258 return ( 'access denied' )
2259 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2261 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2263 #should try decryption (we might have the private key)
2264 # and if not maybe queue a job for the server that does?
2265 return ( "Can't (yet) ban encrypted credit cards" )
2266 if $self->is_encrypted($self->payinfo);
2268 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2269 my $error = $ban->insert;
2270 return ( $error ) if $error;
2274 my @pkgs = $self->ncancelled_pkgs;
2276 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2278 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2279 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2283 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2284 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2287 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2290 sub _banned_pay_hashref {
2301 'payby' => $payby2ban{$self->payby},
2302 'payinfo' => $self->payinfo,
2303 #don't ever *search* on reason! #'reason' =>
2307 sub _new_banned_pay_hashref {
2309 my $hr = $self->_banned_pay_hashref;
2310 $hr->{payinfo} = md5_base64($hr->{payinfo});
2316 Returns all notes (see L<FS::cust_main_note>) for this customer.
2321 my($self,$orderby_classnum) = (shift,shift);
2322 my $orderby = "_DATE DESC";
2323 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2324 qsearch( 'cust_main_note',
2325 { 'custnum' => $self->custnum },
2327 "ORDER BY $orderby",
2333 Returns the agent (see L<FS::agent>) for this customer.
2339 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2344 Returns the agent name (see L<FS::agent>) for this customer.
2350 $self->agent->agent;
2355 Returns any tags associated with this customer, as FS::cust_tag objects,
2356 or an empty list if there are no tags.
2362 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2367 Returns any tags associated with this customer, as FS::part_tag objects,
2368 or an empty list if there are no tags.
2374 map $_->part_tag, $self->cust_tag;
2380 Returns the customer class, as an FS::cust_class object, or the empty string
2381 if there is no customer class.
2387 if ( $self->classnum ) {
2388 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2396 Returns the customer category name, or the empty string if there is no customer
2403 my $cust_class = $self->cust_class;
2405 ? $cust_class->categoryname
2411 Returns the customer class name, or the empty string if there is no customer
2418 my $cust_class = $self->cust_class;
2420 ? $cust_class->classname
2424 =item BILLING METHODS
2426 Documentation on billing methods has been moved to
2427 L<FS::cust_main::Billing>.
2429 =item REALTIME BILLING METHODS
2431 Documentation on realtime billing methods has been moved to
2432 L<FS::cust_main::Billing_Realtime>.
2436 Removes the I<paycvv> field from the database directly.
2438 If there is an error, returns the error, otherwise returns false.
2444 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2445 or return dbh->errstr;
2446 $sth->execute($self->custnum)
2447 or return $sth->errstr;
2452 =item batch_card OPTION => VALUE...
2454 Adds a payment for this invoice to the pending credit card batch (see
2455 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2456 runs the payment using a realtime gateway.
2461 my ($self, %options) = @_;
2464 if (exists($options{amount})) {
2465 $amount = $options{amount};
2467 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2469 return '' unless $amount > 0;
2471 my $invnum = delete $options{invnum};
2472 my $payby = $options{payby} || $self->payby; #still dubious
2474 if ($options{'realtime'}) {
2475 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2481 my $oldAutoCommit = $FS::UID::AutoCommit;
2482 local $FS::UID::AutoCommit = 0;
2485 #this needs to handle mysql as well as Pg, like svc_acct.pm
2486 #(make it into a common function if folks need to do batching with mysql)
2487 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2488 or return "Cannot lock pay_batch: " . $dbh->errstr;
2492 'payby' => FS::payby->payby2payment($payby),
2494 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2496 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2498 unless ( $pay_batch ) {
2499 $pay_batch = new FS::pay_batch \%pay_batch;
2500 my $error = $pay_batch->insert;
2502 $dbh->rollback if $oldAutoCommit;
2503 die "error creating new batch: $error\n";
2507 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2508 'batchnum' => $pay_batch->batchnum,
2509 'custnum' => $self->custnum,
2512 foreach (qw( address1 address2 city state zip country payby payinfo paydate
2514 $options{$_} = '' unless exists($options{$_});
2517 my $cust_pay_batch = new FS::cust_pay_batch ( {
2518 'batchnum' => $pay_batch->batchnum,
2519 'invnum' => $invnum || 0, # is there a better value?
2520 # this field should be
2522 # cust_bill_pay_batch now
2523 'custnum' => $self->custnum,
2524 'last' => $self->getfield('last'),
2525 'first' => $self->getfield('first'),
2526 'address1' => $options{address1} || $self->address1,
2527 'address2' => $options{address2} || $self->address2,
2528 'city' => $options{city} || $self->city,
2529 'state' => $options{state} || $self->state,
2530 'zip' => $options{zip} || $self->zip,
2531 'country' => $options{country} || $self->country,
2532 'payby' => $options{payby} || $self->payby,
2533 'payinfo' => $options{payinfo} || $self->payinfo,
2534 'exp' => $options{paydate} || $self->paydate,
2535 'payname' => $options{payname} || $self->payname,
2536 'amount' => $amount, # consolidating
2539 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2540 if $old_cust_pay_batch;
2543 if ($old_cust_pay_batch) {
2544 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2546 $error = $cust_pay_batch->insert;
2550 $dbh->rollback if $oldAutoCommit;
2554 my $unapplied = $self->total_unapplied_credits
2555 + $self->total_unapplied_payments
2556 + $self->in_transit_payments;
2557 foreach my $cust_bill ($self->open_cust_bill) {
2558 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2559 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2560 'invnum' => $cust_bill->invnum,
2561 'paybatchnum' => $cust_pay_batch->paybatchnum,
2562 'amount' => $cust_bill->owed,
2565 if ($unapplied >= $cust_bill_pay_batch->amount){
2566 $unapplied -= $cust_bill_pay_batch->amount;
2569 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2570 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2572 $error = $cust_bill_pay_batch->insert;
2574 $dbh->rollback if $oldAutoCommit;
2579 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2585 Returns the total owed for this customer on all invoices
2586 (see L<FS::cust_bill/owed>).
2592 $self->total_owed_date(2145859200); #12/31/2037
2595 =item total_owed_date TIME
2597 Returns the total owed for this customer on all invoices with date earlier than
2598 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2599 see L<Time::Local> and L<Date::Parse> for conversion functions.
2603 sub total_owed_date {
2607 my $custnum = $self->custnum;
2609 my $owed_sql = FS::cust_bill->owed_sql;
2612 SELECT SUM($owed_sql) FROM cust_bill
2613 WHERE custnum = $custnum
2617 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2621 =item total_owed_pkgnum PKGNUM
2623 Returns the total owed on all invoices for this customer's specific package
2624 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2628 sub total_owed_pkgnum {
2629 my( $self, $pkgnum ) = @_;
2630 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2633 =item total_owed_date_pkgnum TIME PKGNUM
2635 Returns the total owed for this customer's specific package when using
2636 experimental package balances on all invoices with date earlier than
2637 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2638 see L<Time::Local> and L<Date::Parse> for conversion functions.
2642 sub total_owed_date_pkgnum {
2643 my( $self, $time, $pkgnum ) = @_;
2646 foreach my $cust_bill (
2647 grep { $_->_date <= $time }
2648 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2650 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2652 sprintf( "%.2f", $total_bill );
2658 Returns the total amount of all payments.
2665 $total += $_->paid foreach $self->cust_pay;
2666 sprintf( "%.2f", $total );
2669 =item total_unapplied_credits
2671 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2672 customer. See L<FS::cust_credit/credited>.
2674 =item total_credited
2676 Old name for total_unapplied_credits. Don't use.
2680 sub total_credited {
2681 #carp "total_credited deprecated, use total_unapplied_credits";
2682 shift->total_unapplied_credits(@_);
2685 sub total_unapplied_credits {
2688 my $custnum = $self->custnum;
2690 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2693 SELECT SUM($unapplied_sql) FROM cust_credit
2694 WHERE custnum = $custnum
2697 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2701 =item total_unapplied_credits_pkgnum PKGNUM
2703 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2704 customer. See L<FS::cust_credit/credited>.
2708 sub total_unapplied_credits_pkgnum {
2709 my( $self, $pkgnum ) = @_;
2710 my $total_credit = 0;
2711 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2712 sprintf( "%.2f", $total_credit );
2716 =item total_unapplied_payments
2718 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2719 See L<FS::cust_pay/unapplied>.
2723 sub total_unapplied_payments {
2726 my $custnum = $self->custnum;
2728 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2731 SELECT SUM($unapplied_sql) FROM cust_pay
2732 WHERE custnum = $custnum
2735 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2739 =item total_unapplied_payments_pkgnum PKGNUM
2741 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2742 specific package when using experimental package balances. See
2743 L<FS::cust_pay/unapplied>.
2747 sub total_unapplied_payments_pkgnum {
2748 my( $self, $pkgnum ) = @_;
2749 my $total_unapplied = 0;
2750 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2751 sprintf( "%.2f", $total_unapplied );
2755 =item total_unapplied_refunds
2757 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2758 customer. See L<FS::cust_refund/unapplied>.
2762 sub total_unapplied_refunds {
2764 my $custnum = $self->custnum;
2766 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2769 SELECT SUM($unapplied_sql) FROM cust_refund
2770 WHERE custnum = $custnum
2773 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2779 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2780 total_unapplied_credits minus total_unapplied_payments).
2786 $self->balance_date_range;
2789 =item balance_date TIME
2791 Returns the balance for this customer, only considering invoices with date
2792 earlier than TIME (total_owed_date minus total_credited minus
2793 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2794 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2801 $self->balance_date_range(shift);
2804 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2806 Returns the balance for this customer, optionally considering invoices with
2807 date earlier than START_TIME, and not later than END_TIME
2808 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2810 Times are specified as SQL fragments or numeric
2811 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2812 L<Date::Parse> for conversion functions. The empty string can be passed
2813 to disable that time constraint completely.
2815 Available options are:
2819 =item unapplied_date
2821 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)
2827 sub balance_date_range {
2829 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2830 ') FROM cust_main WHERE custnum='. $self->custnum;
2831 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2834 =item balance_pkgnum PKGNUM
2836 Returns the balance for this customer's specific package when using
2837 experimental package balances (total_owed plus total_unrefunded, minus
2838 total_unapplied_credits minus total_unapplied_payments)
2842 sub balance_pkgnum {
2843 my( $self, $pkgnum ) = @_;
2846 $self->total_owed_pkgnum($pkgnum)
2847 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2848 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2849 - $self->total_unapplied_credits_pkgnum($pkgnum)
2850 - $self->total_unapplied_payments_pkgnum($pkgnum)
2854 =item in_transit_payments
2856 Returns the total of requests for payments for this customer pending in
2857 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2861 sub in_transit_payments {
2863 my $in_transit_payments = 0;
2864 foreach my $pay_batch ( qsearch('pay_batch', {
2867 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2868 'batchnum' => $pay_batch->batchnum,
2869 'custnum' => $self->custnum,
2871 $in_transit_payments += $cust_pay_batch->amount;
2874 sprintf( "%.2f", $in_transit_payments );
2879 Returns a hash of useful information for making a payment.
2889 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2890 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2891 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2895 For credit card transactions:
2907 For electronic check transactions:
2922 $return{balance} = $self->balance;
2924 $return{payname} = $self->payname
2925 || ( $self->first. ' '. $self->get('last') );
2927 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
2929 $return{payby} = $self->payby;
2930 $return{stateid_state} = $self->stateid_state;
2932 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2933 $return{card_type} = cardtype($self->payinfo);
2934 $return{payinfo} = $self->paymask;
2936 @return{'month', 'year'} = $self->paydate_monthyear;
2940 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2941 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2942 $return{payinfo1} = $payinfo1;
2943 $return{payinfo2} = $payinfo2;
2944 $return{paytype} = $self->paytype;
2945 $return{paystate} = $self->paystate;
2949 #doubleclick protection
2951 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2957 =item paydate_monthyear
2959 Returns a two-element list consisting of the month and year of this customer's
2960 paydate (credit card expiration date for CARD customers)
2964 sub paydate_monthyear {
2966 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2968 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2977 Returns the exact time in seconds corresponding to the payment method
2978 expiration date. For CARD/DCRD customers this is the end of the month;
2979 for others (COMP is the only other payby that uses paydate) it's the start.
2980 Returns 0 if the paydate is empty or set to the far future.
2986 my ($month, $year) = $self->paydate_monthyear;
2987 return 0 if !$year or $year >= 2037;
2988 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2990 if ( $month == 13 ) {
2994 return timelocal(0,0,0,1,$month-1,$year) - 1;
2997 return timelocal(0,0,0,1,$month-1,$year);
3001 =item paydate_epoch_sql
3003 Class method. Returns an SQL expression to obtain the payment expiration date
3004 as a number of seconds.
3008 # Special expiration date behavior for non-CARD/DCRD customers has been
3009 # carefully preserved. Do we really use that?
3010 sub paydate_epoch_sql {
3012 my $table = shift || 'cust_main';
3013 my ($case1, $case2);
3014 if ( driver_name eq 'Pg' ) {
3015 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3016 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3018 elsif ( lc(driver_name) eq 'mysql' ) {
3019 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3020 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3023 return "CASE WHEN $table.payby IN('CARD','DCRD')
3029 =item tax_exemption TAXNAME
3034 my( $self, $taxname ) = @_;
3036 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3037 'taxname' => $taxname,
3042 =item cust_main_exemption
3046 sub cust_main_exemption {
3048 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3051 =item invoicing_list [ ARRAYREF ]
3053 If an arguement is given, sets these email addresses as invoice recipients
3054 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3055 (except as warnings), so use check_invoicing_list first.
3057 Returns a list of email addresses (with svcnum entries expanded).
3059 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3060 check it without disturbing anything by passing nothing.
3062 This interface may change in the future.
3066 sub invoicing_list {
3067 my( $self, $arrayref ) = @_;
3070 my @cust_main_invoice;
3071 if ( $self->custnum ) {
3072 @cust_main_invoice =
3073 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3075 @cust_main_invoice = ();
3077 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3078 #warn $cust_main_invoice->destnum;
3079 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3080 #warn $cust_main_invoice->destnum;
3081 my $error = $cust_main_invoice->delete;
3082 warn $error if $error;
3085 if ( $self->custnum ) {
3086 @cust_main_invoice =
3087 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3089 @cust_main_invoice = ();
3091 my %seen = map { $_->address => 1 } @cust_main_invoice;
3092 foreach my $address ( @{$arrayref} ) {
3093 next if exists $seen{$address} && $seen{$address};
3094 $seen{$address} = 1;
3095 my $cust_main_invoice = new FS::cust_main_invoice ( {
3096 'custnum' => $self->custnum,
3099 my $error = $cust_main_invoice->insert;
3100 warn $error if $error;
3104 if ( $self->custnum ) {
3106 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3113 =item check_invoicing_list ARRAYREF
3115 Checks these arguements as valid input for the invoicing_list method. If there
3116 is an error, returns the error, otherwise returns false.
3120 sub check_invoicing_list {
3121 my( $self, $arrayref ) = @_;
3123 foreach my $address ( @$arrayref ) {
3125 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3126 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3129 my $cust_main_invoice = new FS::cust_main_invoice ( {
3130 'custnum' => $self->custnum,
3133 my $error = $self->custnum
3134 ? $cust_main_invoice->check
3135 : $cust_main_invoice->checkdest
3137 return $error if $error;
3141 return "Email address required"
3142 if $conf->exists('cust_main-require_invoicing_list_email')
3143 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3148 =item set_default_invoicing_list
3150 Sets the invoicing list to all accounts associated with this customer,
3151 overwriting any previous invoicing list.
3155 sub set_default_invoicing_list {
3157 $self->invoicing_list($self->all_emails);
3162 Returns the email addresses of all accounts provisioned for this customer.
3169 foreach my $cust_pkg ( $self->all_pkgs ) {
3170 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3172 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3173 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3175 $list{$_}=1 foreach map { $_->email } @svc_acct;
3180 =item invoicing_list_addpost
3182 Adds postal invoicing to this customer. If this customer is already configured
3183 to receive postal invoices, does nothing.
3187 sub invoicing_list_addpost {
3189 return if grep { $_ eq 'POST' } $self->invoicing_list;
3190 my @invoicing_list = $self->invoicing_list;
3191 push @invoicing_list, 'POST';
3192 $self->invoicing_list(\@invoicing_list);
3195 =item invoicing_list_emailonly
3197 Returns the list of email invoice recipients (invoicing_list without non-email
3198 destinations such as POST and FAX).
3202 sub invoicing_list_emailonly {
3204 warn "$me invoicing_list_emailonly called"
3206 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3209 =item invoicing_list_emailonly_scalar
3211 Returns the list of email invoice recipients (invoicing_list without non-email
3212 destinations such as POST and FAX) as a comma-separated scalar.
3216 sub invoicing_list_emailonly_scalar {
3218 warn "$me invoicing_list_emailonly_scalar called"
3220 join(', ', $self->invoicing_list_emailonly);
3223 =item referral_custnum_cust_main
3225 Returns the customer who referred this customer (or the empty string, if
3226 this customer was not referred).
3228 Note the difference with referral_cust_main method: This method,
3229 referral_custnum_cust_main returns the single customer (if any) who referred
3230 this customer, while referral_cust_main returns an array of customers referred
3235 sub referral_custnum_cust_main {
3237 return '' unless $self->referral_custnum;
3238 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3241 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3243 Returns an array of customers referred by this customer (referral_custnum set
3244 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3245 customers referred by customers referred by this customer and so on, inclusive.
3246 The default behavior is DEPTH 1 (no recursion).
3248 Note the difference with referral_custnum_cust_main method: This method,
3249 referral_cust_main, returns an array of customers referred BY this customer,
3250 while referral_custnum_cust_main returns the single customer (if any) who
3251 referred this customer.
3255 sub referral_cust_main {
3257 my $depth = @_ ? shift : 1;
3258 my $exclude = @_ ? shift : {};
3261 map { $exclude->{$_->custnum}++; $_; }
3262 grep { ! $exclude->{ $_->custnum } }
3263 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3267 map { $_->referral_cust_main($depth-1, $exclude) }
3274 =item referral_cust_main_ncancelled
3276 Same as referral_cust_main, except only returns customers with uncancelled
3281 sub referral_cust_main_ncancelled {
3283 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3286 =item referral_cust_pkg [ DEPTH ]
3288 Like referral_cust_main, except returns a flat list of all unsuspended (and
3289 uncancelled) packages for each customer. The number of items in this list may
3290 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3294 sub referral_cust_pkg {
3296 my $depth = @_ ? shift : 1;
3298 map { $_->unsuspended_pkgs }
3299 grep { $_->unsuspended_pkgs }
3300 $self->referral_cust_main($depth);
3303 =item referring_cust_main
3305 Returns the single cust_main record for the customer who referred this customer
3306 (referral_custnum), or false.
3310 sub referring_cust_main {
3312 return '' unless $self->referral_custnum;
3313 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3316 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3318 Applies a credit to this customer. If there is an error, returns the error,
3319 otherwise returns false.
3321 REASON can be a text string, an FS::reason object, or a scalar reference to
3322 a reasonnum. If a text string, it will be automatically inserted as a new
3323 reason, and a 'reason_type' option must be passed to indicate the
3324 FS::reason_type for the new reason.
3326 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3328 Any other options are passed to FS::cust_credit::insert.
3333 my( $self, $amount, $reason, %options ) = @_;
3335 my $cust_credit = new FS::cust_credit {
3336 'custnum' => $self->custnum,
3337 'amount' => $amount,
3340 if ( ref($reason) ) {
3342 if ( ref($reason) eq 'SCALAR' ) {
3343 $cust_credit->reasonnum( $$reason );
3345 $cust_credit->reasonnum( $reason->reasonnum );
3349 $cust_credit->set('reason', $reason)
3352 for (qw( addlinfo eventnum )) {
3353 $cust_credit->$_( delete $options{$_} )
3354 if exists($options{$_});
3357 $cust_credit->insert(%options);
3361 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3363 Creates a one-time charge for this customer. If there is an error, returns
3364 the error, otherwise returns false.
3366 New-style, with a hashref of options:
3368 my $error = $cust_main->charge(
3372 'start_date' => str2time('7/4/2009'),
3373 'pkg' => 'Description',
3374 'comment' => 'Comment',
3375 'additional' => [], #extra invoice detail
3376 'classnum' => 1, #pkg_class
3378 'setuptax' => '', # or 'Y' for tax exempt
3381 'taxclass' => 'Tax class',
3384 'taxproduct' => 2, #part_pkg_taxproduct
3385 'override' => {}, #XXX describe
3387 #will be filled in with the new object
3388 'cust_pkg_ref' => \$cust_pkg,
3390 #generate an invoice immediately
3392 'invoice_terms' => '', #with these terms
3398 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3404 my ( $amount, $quantity, $start_date, $classnum );
3405 my ( $pkg, $comment, $additional );
3406 my ( $setuptax, $taxclass ); #internal taxes
3407 my ( $taxproduct, $override ); #vendor (CCH) taxes
3409 my $cust_pkg_ref = '';
3410 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3411 if ( ref( $_[0] ) ) {
3412 $amount = $_[0]->{amount};
3413 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3414 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3415 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3416 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3417 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3418 : '$'. sprintf("%.2f",$amount);
3419 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3420 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3421 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3422 $additional = $_[0]->{additional} || [];
3423 $taxproduct = $_[0]->{taxproductnum};
3424 $override = { '' => $_[0]->{tax_override} };
3425 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3426 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3427 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3432 $pkg = @_ ? shift : 'One-time charge';
3433 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3435 $taxclass = @_ ? shift : '';
3439 local $SIG{HUP} = 'IGNORE';
3440 local $SIG{INT} = 'IGNORE';
3441 local $SIG{QUIT} = 'IGNORE';
3442 local $SIG{TERM} = 'IGNORE';
3443 local $SIG{TSTP} = 'IGNORE';
3444 local $SIG{PIPE} = 'IGNORE';
3446 my $oldAutoCommit = $FS::UID::AutoCommit;
3447 local $FS::UID::AutoCommit = 0;
3450 my $part_pkg = new FS::part_pkg ( {
3452 'comment' => $comment,
3456 'classnum' => ( $classnum ? $classnum : '' ),
3457 'setuptax' => $setuptax,
3458 'taxclass' => $taxclass,
3459 'taxproductnum' => $taxproduct,
3462 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3463 ( 0 .. @$additional - 1 )
3465 'additional_count' => scalar(@$additional),
3466 'setup_fee' => $amount,
3469 my $error = $part_pkg->insert( options => \%options,
3470 tax_overrides => $override,
3473 $dbh->rollback if $oldAutoCommit;
3477 my $pkgpart = $part_pkg->pkgpart;
3478 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3479 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3480 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3481 $error = $type_pkgs->insert;
3483 $dbh->rollback if $oldAutoCommit;
3488 my $cust_pkg = new FS::cust_pkg ( {
3489 'custnum' => $self->custnum,
3490 'pkgpart' => $pkgpart,
3491 'quantity' => $quantity,
3492 'start_date' => $start_date,
3493 'no_auto' => $no_auto,
3496 $error = $cust_pkg->insert;
3498 $dbh->rollback if $oldAutoCommit;
3500 } elsif ( $cust_pkg_ref ) {
3501 ${$cust_pkg_ref} = $cust_pkg;
3505 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3506 'pkg_list' => [ $cust_pkg ],
3509 $dbh->rollback if $oldAutoCommit;
3514 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3519 #=item charge_postal_fee
3521 #Applies a one time charge this customer. If there is an error,
3522 #returns the error, returns the cust_pkg charge object or false
3523 #if there was no charge.
3527 # This should be a customer event. For that to work requires that bill
3528 # also be a customer event.
3530 sub charge_postal_fee {
3533 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3534 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3536 my $cust_pkg = new FS::cust_pkg ( {
3537 'custnum' => $self->custnum,
3538 'pkgpart' => $pkgpart,
3542 my $error = $cust_pkg->insert;
3543 $error ? $error : $cust_pkg;
3546 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3548 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3550 Optionally, a list or hashref of additional arguments to the qsearch call can
3557 my $opt = ref($_[0]) ? shift : { @_ };
3559 #return $self->num_cust_bill unless wantarray || keys %$opt;
3561 $opt->{'table'} = 'cust_bill';
3562 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3563 $opt->{'hashref'}{'custnum'} = $self->custnum;
3564 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3566 map { $_ } #behavior of sort undefined in scalar context
3567 sort { $a->_date <=> $b->_date }
3571 =item open_cust_bill
3573 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3578 sub open_cust_bill {
3582 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3588 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3590 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3594 sub legacy_cust_bill {
3597 #return $self->num_legacy_cust_bill unless wantarray;
3599 map { $_ } #behavior of sort undefined in scalar context
3600 sort { $a->_date <=> $b->_date }
3601 qsearch({ 'table' => 'legacy_cust_bill',
3602 'hashref' => { 'custnum' => $self->custnum, },
3603 'order_by' => 'ORDER BY _date ASC',
3607 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3609 Returns all the statements (see L<FS::cust_statement>) for this customer.
3611 Optionally, a list or hashref of additional arguments to the qsearch call can
3616 sub cust_statement {
3618 my $opt = ref($_[0]) ? shift : { @_ };
3620 #return $self->num_cust_statement unless wantarray || keys %$opt;
3622 $opt->{'table'} = 'cust_statement';
3623 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3624 $opt->{'hashref'}{'custnum'} = $self->custnum;
3625 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3627 map { $_ } #behavior of sort undefined in scalar context
3628 sort { $a->_date <=> $b->_date }
3634 Returns all the credits (see L<FS::cust_credit>) for this customer.
3640 map { $_ } #return $self->num_cust_credit unless wantarray;
3641 sort { $a->_date <=> $b->_date }
3642 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3645 =item cust_credit_pkgnum
3647 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3648 package when using experimental package balances.
3652 sub cust_credit_pkgnum {
3653 my( $self, $pkgnum ) = @_;
3654 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3655 sort { $a->_date <=> $b->_date }
3656 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3657 'pkgnum' => $pkgnum,
3664 Returns all the payments (see L<FS::cust_pay>) for this customer.
3670 return $self->num_cust_pay unless wantarray;
3671 sort { $a->_date <=> $b->_date }
3672 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3677 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3678 called automatically when the cust_pay method is used in a scalar context.
3684 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3685 my $sth = dbh->prepare($sql) or die dbh->errstr;
3686 $sth->execute($self->custnum) or die $sth->errstr;
3687 $sth->fetchrow_arrayref->[0];
3690 =item cust_pay_pkgnum
3692 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3693 package when using experimental package balances.
3697 sub cust_pay_pkgnum {
3698 my( $self, $pkgnum ) = @_;
3699 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3700 sort { $a->_date <=> $b->_date }
3701 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3702 'pkgnum' => $pkgnum,
3709 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3715 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3716 sort { $a->_date <=> $b->_date }
3717 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3720 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3722 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3724 Optionally, a list or hashref of additional arguments to the qsearch call can
3729 sub cust_pay_batch {
3731 my $opt = ref($_[0]) ? shift : { @_ };
3733 #return $self->num_cust_statement unless wantarray || keys %$opt;
3735 $opt->{'table'} = 'cust_pay_batch';
3736 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3737 $opt->{'hashref'}{'custnum'} = $self->custnum;
3738 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3740 map { $_ } #behavior of sort undefined in scalar context
3741 sort { $a->paybatchnum <=> $b->paybatchnum }
3745 =item cust_pay_pending
3747 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3748 (without status "done").
3752 sub cust_pay_pending {
3754 return $self->num_cust_pay_pending unless wantarray;
3755 sort { $a->_date <=> $b->_date }
3756 qsearch( 'cust_pay_pending', {
3757 'custnum' => $self->custnum,
3758 'status' => { op=>'!=', value=>'done' },
3763 =item cust_pay_pending_attempt
3765 Returns all payment attempts / declined payments for this customer, as pending
3766 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3767 a corresponding payment (see L<FS::cust_pay>).
3771 sub cust_pay_pending_attempt {
3773 return $self->num_cust_pay_pending_attempt unless wantarray;
3774 sort { $a->_date <=> $b->_date }
3775 qsearch( 'cust_pay_pending', {
3776 'custnum' => $self->custnum,
3783 =item num_cust_pay_pending
3785 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3786 customer (without status "done"). Also called automatically when the
3787 cust_pay_pending method is used in a scalar context.
3791 sub num_cust_pay_pending {
3794 " SELECT COUNT(*) FROM cust_pay_pending ".
3795 " WHERE custnum = ? AND status != 'done' ",
3800 =item num_cust_pay_pending_attempt
3802 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3803 customer, with status "done" but without a corresp. Also called automatically when the
3804 cust_pay_pending method is used in a scalar context.
3808 sub num_cust_pay_pending_attempt {
3811 " SELECT COUNT(*) FROM cust_pay_pending ".
3812 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3819 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3825 map { $_ } #return $self->num_cust_refund unless wantarray;
3826 sort { $a->_date <=> $b->_date }
3827 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3830 =item display_custnum
3832 Returns the displayed customer number for this customer: agent_custid if
3833 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3837 sub display_custnum {
3839 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3840 return $self->agent_custid;
3842 return $self->custnum;
3848 Returns a name string for this customer, either "Company (Last, First)" or
3855 my $name = $self->contact;
3856 $name = $self->company. " ($name)" if $self->company;
3862 Returns a name string for this (service/shipping) contact, either
3863 "Company (Last, First)" or "Last, First".
3869 if ( $self->get('ship_last') ) {
3870 my $name = $self->ship_contact;
3871 $name = $self->ship_company. " ($name)" if $self->ship_company;
3880 Returns a name string for this customer, either "Company" or "First Last".
3886 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3889 =item ship_name_short
3891 Returns a name string for this (service/shipping) contact, either "Company"
3896 sub ship_name_short {
3898 if ( $self->get('ship_last') ) {
3899 $self->ship_company !~ /^\s*$/
3900 ? $self->ship_company
3901 : $self->ship_contact_firstlast;
3903 $self->name_company_or_firstlast;
3909 Returns this customer's full (billing) contact name only, "Last, First"
3915 $self->get('last'). ', '. $self->first;
3920 Returns this customer's full (shipping) contact name only, "Last, First"
3926 $self->get('ship_last')
3927 ? $self->get('ship_last'). ', '. $self->ship_first
3931 =item contact_firstlast
3933 Returns this customers full (billing) contact name only, "First Last".
3937 sub contact_firstlast {
3939 $self->first. ' '. $self->get('last');
3942 =item ship_contact_firstlast
3944 Returns this customer's full (shipping) contact name only, "First Last".
3948 sub ship_contact_firstlast {
3950 $self->get('ship_last')
3951 ? $self->first. ' '. $self->get('ship_last')
3952 : $self->contact_firstlast;
3957 Returns this customer's full country name
3963 code2country($self->country);
3966 =item geocode DATA_VENDOR
3968 Returns a value for the customer location as encoded by DATA_VENDOR.
3969 Currently this only makes sense for "CCH" as DATA_VENDOR.
3977 Returns a status string for this customer, currently:
3981 =item prospect - No packages have ever been ordered
3983 =item ordered - Recurring packages all are new (not yet billed).
3985 =item active - One or more recurring packages is active
3987 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3989 =item suspended - All non-cancelled recurring packages are suspended
3991 =item cancelled - All recurring packages are cancelled
3995 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3996 cust_main-status_module configuration option.
4000 sub status { shift->cust_status(@_); }
4004 for my $status ( FS::cust_main->statuses() ) {
4005 my $method = $status.'_sql';
4006 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4007 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4008 $sth->execute( ($self->custnum) x $numnum )
4009 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4010 return $status if $sth->fetchrow_arrayref->[0];
4014 =item ucfirst_cust_status
4016 =item ucfirst_status
4018 Returns the status with the first character capitalized.
4022 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4024 sub ucfirst_cust_status {
4026 ucfirst($self->cust_status);
4031 Returns a hex triplet color string for this customer's status.
4035 sub statuscolor { shift->cust_statuscolor(@_); }
4037 sub cust_statuscolor {
4039 __PACKAGE__->statuscolors->{$self->cust_status};
4044 Returns an array of hashes representing the customer's RT tickets.
4051 my $num = $conf->config('cust_main-max_tickets') || 10;
4054 if ( $conf->config('ticket_system') ) {
4055 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4057 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4061 foreach my $priority (
4062 $conf->config('ticket_system-custom_priority_field-values'), ''
4064 last if scalar(@tickets) >= $num;
4066 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4067 $num - scalar(@tickets),
4077 # Return services representing svc_accts in customer support packages
4078 sub support_services {
4080 my %packages = map { $_ => 1 } $conf->config('support_packages');
4082 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4083 grep { $_->part_svc->svcdb eq 'svc_acct' }
4084 map { $_->cust_svc }
4085 grep { exists $packages{ $_->pkgpart } }
4086 $self->ncancelled_pkgs;
4090 # Return a list of latitude/longitude for one of the services (if any)
4091 sub service_coordinates {
4095 grep { $_->latitude && $_->longitude }
4097 map { $_->cust_svc }
4098 $self->ncancelled_pkgs;
4100 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4105 Returns a masked version of the named field
4110 my ($self,$field) = @_;
4114 'x'x(length($self->getfield($field))-4).
4115 substr($self->getfield($field), (length($self->getfield($field))-4));
4121 =head1 CLASS METHODS
4127 Class method that returns the list of possible status strings for customers
4128 (see L<the status method|/status>). For example:
4130 @statuses = FS::cust_main->statuses();
4136 keys %{ $self->statuscolors };
4139 =item cust_status_sql
4141 Returns an SQL fragment to determine the status of a cust_main record, as a
4146 sub cust_status_sql {
4148 for my $status ( FS::cust_main->statuses() ) {
4149 my $method = $status.'_sql';
4150 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4159 Returns an SQL expression identifying prospective cust_main records (customers
4160 with no packages ever ordered)
4164 use vars qw($select_count_pkgs);
4165 $select_count_pkgs =
4166 "SELECT COUNT(*) FROM cust_pkg
4167 WHERE cust_pkg.custnum = cust_main.custnum";
4169 sub select_count_pkgs_sql {
4174 " 0 = ( $select_count_pkgs ) ";
4179 Returns an SQL expression identifying ordered cust_main records (customers with
4180 no active packages, but recurring packages not yet setup or one time charges
4186 FS::cust_main->none_active_sql.
4187 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4192 Returns an SQL expression identifying active cust_main records (customers with
4193 active recurring packages).
4198 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4201 =item none_active_sql
4203 Returns an SQL expression identifying cust_main records with no active
4204 recurring packages. This includes customers of status prospect, ordered,
4205 inactive, and suspended.
4209 sub none_active_sql {
4210 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4215 Returns an SQL expression identifying inactive cust_main records (customers with
4216 no active recurring packages, but otherwise unsuspended/uncancelled).
4221 FS::cust_main->none_active_sql.
4222 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4228 Returns an SQL expression identifying suspended cust_main records.
4233 sub suspended_sql { susp_sql(@_); }
4235 FS::cust_main->none_active_sql.
4236 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4242 Returns an SQL expression identifying cancelled cust_main records.
4246 sub cancel_sql { shift->cancelled_sql(@_); }
4249 =item uncancelled_sql
4251 Returns an SQL expression identifying un-cancelled cust_main records.
4255 sub uncancelled_sql { uncancel_sql(@_); }
4256 sub uncancel_sql { "
4257 ( 0 < ( $select_count_pkgs
4258 AND ( cust_pkg.cancel IS NULL
4259 OR cust_pkg.cancel = 0
4262 OR 0 = ( $select_count_pkgs )
4268 Returns an SQL fragment to retreive the balance.
4273 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4274 WHERE cust_bill.custnum = cust_main.custnum )
4275 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4276 WHERE cust_pay.custnum = cust_main.custnum )
4277 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4278 WHERE cust_credit.custnum = cust_main.custnum )
4279 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4280 WHERE cust_refund.custnum = cust_main.custnum )
4283 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4285 Returns an SQL fragment to retreive the balance for this customer, optionally
4286 considering invoices with date earlier than START_TIME, and not
4287 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4288 total_unapplied_payments).
4290 Times are specified as SQL fragments or numeric
4291 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4292 L<Date::Parse> for conversion functions. The empty string can be passed
4293 to disable that time constraint completely.
4295 Available options are:
4299 =item unapplied_date
4301 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)
4306 set to true to remove all customer comparison clauses, for totals
4311 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4316 JOIN clause (typically used with the total option)
4320 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4321 time will be ignored. Note that START_TIME and END_TIME only limit the date
4322 range for invoices and I<unapplied> payments, credits, and refunds.
4328 sub balance_date_sql {
4329 my( $class, $start, $end, %opt ) = @_;
4331 my $cutoff = $opt{'cutoff'};
4333 my $owed = FS::cust_bill->owed_sql($cutoff);
4334 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4335 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4336 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4338 my $j = $opt{'join'} || '';
4340 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4341 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4342 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4343 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4345 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4346 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4347 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4348 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4353 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4355 Returns an SQL fragment to retreive the total unapplied payments for this
4356 customer, only considering payments with date earlier than START_TIME, and
4357 optionally not later than END_TIME.
4359 Times are specified as SQL fragments or numeric
4360 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4361 L<Date::Parse> for conversion functions. The empty string can be passed
4362 to disable that time constraint completely.
4364 Available options are:
4368 sub unapplied_payments_date_sql {
4369 my( $class, $start, $end, %opt ) = @_;
4371 my $cutoff = $opt{'cutoff'};
4373 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4375 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4376 'unapplied_date'=>1 );
4378 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4381 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4383 Helper method for balance_date_sql; name (and usage) subject to change
4384 (suggestions welcome).
4386 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4387 cust_refund, cust_credit or cust_pay).
4389 If TABLE is "cust_bill" or the unapplied_date option is true, only
4390 considers records with date earlier than START_TIME, and optionally not
4391 later than END_TIME .
4395 sub _money_table_where {
4396 my( $class, $table, $start, $end, %opt ) = @_;
4399 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4400 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4401 push @where, "$table._date <= $start" if defined($start) && length($start);
4402 push @where, "$table._date > $end" if defined($end) && length($end);
4404 push @where, @{$opt{'where'}} if $opt{'where'};
4405 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4411 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4412 use FS::cust_main::Search;
4415 FS::cust_main::Search->search(@_);
4424 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4428 use FS::cust_main::Search;
4429 sub append_fuzzyfiles {
4430 #my( $first, $last, $company ) = @_;
4432 FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4434 use Fcntl qw(:flock);
4436 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4438 foreach my $field (@fuzzyfields) {
4443 open(CACHE,">>$dir/cust_main.$field")
4444 or die "can't open $dir/cust_main.$field: $!";
4445 flock(CACHE,LOCK_EX)
4446 or die "can't lock $dir/cust_main.$field: $!";
4448 print CACHE "$value\n";
4450 flock(CACHE,LOCK_UN)
4451 or die "can't unlock $dir/cust_main.$field: $!";
4466 #warn join('-',keys %$param);
4467 my $fh = $param->{filehandle};
4468 my $agentnum = $param->{agentnum};
4469 my $format = $param->{format};
4471 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4474 if ( $format eq 'simple' ) {
4475 @fields = qw( custnum agent_custid amount pkg );
4477 die "unknown format $format";
4480 eval "use Text::CSV_XS;";
4483 my $csv = new Text::CSV_XS;
4490 local $SIG{HUP} = 'IGNORE';
4491 local $SIG{INT} = 'IGNORE';
4492 local $SIG{QUIT} = 'IGNORE';
4493 local $SIG{TERM} = 'IGNORE';
4494 local $SIG{TSTP} = 'IGNORE';
4495 local $SIG{PIPE} = 'IGNORE';
4497 my $oldAutoCommit = $FS::UID::AutoCommit;
4498 local $FS::UID::AutoCommit = 0;
4501 #while ( $columns = $csv->getline($fh) ) {
4503 while ( defined($line=<$fh>) ) {
4505 $csv->parse($line) or do {
4506 $dbh->rollback if $oldAutoCommit;
4507 return "can't parse: ". $csv->error_input();
4510 my @columns = $csv->fields();
4511 #warn join('-',@columns);
4514 foreach my $field ( @fields ) {
4515 $row{$field} = shift @columns;
4518 if ( $row{custnum} && $row{agent_custid} ) {
4519 dbh->rollback if $oldAutoCommit;
4520 return "can't specify custnum with agent_custid $row{agent_custid}";
4524 if ( $row{agent_custid} && $agentnum ) {
4525 %hash = ( 'agent_custid' => $row{agent_custid},
4526 'agentnum' => $agentnum,
4530 if ( $row{custnum} ) {
4531 %hash = ( 'custnum' => $row{custnum} );
4534 unless ( scalar(keys %hash) ) {
4535 $dbh->rollback if $oldAutoCommit;
4536 return "can't find customer without custnum or agent_custid and agentnum";
4539 my $cust_main = qsearchs('cust_main', { %hash } );
4540 unless ( $cust_main ) {
4541 $dbh->rollback if $oldAutoCommit;
4542 my $custnum = $row{custnum} || $row{agent_custid};
4543 return "unknown custnum $custnum";
4546 if ( $row{'amount'} > 0 ) {
4547 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4549 $dbh->rollback if $oldAutoCommit;
4553 } elsif ( $row{'amount'} < 0 ) {
4554 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4557 $dbh->rollback if $oldAutoCommit;
4567 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4569 return "Empty file!" unless $imported;
4575 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4577 Deprecated. Use event notification and message templates
4578 (L<FS::msg_template>) instead.
4580 Sends a templated email notification to the customer (see L<Text::Template>).
4582 OPTIONS is a hash and may include
4584 I<from> - the email sender (default is invoice_from)
4586 I<to> - comma-separated scalar or arrayref of recipients
4587 (default is invoicing_list)
4589 I<subject> - The subject line of the sent email notification
4590 (default is "Notice from company_name")
4592 I<extra_fields> - a hashref of name/value pairs which will be substituted
4595 The following variables are vavailable in the template.
4597 I<$first> - the customer first name
4598 I<$last> - the customer last name
4599 I<$company> - the customer company
4600 I<$payby> - a description of the method of payment for the customer
4601 # would be nice to use FS::payby::shortname
4602 I<$payinfo> - the account information used to collect for this customer
4603 I<$expdate> - the expiration of the customer payment in seconds from epoch
4608 my ($self, $template, %options) = @_;
4610 return unless $conf->exists($template);
4612 my $from = $conf->config('invoice_from', $self->agentnum)
4613 if $conf->exists('invoice_from', $self->agentnum);
4614 $from = $options{from} if exists($options{from});
4616 my $to = join(',', $self->invoicing_list_emailonly);
4617 $to = $options{to} if exists($options{to});
4619 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4620 if $conf->exists('company_name', $self->agentnum);
4621 $subject = $options{subject} if exists($options{subject});
4623 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4624 SOURCE => [ map "$_\n",
4625 $conf->config($template)]
4627 or die "can't create new Text::Template object: Text::Template::ERROR";
4628 $notify_template->compile()
4629 or die "can't compile template: Text::Template::ERROR";
4631 $FS::notify_template::_template::company_name =
4632 $conf->config('company_name', $self->agentnum);
4633 $FS::notify_template::_template::company_address =
4634 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4636 my $paydate = $self->paydate || '2037-12-31';
4637 $FS::notify_template::_template::first = $self->first;
4638 $FS::notify_template::_template::last = $self->last;
4639 $FS::notify_template::_template::company = $self->company;
4640 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4641 my $payby = $self->payby;
4642 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4643 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4645 #credit cards expire at the end of the month/year of their exp date
4646 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4647 $FS::notify_template::_template::payby = 'credit card';
4648 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4649 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4651 }elsif ($payby eq 'COMP') {
4652 $FS::notify_template::_template::payby = 'complimentary account';
4654 $FS::notify_template::_template::payby = 'current method';
4656 $FS::notify_template::_template::expdate = $expire_time;
4658 for (keys %{$options{extra_fields}}){
4660 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4663 send_email(from => $from,
4665 subject => $subject,
4666 body => $notify_template->fill_in( PACKAGE =>
4667 'FS::notify_template::_template' ),
4672 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4674 Generates a templated notification to the customer (see L<Text::Template>).
4676 OPTIONS is a hash and may include
4678 I<extra_fields> - a hashref of name/value pairs which will be substituted
4679 into the template. These values may override values mentioned below
4680 and those from the customer record.
4682 The following variables are available in the template instead of or in addition
4683 to the fields of the customer record.
4685 I<$payby> - a description of the method of payment for the customer
4686 # would be nice to use FS::payby::shortname
4687 I<$payinfo> - the masked account information used to collect for this customer
4688 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4689 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4693 # a lot like cust_bill::print_latex
4694 sub generate_letter {
4695 my ($self, $template, %options) = @_;
4697 return unless $conf->exists($template);
4699 my $letter_template = new Text::Template
4701 SOURCE => [ map "$_\n", $conf->config($template)],
4702 DELIMITERS => [ '[@--', '--@]' ],
4704 or die "can't create new Text::Template object: Text::Template::ERROR";
4706 $letter_template->compile()
4707 or die "can't compile template: Text::Template::ERROR";
4709 my %letter_data = map { $_ => $self->$_ } $self->fields;
4710 $letter_data{payinfo} = $self->mask_payinfo;
4712 #my $paydate = $self->paydate || '2037-12-31';
4713 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4715 my $payby = $self->payby;
4716 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4717 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4719 #credit cards expire at the end of the month/year of their exp date
4720 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4721 $letter_data{payby} = 'credit card';
4722 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4723 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4725 }elsif ($payby eq 'COMP') {
4726 $letter_data{payby} = 'complimentary account';
4728 $letter_data{payby} = 'current method';
4730 $letter_data{expdate} = $expire_time;
4732 for (keys %{$options{extra_fields}}){
4733 $letter_data{$_} = $options{extra_fields}->{$_};
4736 unless(exists($letter_data{returnaddress})){
4737 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4738 $self->agent_template)
4740 if ( length($retadd) ) {
4741 $letter_data{returnaddress} = $retadd;
4742 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4743 $letter_data{returnaddress} =
4744 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4748 ( $conf->config('company_name', $self->agentnum),
4749 $conf->config('company_address', $self->agentnum),
4753 $letter_data{returnaddress} = '~';
4757 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4759 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4761 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4763 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4767 ) or die "can't open temp file: $!\n";
4768 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4769 or die "can't write temp file: $!\n";
4771 $letter_data{'logo_file'} = $lh->filename;
4773 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4777 ) or die "can't open temp file: $!\n";
4779 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4781 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4782 return ($1, $letter_data{'logo_file'});
4786 =item print_ps TEMPLATE
4788 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4794 my($file, $lfile) = $self->generate_letter(@_);
4795 my $ps = FS::Misc::generate_ps($file);
4796 unlink($file.'.tex');
4802 =item print TEMPLATE
4804 Prints the filled in template.
4806 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4810 sub queueable_print {
4813 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4814 or die "invalid customer number: " . $opt{custvnum};
4816 my $error = $self->print( $opt{template} );
4817 die $error if $error;
4821 my ($self, $template) = (shift, shift);
4822 do_print [ $self->print_ps($template) ];
4825 #these three subs should just go away once agent stuff is all config overrides
4827 sub agent_template {
4829 $self->_agent_plandata('agent_templatename');
4832 sub agent_invoice_from {
4834 $self->_agent_plandata('agent_invoice_from');
4837 sub _agent_plandata {
4838 my( $self, $option ) = @_;
4840 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4841 #agent-specific Conf
4843 use FS::part_event::Condition;
4845 my $agentnum = $self->agentnum;
4847 my $regexp = regexp_sql();
4849 my $part_event_option =
4851 'select' => 'part_event_option.*',
4852 'table' => 'part_event_option',
4854 LEFT JOIN part_event USING ( eventpart )
4855 LEFT JOIN part_event_option AS peo_agentnum
4856 ON ( part_event.eventpart = peo_agentnum.eventpart
4857 AND peo_agentnum.optionname = 'agentnum'
4858 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4860 LEFT JOIN part_event_condition
4861 ON ( part_event.eventpart = part_event_condition.eventpart
4862 AND part_event_condition.conditionname = 'cust_bill_age'
4864 LEFT JOIN part_event_condition_option
4865 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4866 AND part_event_condition_option.optionname = 'age'
4869 #'hashref' => { 'optionname' => $option },
4870 #'hashref' => { 'part_event_option.optionname' => $option },
4872 " WHERE part_event_option.optionname = ". dbh->quote($option).
4873 " AND action = 'cust_bill_send_agent' ".
4874 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4875 " AND peo_agentnum.optionname = 'agentnum' ".
4876 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4878 CASE WHEN part_event_condition_option.optionname IS NULL
4880 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4882 , part_event.weight".
4886 unless ( $part_event_option ) {
4887 return $self->agent->invoice_template || ''
4888 if $option eq 'agent_templatename';
4892 $part_event_option->optionvalue;
4896 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4898 Subroutine (not a method), designed to be called from the queue.
4900 Takes a list of options and values.
4902 Pulls up the customer record via the custnum option and calls bill_and_collect.
4907 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4909 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4910 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4912 $cust_main->bill_and_collect( %args );
4915 sub process_bill_and_collect {
4917 my $param = thaw(decode_base64(shift));
4918 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4919 or die "custnum '$param->{custnum}' not found!\n";
4920 $param->{'job'} = $job;
4921 $param->{'fatal'} = 1; # runs from job queue, will be caught
4922 $param->{'retry'} = 1;
4924 $cust_main->bill_and_collect( %$param );
4927 sub _upgrade_data { #class method
4928 my ($class, %opts) = @_;
4931 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4932 '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',
4934 # fix yyyy-m-dd formatted paydates
4935 if ( driver_name =~ /^mysql$/i ) {
4937 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4939 else { # the SQL standard
4941 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4944 foreach my $sql ( @statements ) {
4945 my $sth = dbh->prepare($sql) or die dbh->errstr;
4946 $sth->execute or die $sth->errstr;
4949 local($ignore_expired_card) = 1;
4950 local($ignore_illegal_zip) = 1;
4951 local($ignore_banned_card) = 1;
4952 local($skip_fuzzyfiles) = 1;
4953 $class->_upgrade_otaker(%opts);
4963 The delete method should possibly take an FS::cust_main object reference
4964 instead of a scalar customer number.
4966 Bill and collect options should probably be passed as references instead of a
4969 There should probably be a configuration file with a list of allowed credit
4972 No multiple currency support (probably a larger project than just this module).
4974 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4976 Birthdates rely on negative epoch values.
4978 The payby for card/check batches is broken. With mixed batching, bad
4981 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4985 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4986 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4987 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.