5 #FS::cust_main:_Marketgear when they're ready to move to 2.1
6 use base qw( FS::cust_main::Packages FS::cust_main::Status
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 use vars qw( $DEBUG $me $conf
16 $ignore_expired_card $ignore_illegal_zip $ignore_banned_card
17 $skip_fuzzyfiles @fuzzyfields
21 use Scalar::Util qw( blessed );
22 use Time::Local qw(timelocal);
23 use Storable qw(thaw);
27 use Digest::MD5 qw(md5_base64);
30 use File::Temp; #qw( tempfile );
31 use Business::CreditCard 0.28;
33 use FS::UID qw( getotaker dbh driver_name );
34 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
35 use FS::Misc qw( generate_email send_email generate_ps do_print );
36 use FS::Msgcat qw(gettext);
44 use FS::cust_pay_pending;
45 use FS::cust_pay_void;
46 use FS::cust_pay_batch;
49 use FS::part_referral;
50 use FS::cust_main_county;
51 use FS::cust_location;
53 use FS::cust_main_exemption;
54 use FS::cust_tax_adjustment;
55 use FS::cust_tax_location;
57 use FS::cust_main_invoice;
59 use FS::prepay_credit;
65 use FS::payment_gateway;
66 use FS::agent_payment_gateway;
68 use FS::cust_main_note;
69 use FS::cust_attachment;
73 # 1 is mostly method/subroutine entry and options
74 # 2 traces progress of some operations
75 # 3 is even more information including possibly sensitive data
77 $me = '[FS::cust_main]';
80 $ignore_expired_card = 0;
81 $ignore_illegal_zip = 0;
82 $ignore_banned_card = 0;
85 @fuzzyfields = ( 'first', 'last', 'company', 'address1' );
87 @encrypted_fields = ('payinfo', 'paycvv');
88 sub nohistory_fields { ('payinfo', 'paycvv'); }
90 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
92 #ask FS::UID to run this stuff for us later
93 #$FS::UID::callback{'FS::cust_main'} = sub {
94 install_callback FS::UID sub {
96 #yes, need it for stuff below (prolly should be cached)
101 my ( $hashref, $cache ) = @_;
102 if ( exists $hashref->{'pkgnum'} ) {
103 #@{ $self->{'_pkgnum'} } = ();
104 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
105 $self->{'_pkgnum'} = $subcache;
106 #push @{ $self->{'_pkgnum'} },
107 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
113 FS::cust_main - Object methods for cust_main records
119 $record = new FS::cust_main \%hash;
120 $record = new FS::cust_main { 'column' => 'value' };
122 $error = $record->insert;
124 $error = $new_record->replace($old_record);
126 $error = $record->delete;
128 $error = $record->check;
130 @cust_pkg = $record->all_pkgs;
132 @cust_pkg = $record->ncancelled_pkgs;
134 @cust_pkg = $record->suspended_pkgs;
136 $error = $record->bill;
137 $error = $record->bill %options;
138 $error = $record->bill 'time' => $time;
140 $error = $record->collect;
141 $error = $record->collect %options;
142 $error = $record->collect 'invoice_time' => $time,
147 An FS::cust_main object represents a customer. FS::cust_main inherits from
148 FS::Record. The following fields are currently supported:
154 Primary key (assigned automatically for new customers)
158 Agent (see L<FS::agent>)
162 Advertising source (see L<FS::part_referral>)
174 Cocial security number (optional)
190 (optional, see L<FS::cust_main_county>)
194 (see L<FS::cust_main_county>)
200 (see L<FS::cust_main_county>)
236 (optional, see L<FS::cust_main_county>)
240 (see L<FS::cust_main_county>)
246 (see L<FS::cust_main_county>)
262 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
266 Payment Information (See L<FS::payinfo_Mixin> for data format)
270 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
274 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
278 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
282 Start date month (maestro/solo cards only)
286 Start date year (maestro/solo cards only)
290 Issue number (maestro/solo cards only)
294 Name on card or billing name
298 IP address from which payment information was received
302 Tax exempt, empty or `Y'
306 Order taker (see L<FS::access_user>)
312 =item referral_custnum
314 Referring customer number
318 Enable individual CDR spooling, empty or `Y'
322 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
326 Discourage individual CDR printing, empty or `Y'
330 Allow self-service editing of ticket subjects, empty or 'Y'
340 Creates a new customer. To add the customer to the database, see L<"insert">.
342 Note that this stores the hash reference, not a distinct copy of the hash it
343 points to. You can ask the object for a copy with the I<hash> method.
347 sub table { 'cust_main'; }
349 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
351 Adds this customer to the database. If there is an error, returns the error,
352 otherwise returns false.
354 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
355 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
356 are inserted atomicly, or the transaction is rolled back. Passing an empty
357 hash reference is equivalent to not supplying this parameter. There should be
358 a better explanation of this, but until then, here's an example:
361 tie %hash, 'Tie::RefHash'; #this part is important
363 $cust_pkg => [ $svc_acct ],
366 $cust_main->insert( \%hash );
368 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
369 be set as the invoicing list (see L<"invoicing_list">). Errors return as
370 expected and rollback the entire transaction; it is not necessary to call
371 check_invoicing_list first. The invoicing_list is set after the records in the
372 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
373 invoicing_list destination to the newly-created svc_acct. Here's an example:
375 $cust_main->insert( {}, [ $email, 'POST' ] );
377 Currently available options are: I<depend_jobnum>, I<noexport>,
378 I<tax_exemption> and I<prospectnum>.
380 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
381 on the supplied jobnum (they will not run until the specific job completes).
382 This can be used to defer provisioning until some action completes (such
383 as running the customer's credit card successfully).
385 The I<noexport> option is deprecated. If I<noexport> is set true, no
386 provisioning jobs (exports) are scheduled. (You can schedule them later with
387 the B<reexport> method.)
389 The I<tax_exemption> option can be set to an arrayref of tax names.
390 FS::cust_main_exemption records will be created and inserted.
392 If I<prospectnum> is set, moves contacts and locations from that prospect.
398 my $cust_pkgs = @_ ? shift : {};
399 my $invoicing_list = @_ ? shift : '';
401 warn "$me insert called with options ".
402 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
405 local $SIG{HUP} = 'IGNORE';
406 local $SIG{INT} = 'IGNORE';
407 local $SIG{QUIT} = 'IGNORE';
408 local $SIG{TERM} = 'IGNORE';
409 local $SIG{TSTP} = 'IGNORE';
410 local $SIG{PIPE} = 'IGNORE';
412 my $oldAutoCommit = $FS::UID::AutoCommit;
413 local $FS::UID::AutoCommit = 0;
416 my $prepay_identifier = '';
417 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
419 if ( $self->payby eq 'PREPAY' ) {
421 $self->payby('BILL');
422 $prepay_identifier = $self->payinfo;
425 warn " looking up prepaid card $prepay_identifier\n"
428 my $error = $self->get_prepay( $prepay_identifier,
429 'amount_ref' => \$amount,
430 'seconds_ref' => \$seconds,
431 'upbytes_ref' => \$upbytes,
432 'downbytes_ref' => \$downbytes,
433 'totalbytes_ref' => \$totalbytes,
436 $dbh->rollback if $oldAutoCommit;
437 #return "error applying prepaid card (transaction rolled back): $error";
441 $payby = 'PREP' if $amount;
443 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
446 $self->payby('BILL');
447 $amount = $self->paid;
451 warn " inserting $self\n"
454 $self->signupdate(time) unless $self->signupdate;
456 $self->auto_agent_custid()
457 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
459 my $error = $self->SUPER::insert;
461 $dbh->rollback if $oldAutoCommit;
462 #return "inserting cust_main record (transaction rolled back): $error";
466 warn " setting invoicing list\n"
469 if ( $invoicing_list ) {
470 $error = $self->check_invoicing_list( $invoicing_list );
472 $dbh->rollback if $oldAutoCommit;
473 #return "checking invoicing_list (transaction rolled back): $error";
476 $self->invoicing_list( $invoicing_list );
479 warn " setting customer tags\n"
482 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
483 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
484 'custnum' => $self->custnum };
485 my $error = $cust_tag->insert;
487 $dbh->rollback if $oldAutoCommit;
492 my $prospectnum = delete $options{'prospectnum'};
493 if ( $prospectnum ) {
495 warn " moving contacts and locations from prospect $prospectnum\n"
499 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
500 unless ( $prospect_main ) {
501 $dbh->rollback if $oldAutoCommit;
502 return "Unknown prospectnum $prospectnum";
504 $prospect_main->custnum($self->custnum);
505 $prospect_main->disabled('Y');
506 my $error = $prospect_main->replace;
508 $dbh->rollback if $oldAutoCommit;
512 my @contact = $prospect_main->contact;
513 my @cust_location = $prospect_main->cust_location;
514 my @qual = $prospect_main->qual;
516 foreach my $r ( @contact, @cust_location, @qual ) {
518 $r->custnum($self->custnum);
519 my $error = $r->replace;
521 $dbh->rollback if $oldAutoCommit;
528 warn " setting cust_main_exemption\n"
531 my $tax_exemption = delete $options{'tax_exemption'};
532 if ( $tax_exemption ) {
533 foreach my $taxname ( @$tax_exemption ) {
534 my $cust_main_exemption = new FS::cust_main_exemption {
535 'custnum' => $self->custnum,
536 'taxname' => $taxname,
538 my $error = $cust_main_exemption->insert;
540 $dbh->rollback if $oldAutoCommit;
541 return "inserting cust_main_exemption (transaction rolled back): $error";
546 if ( $self->can('start_copy_skel') ) {
547 my $error = $self->start_copy_skel;
549 $dbh->rollback if $oldAutoCommit;
554 warn " ordering packages\n"
557 $error = $self->order_pkgs( $cust_pkgs,
559 'seconds_ref' => \$seconds,
560 'upbytes_ref' => \$upbytes,
561 'downbytes_ref' => \$downbytes,
562 'totalbytes_ref' => \$totalbytes,
565 $dbh->rollback if $oldAutoCommit;
570 $dbh->rollback if $oldAutoCommit;
571 return "No svc_acct record to apply pre-paid time";
573 if ( $upbytes || $downbytes || $totalbytes ) {
574 $dbh->rollback if $oldAutoCommit;
575 return "No svc_acct record to apply pre-paid data";
579 warn " inserting initial $payby payment of $amount\n"
581 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
583 $dbh->rollback if $oldAutoCommit;
584 return "inserting payment (transaction rolled back): $error";
588 unless ( $import || $skip_fuzzyfiles ) {
589 warn " queueing fuzzyfiles update\n"
591 $error = $self->queue_fuzzyfiles_update;
593 $dbh->rollback if $oldAutoCommit;
594 return "updating fuzzy search cache: $error";
599 warn " exporting\n" if $DEBUG > 1;
601 my $export_args = $options{'export_args'} || [];
604 map qsearch( 'part_export', {exportnum=>$_} ),
605 $conf->config('cust_main-exports'); #, $agentnum
607 foreach my $part_export ( @part_export ) {
608 my $error = $part_export->export_insert($self, @$export_args);
610 $dbh->rollback if $oldAutoCommit;
611 return "exporting to ". $part_export->exporttype.
612 " (transaction rolled back): $error";
616 #foreach my $depend_jobnum ( @$depend_jobnums ) {
617 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
619 # foreach my $jobnum ( @jobnums ) {
620 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
621 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
623 # my $error = $queue->depend_insert($depend_jobnum);
625 # $dbh->rollback if $oldAutoCommit;
626 # return "error queuing job dependancy: $error";
633 #if ( exists $options{'jobnums'} ) {
634 # push @{ $options{'jobnums'} }, @jobnums;
637 warn " insert complete; committing transaction\n"
640 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
645 use File::CounterFile;
646 sub auto_agent_custid {
649 my $format = $conf->config('cust_main-auto_agent_custid');
651 if ( $format eq '1YMMXXXXXXXX' ) {
653 my $counter = new File::CounterFile 'cust_main.agent_custid';
656 my $ym = 100000000000 + time2str('%y%m00000000', time);
657 if ( $ym > $counter->value ) {
658 $counter->{'value'} = $agent_custid = $ym;
659 $counter->{'updated'} = 1;
661 $agent_custid = $counter->inc;
667 die "Unknown cust_main-auto_agent_custid format: $format";
670 $self->agent_custid($agent_custid);
674 =item PACKAGE METHODS
676 Documentation on customer package methods has been moved to
677 L<FS::cust_main::Packages>.
679 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
681 Recharges this (existing) customer with the specified prepaid card (see
682 L<FS::prepay_credit>), specified either by I<identifier> or as an
683 FS::prepay_credit object. If there is an error, returns the error, otherwise
686 Optionally, five scalar references can be passed as well. They will have their
687 values filled in with the amount, number of seconds, and number of upload,
688 download, and total bytes applied by this prepaid card.
692 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
693 #the only place that uses these args
694 sub recharge_prepay {
695 my( $self, $prepay_credit, $amountref, $secondsref,
696 $upbytesref, $downbytesref, $totalbytesref ) = @_;
698 local $SIG{HUP} = 'IGNORE';
699 local $SIG{INT} = 'IGNORE';
700 local $SIG{QUIT} = 'IGNORE';
701 local $SIG{TERM} = 'IGNORE';
702 local $SIG{TSTP} = 'IGNORE';
703 local $SIG{PIPE} = 'IGNORE';
705 my $oldAutoCommit = $FS::UID::AutoCommit;
706 local $FS::UID::AutoCommit = 0;
709 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
711 my $error = $self->get_prepay( $prepay_credit,
712 'amount_ref' => \$amount,
713 'seconds_ref' => \$seconds,
714 'upbytes_ref' => \$upbytes,
715 'downbytes_ref' => \$downbytes,
716 'totalbytes_ref' => \$totalbytes,
718 || $self->increment_seconds($seconds)
719 || $self->increment_upbytes($upbytes)
720 || $self->increment_downbytes($downbytes)
721 || $self->increment_totalbytes($totalbytes)
722 || $self->insert_cust_pay_prepay( $amount,
724 ? $prepay_credit->identifier
729 $dbh->rollback if $oldAutoCommit;
733 if ( defined($amountref) ) { $$amountref = $amount; }
734 if ( defined($secondsref) ) { $$secondsref = $seconds; }
735 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
736 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
737 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
739 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
744 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
746 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
747 specified either by I<identifier> or as an FS::prepay_credit object.
749 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
750 incremented by the values of the prepaid card.
752 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
753 check or set this customer's I<agentnum>.
755 If there is an error, returns the error, otherwise returns false.
761 my( $self, $prepay_credit, %opt ) = @_;
763 local $SIG{HUP} = 'IGNORE';
764 local $SIG{INT} = 'IGNORE';
765 local $SIG{QUIT} = 'IGNORE';
766 local $SIG{TERM} = 'IGNORE';
767 local $SIG{TSTP} = 'IGNORE';
768 local $SIG{PIPE} = 'IGNORE';
770 my $oldAutoCommit = $FS::UID::AutoCommit;
771 local $FS::UID::AutoCommit = 0;
774 unless ( ref($prepay_credit) ) {
776 my $identifier = $prepay_credit;
778 $prepay_credit = qsearchs(
780 { 'identifier' => $identifier },
785 unless ( $prepay_credit ) {
786 $dbh->rollback if $oldAutoCommit;
787 return "Invalid prepaid card: ". $identifier;
792 if ( $prepay_credit->agentnum ) {
793 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
794 $dbh->rollback if $oldAutoCommit;
795 return "prepaid card not valid for agent ". $self->agentnum;
797 $self->agentnum($prepay_credit->agentnum);
800 my $error = $prepay_credit->delete;
802 $dbh->rollback if $oldAutoCommit;
803 return "removing prepay_credit (transaction rolled back): $error";
806 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
807 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
809 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
814 =item increment_upbytes SECONDS
816 Updates this customer's single or primary account (see L<FS::svc_acct>) by
817 the specified number of upbytes. If there is an error, returns the error,
818 otherwise returns false.
822 sub increment_upbytes {
823 _increment_column( shift, 'upbytes', @_);
826 =item increment_downbytes SECONDS
828 Updates this customer's single or primary account (see L<FS::svc_acct>) by
829 the specified number of downbytes. If there is an error, returns the error,
830 otherwise returns false.
834 sub increment_downbytes {
835 _increment_column( shift, 'downbytes', @_);
838 =item increment_totalbytes SECONDS
840 Updates this customer's single or primary account (see L<FS::svc_acct>) by
841 the specified number of totalbytes. If there is an error, returns the error,
842 otherwise returns false.
846 sub increment_totalbytes {
847 _increment_column( shift, 'totalbytes', @_);
850 =item increment_seconds SECONDS
852 Updates this customer's single or primary account (see L<FS::svc_acct>) by
853 the specified number of seconds. If there is an error, returns the error,
854 otherwise returns false.
858 sub increment_seconds {
859 _increment_column( shift, 'seconds', @_);
862 =item _increment_column AMOUNT
864 Updates this customer's single or primary account (see L<FS::svc_acct>) by
865 the specified number of seconds or bytes. If there is an error, returns
866 the error, otherwise returns false.
870 sub _increment_column {
871 my( $self, $column, $amount ) = @_;
872 warn "$me increment_column called: $column, $amount\n"
875 return '' unless $amount;
877 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
878 $self->ncancelled_pkgs;
881 return 'No packages with primary or single services found'.
882 ' to apply pre-paid time';
883 } elsif ( scalar(@cust_pkg) > 1 ) {
884 #maybe have a way to specify the package/account?
885 return 'Multiple packages found to apply pre-paid time';
888 my $cust_pkg = $cust_pkg[0];
889 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
893 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
896 return 'No account found to apply pre-paid time';
897 } elsif ( scalar(@cust_svc) > 1 ) {
898 return 'Multiple accounts found to apply pre-paid time';
901 my $svc_acct = $cust_svc[0]->svc_x;
902 warn " found service svcnum ". $svc_acct->pkgnum.
903 ' ('. $svc_acct->email. ")\n"
906 $column = "increment_$column";
907 $svc_acct->$column($amount);
911 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
913 Inserts a prepayment in the specified amount for this customer. An optional
914 second argument can specify the prepayment identifier for tracking purposes.
915 If there is an error, returns the error, otherwise returns false.
919 sub insert_cust_pay_prepay {
920 shift->insert_cust_pay('PREP', @_);
923 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
925 Inserts a cash payment in the specified amount for this customer. An optional
926 second argument can specify the payment identifier for tracking purposes.
927 If there is an error, returns the error, otherwise returns false.
931 sub insert_cust_pay_cash {
932 shift->insert_cust_pay('CASH', @_);
935 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
937 Inserts a Western Union payment in the specified amount for this customer. An
938 optional second argument can specify the prepayment identifier for tracking
939 purposes. If there is an error, returns the error, otherwise returns false.
943 sub insert_cust_pay_west {
944 shift->insert_cust_pay('WEST', @_);
947 sub insert_cust_pay {
948 my( $self, $payby, $amount ) = splice(@_, 0, 3);
949 my $payinfo = scalar(@_) ? shift : '';
951 my $cust_pay = new FS::cust_pay {
952 'custnum' => $self->custnum,
953 'paid' => sprintf('%.2f', $amount),
954 #'_date' => #date the prepaid card was purchased???
956 'payinfo' => $payinfo,
964 This method is deprecated. See the I<depend_jobnum> option to the insert and
965 order_pkgs methods for a better way to defer provisioning.
967 Re-schedules all exports by calling the B<reexport> method of all associated
968 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
969 otherwise returns false.
976 carp "WARNING: FS::cust_main::reexport is deprectated; ".
977 "use the depend_jobnum option to insert or order_pkgs to delay export";
979 local $SIG{HUP} = 'IGNORE';
980 local $SIG{INT} = 'IGNORE';
981 local $SIG{QUIT} = 'IGNORE';
982 local $SIG{TERM} = 'IGNORE';
983 local $SIG{TSTP} = 'IGNORE';
984 local $SIG{PIPE} = 'IGNORE';
986 my $oldAutoCommit = $FS::UID::AutoCommit;
987 local $FS::UID::AutoCommit = 0;
990 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
991 my $error = $cust_pkg->reexport;
993 $dbh->rollback if $oldAutoCommit;
998 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1003 =item delete [ OPTION => VALUE ... ]
1005 This deletes the customer. If there is an error, returns the error, otherwise
1008 This will completely remove all traces of the customer record. This is not
1009 what you want when a customer cancels service; for that, cancel all of the
1010 customer's packages (see L</cancel>).
1012 If the customer has any uncancelled packages, you need to pass a new (valid)
1013 customer number for those packages to be transferred to, as the "new_customer"
1014 option. Cancelled packages will be deleted. Did I mention that this is NOT
1015 what you want when a customer cancels service and that you really should be
1016 looking at L<FS::cust_pkg/cancel>?
1018 You can't delete a customer with invoices (see L<FS::cust_bill>),
1019 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1020 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1021 set the "delete_financials" option to a true value.
1026 my( $self, %opt ) = @_;
1028 local $SIG{HUP} = 'IGNORE';
1029 local $SIG{INT} = 'IGNORE';
1030 local $SIG{QUIT} = 'IGNORE';
1031 local $SIG{TERM} = 'IGNORE';
1032 local $SIG{TSTP} = 'IGNORE';
1033 local $SIG{PIPE} = 'IGNORE';
1035 my $oldAutoCommit = $FS::UID::AutoCommit;
1036 local $FS::UID::AutoCommit = 0;
1039 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1040 $dbh->rollback if $oldAutoCommit;
1041 return "Can't delete a master agent customer";
1044 #use FS::access_user
1045 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1046 $dbh->rollback if $oldAutoCommit;
1047 return "Can't delete a master employee customer";
1050 tie my %financial_tables, 'Tie::IxHash',
1051 'cust_bill' => 'invoices',
1052 'cust_statement' => 'statements',
1053 'cust_credit' => 'credits',
1054 'cust_pay' => 'payments',
1055 'cust_refund' => 'refunds',
1058 foreach my $table ( keys %financial_tables ) {
1060 my @records = $self->$table();
1062 if ( @records && ! $opt{'delete_financials'} ) {
1063 $dbh->rollback if $oldAutoCommit;
1064 return "Can't delete a customer with ". $financial_tables{$table};
1067 foreach my $record ( @records ) {
1068 my $error = $record->delete;
1070 $dbh->rollback if $oldAutoCommit;
1071 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1077 my @cust_pkg = $self->ncancelled_pkgs;
1079 my $new_custnum = $opt{'new_custnum'};
1080 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1081 $dbh->rollback if $oldAutoCommit;
1082 return "Invalid new customer number: $new_custnum";
1084 foreach my $cust_pkg ( @cust_pkg ) {
1085 my %hash = $cust_pkg->hash;
1086 $hash{'custnum'} = $new_custnum;
1087 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1088 my $error = $new_cust_pkg->replace($cust_pkg,
1089 options => { $cust_pkg->options },
1092 $dbh->rollback if $oldAutoCommit;
1097 my @cancelled_cust_pkg = $self->all_pkgs;
1098 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1099 my $error = $cust_pkg->delete;
1101 $dbh->rollback if $oldAutoCommit;
1106 #cust_tax_adjustment in financials?
1107 #cust_pay_pending? ouch
1109 foreach my $table (qw(
1110 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1111 cust_location cust_main_note cust_tax_adjustment
1112 cust_pay_void cust_pay_batch queue cust_tax_exempt
1114 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1115 my $error = $record->delete;
1117 $dbh->rollback if $oldAutoCommit;
1123 my $sth = $dbh->prepare(
1124 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1126 my $errstr = $dbh->errstr;
1127 $dbh->rollback if $oldAutoCommit;
1130 $sth->execute($self->custnum) or do {
1131 my $errstr = $sth->errstr;
1132 $dbh->rollback if $oldAutoCommit;
1138 my $ticket_dbh = '';
1139 if ($conf->config('ticket_system') eq 'RT_Internal') {
1141 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1142 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1143 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1144 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1147 if ( $ticket_dbh ) {
1149 my $ticket_sth = $ticket_dbh->prepare(
1150 'DELETE FROM Links WHERE Target = ?'
1152 my $errstr = $ticket_dbh->errstr;
1153 $dbh->rollback if $oldAutoCommit;
1156 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1158 my $errstr = $ticket_sth->errstr;
1159 $dbh->rollback if $oldAutoCommit;
1163 #check and see if the customer is the only link on the ticket, and
1164 #if so, set the ticket to deleted status in RT?
1165 #maybe someday, for now this will at least fix tickets not displaying
1169 #delete the customer record
1171 my $error = $self->SUPER::delete;
1173 $dbh->rollback if $oldAutoCommit;
1177 # cust_main exports!
1179 #my $export_args = $options{'export_args'} || [];
1182 map qsearch( 'part_export', {exportnum=>$_} ),
1183 $conf->config('cust_main-exports'); #, $agentnum
1185 foreach my $part_export ( @part_export ) {
1186 my $error = $part_export->export_delete( $self ); #, @$export_args);
1188 $dbh->rollback if $oldAutoCommit;
1189 return "exporting to ". $part_export->exporttype.
1190 " (transaction rolled back): $error";
1194 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1199 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1201 This merges this customer into the provided new custnum, and then deletes the
1202 customer. If there is an error, returns the error, otherwise returns false.
1204 The source customer's name, company name, phone numbers, agent,
1205 referring customer, customer class, advertising source, order taker, and
1206 billing information (except balance) are discarded.
1208 All packages are moved to the target customer. Packages with package locations
1209 are preserved. Packages without package locations are moved to a new package
1210 location with the source customer's service/shipping address.
1212 All invoices, statements, payments, credits and refunds are moved to the target
1213 customer. The source customer's balance is added to the target customer.
1215 All notes, attachments, tickets and customer tags are moved to the target
1218 Change history is not currently moved.
1223 my( $self, $new_custnum, %opt ) = @_;
1225 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1227 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1228 return "Invalid new customer number: $new_custnum";
1231 local $SIG{HUP} = 'IGNORE';
1232 local $SIG{INT} = 'IGNORE';
1233 local $SIG{QUIT} = 'IGNORE';
1234 local $SIG{TERM} = 'IGNORE';
1235 local $SIG{TSTP} = 'IGNORE';
1236 local $SIG{PIPE} = 'IGNORE';
1238 my $oldAutoCommit = $FS::UID::AutoCommit;
1239 local $FS::UID::AutoCommit = 0;
1242 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1243 $dbh->rollback if $oldAutoCommit;
1244 return "Can't merge a master agent customer";
1247 #use FS::access_user
1248 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1249 $dbh->rollback if $oldAutoCommit;
1250 return "Can't merge a master employee customer";
1253 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1254 'status' => { op=>'!=', value=>'done' },
1258 $dbh->rollback if $oldAutoCommit;
1259 return "Can't merge a customer with pending payments";
1262 tie my %financial_tables, 'Tie::IxHash',
1263 'cust_bill' => 'invoices',
1264 'cust_statement' => 'statements',
1265 'cust_credit' => 'credits',
1266 'cust_pay' => 'payments',
1267 'cust_pay_void' => 'voided payments',
1268 'cust_refund' => 'refunds',
1271 foreach my $table ( keys %financial_tables ) {
1273 my @records = $self->$table();
1275 foreach my $record ( @records ) {
1276 $record->custnum($new_custnum);
1277 my $error = $record->replace;
1279 $dbh->rollback if $oldAutoCommit;
1280 return "Error merging ". $financial_tables{$table}. ": $error\n";
1286 my $name = $self->ship_name;
1288 my $locationnum = '';
1289 foreach my $cust_pkg ( $self->all_pkgs ) {
1290 $cust_pkg->custnum($new_custnum);
1292 unless ( $cust_pkg->locationnum ) {
1293 unless ( $locationnum ) {
1294 my $cust_location = new FS::cust_location {
1295 $self->location_hash,
1296 'custnum' => $new_custnum,
1298 my $error = $cust_location->insert;
1300 $dbh->rollback if $oldAutoCommit;
1303 $locationnum = $cust_location->locationnum;
1305 $cust_pkg->locationnum($locationnum);
1308 my $error = $cust_pkg->replace;
1310 $dbh->rollback if $oldAutoCommit;
1314 # add customer (ship) name to svc_phone.phone_name if blank
1315 my @cust_svc = $cust_pkg->cust_svc;
1316 foreach my $cust_svc (@cust_svc) {
1317 my($label, $value, $svcdb) = $cust_svc->label;
1318 next unless $svcdb eq 'svc_phone';
1319 my $svc_phone = $cust_svc->svc_x;
1320 next if $svc_phone->phone_name;
1321 $svc_phone->phone_name($name);
1322 my $error = $svc_phone->replace;
1324 $dbh->rollback if $oldAutoCommit;
1332 # cust_tax_exempt (texas tax exemptions)
1333 # cust_recon (some sort of not-well understood thing for OnPac)
1335 #these are moved over
1336 foreach my $table (qw(
1337 cust_tag cust_location contact cust_attachment cust_main_note
1338 cust_tax_adjustment cust_pay_batch queue
1340 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1341 $record->custnum($new_custnum);
1342 my $error = $record->replace;
1344 $dbh->rollback if $oldAutoCommit;
1350 #these aren't preserved
1351 foreach my $table (qw(
1352 cust_main_exemption cust_main_invoice
1354 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1355 my $error = $record->delete;
1357 $dbh->rollback if $oldAutoCommit;
1364 my $sth = $dbh->prepare(
1365 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1367 my $errstr = $dbh->errstr;
1368 $dbh->rollback if $oldAutoCommit;
1371 $sth->execute($new_custnum, $self->custnum) or do {
1372 my $errstr = $sth->errstr;
1373 $dbh->rollback if $oldAutoCommit;
1379 my $ticket_dbh = '';
1380 if ($conf->config('ticket_system') eq 'RT_Internal') {
1382 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1383 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1384 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1385 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1388 if ( $ticket_dbh ) {
1390 my $ticket_sth = $ticket_dbh->prepare(
1391 'UPDATE Links SET Target = ? WHERE Target = ?'
1393 my $errstr = $ticket_dbh->errstr;
1394 $dbh->rollback if $oldAutoCommit;
1397 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1398 'freeside://freeside/cust_main/'.$self->custnum)
1400 my $errstr = $ticket_sth->errstr;
1401 $dbh->rollback if $oldAutoCommit;
1407 #delete the customer record
1409 my $error = $self->delete;
1411 $dbh->rollback if $oldAutoCommit;
1415 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1420 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1423 Replaces the OLD_RECORD with this one in the database. If there is an error,
1424 returns the error, otherwise returns false.
1426 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1427 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1428 expected and rollback the entire transaction; it is not necessary to call
1429 check_invoicing_list first. Here's an example:
1431 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1433 Currently available options are: I<tax_exemption>.
1435 The I<tax_exemption> option can be set to an arrayref of tax names.
1436 FS::cust_main_exemption records will be deleted and inserted as appropriate.
1443 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1445 : $self->replace_old;
1449 warn "$me replace called\n"
1452 my $curuser = $FS::CurrentUser::CurrentUser;
1453 if ( $self->payby eq 'COMP'
1454 && $self->payby ne $old->payby
1455 && ! $curuser->access_right('Complimentary customer')
1458 return "You are not permitted to create complimentary accounts.";
1461 if ( $old->get('geocode') && $old->get('geocode') eq $self->get('geocode')
1462 && $conf->exists('enable_taxproducts')
1465 my $pre = ($conf->exists('tax-ship_address') && $self->ship_zip)
1467 $self->set('geocode', '')
1468 if $old->get($pre.'zip') ne $self->get($pre.'zip')
1469 && length($self->get($pre.'zip')) >= 10;
1472 local($ignore_expired_card) = 1
1473 if $old->payby =~ /^(CARD|DCRD)$/
1474 && $self->payby =~ /^(CARD|DCRD)$/
1475 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1477 local($ignore_banned_card) = 1
1478 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1479 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1480 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1482 local $SIG{HUP} = 'IGNORE';
1483 local $SIG{INT} = 'IGNORE';
1484 local $SIG{QUIT} = 'IGNORE';
1485 local $SIG{TERM} = 'IGNORE';
1486 local $SIG{TSTP} = 'IGNORE';
1487 local $SIG{PIPE} = 'IGNORE';
1489 my $oldAutoCommit = $FS::UID::AutoCommit;
1490 local $FS::UID::AutoCommit = 0;
1493 my $error = $self->SUPER::replace($old);
1496 $dbh->rollback if $oldAutoCommit;
1500 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1501 my $invoicing_list = shift @param;
1502 $error = $self->check_invoicing_list( $invoicing_list );
1504 $dbh->rollback if $oldAutoCommit;
1507 $self->invoicing_list( $invoicing_list );
1510 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1512 #this could be more efficient than deleting and re-inserting, if it matters
1513 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1514 my $error = $cust_tag->delete;
1516 $dbh->rollback if $oldAutoCommit;
1520 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1521 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1522 'custnum' => $self->custnum };
1523 my $error = $cust_tag->insert;
1525 $dbh->rollback if $oldAutoCommit;
1532 my %options = @param;
1534 my $tax_exemption = delete $options{'tax_exemption'};
1535 if ( $tax_exemption ) {
1537 my %cust_main_exemption =
1538 map { $_->taxname => $_ }
1539 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1541 foreach my $taxname ( @$tax_exemption ) {
1543 next if delete $cust_main_exemption{$taxname};
1545 my $cust_main_exemption = new FS::cust_main_exemption {
1546 'custnum' => $self->custnum,
1547 'taxname' => $taxname,
1549 my $error = $cust_main_exemption->insert;
1551 $dbh->rollback if $oldAutoCommit;
1552 return "inserting cust_main_exemption (transaction rolled back): $error";
1556 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1557 my $error = $cust_main_exemption->delete;
1559 $dbh->rollback if $oldAutoCommit;
1560 return "deleting cust_main_exemption (transaction rolled back): $error";
1566 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1567 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1568 && $self->get('payinfo') !~ /^99\d{14}$/
1570 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1575 # card/check/lec info has changed, want to retry realtime_ invoice events
1576 my $error = $self->retry_realtime;
1578 $dbh->rollback if $oldAutoCommit;
1583 unless ( $import || $skip_fuzzyfiles ) {
1584 $error = $self->queue_fuzzyfiles_update;
1586 $dbh->rollback if $oldAutoCommit;
1587 return "updating fuzzy search cache: $error";
1591 # cust_main exports!
1593 my $export_args = $options{'export_args'} || [];
1596 map qsearch( 'part_export', {exportnum=>$_} ),
1597 $conf->config('cust_main-exports'); #, $agentnum
1599 foreach my $part_export ( @part_export ) {
1600 my $error = $part_export->export_replace( $self, $old, @$export_args);
1602 $dbh->rollback if $oldAutoCommit;
1603 return "exporting to ". $part_export->exporttype.
1604 " (transaction rolled back): $error";
1608 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1613 =item queue_fuzzyfiles_update
1615 Used by insert & replace to update the fuzzy search cache
1619 sub queue_fuzzyfiles_update {
1622 local $SIG{HUP} = 'IGNORE';
1623 local $SIG{INT} = 'IGNORE';
1624 local $SIG{QUIT} = 'IGNORE';
1625 local $SIG{TERM} = 'IGNORE';
1626 local $SIG{TSTP} = 'IGNORE';
1627 local $SIG{PIPE} = 'IGNORE';
1629 my $oldAutoCommit = $FS::UID::AutoCommit;
1630 local $FS::UID::AutoCommit = 0;
1633 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1634 my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1636 $dbh->rollback if $oldAutoCommit;
1637 return "queueing job (transaction rolled back): $error";
1640 if ( $self->ship_last ) {
1641 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1642 $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1644 $dbh->rollback if $oldAutoCommit;
1645 return "queueing job (transaction rolled back): $error";
1649 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1656 Checks all fields to make sure this is a valid customer record. If there is
1657 an error, returns the error, otherwise returns false. Called by the insert
1658 and replace methods.
1665 warn "$me check BEFORE: \n". $self->_dump
1669 $self->ut_numbern('custnum')
1670 || $self->ut_number('agentnum')
1671 || $self->ut_textn('agent_custid')
1672 || $self->ut_number('refnum')
1673 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1674 || $self->ut_textn('custbatch')
1675 || $self->ut_name('last')
1676 || $self->ut_name('first')
1677 || $self->ut_snumbern('birthdate')
1678 || $self->ut_snumbern('signupdate')
1679 || $self->ut_textn('company')
1680 || $self->ut_text('address1')
1681 || $self->ut_textn('address2')
1682 || $self->ut_text('city')
1683 || $self->ut_textn('county')
1684 || $self->ut_textn('state')
1685 || $self->ut_country('country')
1686 || $self->ut_anything('comments')
1687 || $self->ut_numbern('referral_custnum')
1688 || $self->ut_textn('stateid')
1689 || $self->ut_textn('stateid_state')
1690 || $self->ut_textn('invoice_terms')
1691 || $self->ut_alphan('geocode')
1692 || $self->ut_floatn('cdr_termination_percentage')
1693 || $self->ut_floatn('credit_limit')
1694 || $self->ut_numbern('billday')
1695 || $self->ut_enum('edit_subject', [ '', 'Y' ] )
1696 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1699 #barf. need message catalogs. i18n. etc.
1700 $error .= "Please select an advertising source."
1701 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1702 return $error if $error;
1704 return "Unknown agent"
1705 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1707 return "Unknown refnum"
1708 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1710 return "Unknown referring custnum: ". $self->referral_custnum
1711 unless ! $self->referral_custnum
1712 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1714 if ( $self->censustract ne '' ) {
1715 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1716 or return "Illegal census tract: ". $self->censustract;
1718 $self->censustract("$1.$2");
1721 if ( $self->ss eq '' ) {
1726 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1727 or return "Illegal social security number: ". $self->ss;
1728 $self->ss("$1-$2-$3");
1732 # bad idea to disable, causes billing to fail because of no tax rates later
1733 # except we don't fail any more
1734 unless ( $import ) {
1735 unless ( qsearch('cust_main_county', {
1736 'country' => $self->country,
1739 return "Unknown state/county/country: ".
1740 $self->state. "/". $self->county. "/". $self->country
1741 unless qsearch('cust_main_county',{
1742 'state' => $self->state,
1743 'county' => $self->county,
1744 'country' => $self->country,
1750 $self->ut_phonen('daytime', $self->country)
1751 || $self->ut_phonen('night', $self->country)
1752 || $self->ut_phonen('fax', $self->country)
1754 return $error if $error;
1756 unless ( $ignore_illegal_zip ) {
1757 $error = $self->ut_zip('zip', $self->country);
1758 return $error if $error;
1761 if ( $conf->exists('cust_main-require_phone')
1762 && ! length($self->daytime) && ! length($self->night)
1765 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1767 : FS::Msgcat::_gettext('daytime');
1768 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1770 : FS::Msgcat::_gettext('night');
1772 return "$daytime_label or $night_label is required"
1776 if ( $self->has_ship_address
1777 && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1778 $self->addr_fields )
1782 $self->ut_name('ship_last')
1783 || $self->ut_name('ship_first')
1784 || $self->ut_textn('ship_company')
1785 || $self->ut_text('ship_address1')
1786 || $self->ut_textn('ship_address2')
1787 || $self->ut_text('ship_city')
1788 || $self->ut_textn('ship_county')
1789 || $self->ut_textn('ship_state')
1790 || $self->ut_country('ship_country')
1792 return $error if $error;
1794 #false laziness with above
1795 unless ( qsearchs('cust_main_county', {
1796 'country' => $self->ship_country,
1799 return "Unknown ship_state/ship_county/ship_country: ".
1800 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1801 unless qsearch('cust_main_county',{
1802 'state' => $self->ship_state,
1803 'county' => $self->ship_county,
1804 'country' => $self->ship_country,
1810 $self->ut_phonen('ship_daytime', $self->ship_country)
1811 || $self->ut_phonen('ship_night', $self->ship_country)
1812 || $self->ut_phonen('ship_fax', $self->ship_country)
1814 return $error if $error;
1816 unless ( $ignore_illegal_zip ) {
1817 $error = $self->ut_zip('ship_zip', $self->ship_country);
1818 return $error if $error;
1820 return "Unit # is required."
1821 if $self->ship_address2 =~ /^\s*$/
1822 && $conf->exists('cust_main-require_address2');
1824 } else { # ship_ info eq billing info, so don't store dup info in database
1826 $self->setfield("ship_$_", '')
1827 foreach $self->addr_fields;
1829 return "Unit # is required."
1830 if $self->address2 =~ /^\s*$/
1831 && $conf->exists('cust_main-require_address2');
1835 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1836 # or return "Illegal payby: ". $self->payby;
1838 FS::payby->can_payby($self->table, $self->payby)
1839 or return "Illegal payby: ". $self->payby;
1841 $error = $self->ut_numbern('paystart_month')
1842 || $self->ut_numbern('paystart_year')
1843 || $self->ut_numbern('payissue')
1844 || $self->ut_textn('paytype')
1846 return $error if $error;
1848 if ( $self->payip eq '' ) {
1851 $error = $self->ut_ip('payip');
1852 return $error if $error;
1855 # If it is encrypted and the private key is not availaible then we can't
1856 # check the credit card.
1857 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1859 if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1861 my $payinfo = $self->payinfo;
1862 $payinfo =~ s/\D//g;
1863 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1864 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1866 $self->payinfo($payinfo);
1868 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1870 return gettext('unknown_card_type')
1871 if $self->payinfo !~ /^99\d{14}$/ #token
1872 && cardtype($self->payinfo) eq "Unknown";
1874 unless ( $ignore_banned_card ) {
1875 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1877 if ( $ban->bantype eq 'warn' ) {
1878 #or others depending on value of $ban->reason ?
1879 return '_duplicate_card'.
1880 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1881 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1882 ' (ban# '. $ban->bannum. ')'
1883 unless $self->override_ban_warn;
1885 return 'Banned credit card: banned on '.
1886 time2str('%a %h %o at %r', $ban->_date).
1887 ' by '. $ban->otaker.
1888 ' (ban# '. $ban->bannum. ')';
1893 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1894 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1895 $self->paycvv =~ /^(\d{4})$/
1896 or return "CVV2 (CID) for American Express cards is four digits.";
1899 $self->paycvv =~ /^(\d{3})$/
1900 or return "CVV2 (CVC2/CID) is three digits.";
1907 my $cardtype = cardtype($payinfo);
1908 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1910 return "Start date or issue number is required for $cardtype cards"
1911 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1913 return "Start month must be between 1 and 12"
1914 if $self->paystart_month
1915 and $self->paystart_month < 1 || $self->paystart_month > 12;
1917 return "Start year must be 1990 or later"
1918 if $self->paystart_year
1919 and $self->paystart_year < 1990;
1921 return "Issue number must be beween 1 and 99"
1923 and $self->payissue < 1 || $self->payissue > 99;
1926 $self->paystart_month('');
1927 $self->paystart_year('');
1928 $self->payissue('');
1931 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1933 my $payinfo = $self->payinfo;
1934 $payinfo =~ s/[^\d\@\.]//g;
1935 if ( $conf->exists('cust_main-require-bank-branch') ) {
1936 $payinfo =~ /^(\d+)\@(\d+)\.(\d+)$/ or return 'invalid echeck account@branch.bank';
1937 $payinfo = "$1\@$2.$3";
1938 } elsif ( $conf->exists('echeck-no_routing') ) {
1939 $payinfo =~ /^(\d+)\@(\d*)$/ or return 'invalid echeck account';
1940 $payinfo = "$1\@$2";
1941 } elsif ( $conf->exists('echeck-nonus') ) {
1942 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1943 $payinfo = "$1\@$2";
1945 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1946 $payinfo = "$1\@$2";
1948 $self->payinfo($payinfo);
1951 unless ( $ignore_banned_card ) {
1952 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1954 if ( $ban->bantype eq 'warn' ) {
1955 #or others depending on value of $ban->reason ?
1956 return '_duplicate_ach' unless $self->override_ban_warn;
1958 return 'Banned ACH account: banned on '.
1959 time2str('%a %h %o at %r', $ban->_date).
1960 ' by '. $ban->otaker.
1961 ' (ban# '. $ban->bannum. ')';
1966 } elsif ( $self->payby eq 'LECB' ) {
1968 my $payinfo = $self->payinfo;
1969 $payinfo =~ s/\D//g;
1970 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1972 $self->payinfo($payinfo);
1975 } elsif ( $self->payby eq 'BILL' ) {
1977 $error = $self->ut_textn('payinfo');
1978 return "Illegal P.O. number: ". $self->payinfo if $error;
1981 } elsif ( $self->payby eq 'COMP' ) {
1983 my $curuser = $FS::CurrentUser::CurrentUser;
1984 if ( ! $self->custnum
1985 && ! $curuser->access_right('Complimentary customer')
1988 return "You are not permitted to create complimentary accounts."
1991 $error = $self->ut_textn('payinfo');
1992 return "Illegal comp account issuer: ". $self->payinfo if $error;
1995 } elsif ( $self->payby eq 'PREPAY' ) {
1997 my $payinfo = $self->payinfo;
1998 $payinfo =~ s/\W//g; #anything else would just confuse things
1999 $self->payinfo($payinfo);
2000 $error = $self->ut_alpha('payinfo');
2001 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2002 return "Unknown prepayment identifier"
2003 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2008 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2009 return "Expiration date required"
2010 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
2014 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2015 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2016 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2017 ( $m, $y ) = ( $2, "19$1" );
2018 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2019 ( $m, $y ) = ( $3, "20$2" );
2021 return "Illegal expiration date: ". $self->paydate;
2023 $m = sprintf('%02d',$m);
2024 $self->paydate("$y-$m-01");
2025 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2026 return gettext('expired_card')
2028 && !$ignore_expired_card
2029 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2032 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2033 ( ! $conf->exists('require_cardname')
2034 || $self->payby !~ /^(CARD|DCRD)$/ )
2036 $self->payname( $self->first. " ". $self->getfield('last') );
2038 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
2039 or return gettext('illegal_name'). " payname: ". $self->payname;
2043 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2044 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2048 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2050 warn "$me check AFTER: \n". $self->_dump
2053 $self->SUPER::check;
2058 Returns a list of fields which have ship_ duplicates.
2063 qw( last first company
2064 address1 address2 city county state zip country
2069 =item has_ship_address
2071 Returns true if this customer record has a separate shipping address.
2075 sub has_ship_address {
2077 scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2082 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2083 city, county, state, zip, country, and geocode. The shipping address is used if present.
2089 Returns all locations (see L<FS::cust_location>) for this customer.
2095 qsearch('cust_location', { 'custnum' => $self->custnum } );
2100 Returns all contacts (see L<FS::contact>) for this customer.
2104 #already used :/ sub contact {
2107 qsearch('contact', { 'custnum' => $self->custnum } );
2112 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2113 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
2114 on success or a list of errors.
2120 grep { $_->unsuspend } $self->suspended_pkgs;
2125 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2127 Returns a list: an empty list on success or a list of errors.
2133 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2136 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2138 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2139 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2140 of a list of pkgparts; the hashref has the following keys:
2144 =item pkgparts - listref of pkgparts
2146 =item (other options are passed to the suspend method)
2151 Returns a list: an empty list on success or a list of errors.
2155 sub suspend_if_pkgpart {
2157 my (@pkgparts, %opt);
2158 if (ref($_[0]) eq 'HASH'){
2159 @pkgparts = @{$_[0]{pkgparts}};
2164 grep { $_->suspend(%opt) }
2165 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2166 $self->unsuspended_pkgs;
2169 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2171 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2172 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2173 instead of a list of pkgparts; the hashref has the following keys:
2177 =item pkgparts - listref of pkgparts
2179 =item (other options are passed to the suspend method)
2183 Returns a list: an empty list on success or a list of errors.
2187 sub suspend_unless_pkgpart {
2189 my (@pkgparts, %opt);
2190 if (ref($_[0]) eq 'HASH'){
2191 @pkgparts = @{$_[0]{pkgparts}};
2196 grep { $_->suspend(%opt) }
2197 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2198 $self->unsuspended_pkgs;
2201 =item cancel [ OPTION => VALUE ... ]
2203 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2205 Available options are:
2209 =item quiet - can be set true to supress email cancellation notices.
2211 =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.
2213 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2215 =item nobill - can be set true to skip billing if it might otherwise be done.
2219 Always returns a list: an empty list on success or a list of errors.
2223 # nb that dates are not specified as valid options to this method
2226 my( $self, %opt ) = @_;
2228 warn "$me cancel called on customer ". $self->custnum. " with options ".
2229 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2232 return ( 'access denied' )
2233 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2235 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2237 #should try decryption (we might have the private key)
2238 # and if not maybe queue a job for the server that does?
2239 return ( "Can't (yet) ban encrypted credit cards" )
2240 if $self->is_encrypted($self->payinfo);
2242 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2243 my $error = $ban->insert;
2244 return ( $error ) if $error;
2248 my @pkgs = $self->ncancelled_pkgs;
2250 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2252 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2253 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2257 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2258 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2261 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2264 sub _banned_pay_hashref {
2275 'payby' => $payby2ban{$self->payby},
2276 'payinfo' => $self->payinfo,
2277 #don't ever *search* on reason! #'reason' =>
2281 sub _new_banned_pay_hashref {
2283 my $hr = $self->_banned_pay_hashref;
2284 $hr->{payinfo} = md5_base64($hr->{payinfo});
2290 Returns all notes (see L<FS::cust_main_note>) for this customer.
2295 my($self,$orderby_classnum) = (shift,shift);
2296 my $orderby = "_DATE DESC";
2297 $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2298 qsearch( 'cust_main_note',
2299 { 'custnum' => $self->custnum },
2301 "ORDER BY $orderby",
2307 Returns the agent (see L<FS::agent>) for this customer.
2313 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2318 Returns the agent name (see L<FS::agent>) for this customer.
2324 $self->agent->agent;
2329 Returns any tags associated with this customer, as FS::cust_tag objects,
2330 or an empty list if there are no tags.
2336 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2341 Returns any tags associated with this customer, as FS::part_tag objects,
2342 or an empty list if there are no tags.
2348 map $_->part_tag, $self->cust_tag;
2354 Returns the customer class, as an FS::cust_class object, or the empty string
2355 if there is no customer class.
2361 if ( $self->classnum ) {
2362 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2370 Returns the customer category name, or the empty string if there is no customer
2377 my $cust_class = $self->cust_class;
2379 ? $cust_class->categoryname
2385 Returns the customer class name, or the empty string if there is no customer
2392 my $cust_class = $self->cust_class;
2394 ? $cust_class->classname
2398 =item BILLING METHODS
2400 Documentation on billing methods has been moved to
2401 L<FS::cust_main::Billing>.
2403 =item REALTIME BILLING METHODS
2405 Documentation on realtime billing methods has been moved to
2406 L<FS::cust_main::Billing_Realtime>.
2410 Removes the I<paycvv> field from the database directly.
2412 If there is an error, returns the error, otherwise returns false.
2418 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2419 or return dbh->errstr;
2420 $sth->execute($self->custnum)
2421 or return $sth->errstr;
2426 =item batch_card OPTION => VALUE...
2428 Adds a payment for this invoice to the pending credit card batch (see
2429 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2430 runs the payment using a realtime gateway.
2435 my ($self, %options) = @_;
2438 if (exists($options{amount})) {
2439 $amount = $options{amount};
2441 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2443 return '' unless $amount > 0;
2445 my $invnum = delete $options{invnum};
2446 my $payby = $options{payby} || $self->payby; #still dubious
2448 if ($options{'realtime'}) {
2449 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2455 my $oldAutoCommit = $FS::UID::AutoCommit;
2456 local $FS::UID::AutoCommit = 0;
2459 #this needs to handle mysql as well as Pg, like svc_acct.pm
2460 #(make it into a common function if folks need to do batching with mysql)
2461 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2462 or return "Cannot lock pay_batch: " . $dbh->errstr;
2466 'payby' => FS::payby->payby2payment($payby),
2469 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2471 unless ( $pay_batch ) {
2472 $pay_batch = new FS::pay_batch \%pay_batch;
2473 my $error = $pay_batch->insert;
2475 $dbh->rollback if $oldAutoCommit;
2476 die "error creating new batch: $error\n";
2480 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2481 'batchnum' => $pay_batch->batchnum,
2482 'custnum' => $self->custnum,
2485 foreach (qw( address1 address2 city state zip country payby payinfo paydate
2487 $options{$_} = '' unless exists($options{$_});
2490 my $cust_pay_batch = new FS::cust_pay_batch ( {
2491 'batchnum' => $pay_batch->batchnum,
2492 'invnum' => $invnum || 0, # is there a better value?
2493 # this field should be
2495 # cust_bill_pay_batch now
2496 'custnum' => $self->custnum,
2497 'last' => $self->getfield('last'),
2498 'first' => $self->getfield('first'),
2499 'address1' => $options{address1} || $self->address1,
2500 'address2' => $options{address2} || $self->address2,
2501 'city' => $options{city} || $self->city,
2502 'state' => $options{state} || $self->state,
2503 'zip' => $options{zip} || $self->zip,
2504 'country' => $options{country} || $self->country,
2505 'payby' => $options{payby} || $self->payby,
2506 'payinfo' => $options{payinfo} || $self->payinfo,
2507 'exp' => $options{paydate} || $self->paydate,
2508 'payname' => $options{payname} || $self->payname,
2509 'amount' => $amount, # consolidating
2512 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2513 if $old_cust_pay_batch;
2516 if ($old_cust_pay_batch) {
2517 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2519 $error = $cust_pay_batch->insert;
2523 $dbh->rollback if $oldAutoCommit;
2527 my $unapplied = $self->total_unapplied_credits
2528 + $self->total_unapplied_payments
2529 + $self->in_transit_payments;
2530 foreach my $cust_bill ($self->open_cust_bill) {
2531 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2532 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2533 'invnum' => $cust_bill->invnum,
2534 'paybatchnum' => $cust_pay_batch->paybatchnum,
2535 'amount' => $cust_bill->owed,
2538 if ($unapplied >= $cust_bill_pay_batch->amount){
2539 $unapplied -= $cust_bill_pay_batch->amount;
2542 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2543 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2545 $error = $cust_bill_pay_batch->insert;
2547 $dbh->rollback if $oldAutoCommit;
2552 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2558 Returns the total owed for this customer on all invoices
2559 (see L<FS::cust_bill/owed>).
2565 $self->total_owed_date(2145859200); #12/31/2037
2568 =item total_owed_date TIME
2570 Returns the total owed for this customer on all invoices with date earlier than
2571 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2572 see L<Time::Local> and L<Date::Parse> for conversion functions.
2576 sub total_owed_date {
2580 my $custnum = $self->custnum;
2582 my $owed_sql = FS::cust_bill->owed_sql;
2585 SELECT SUM($owed_sql) FROM cust_bill
2586 WHERE custnum = $custnum
2590 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2594 =item total_owed_pkgnum PKGNUM
2596 Returns the total owed on all invoices for this customer's specific package
2597 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2601 sub total_owed_pkgnum {
2602 my( $self, $pkgnum ) = @_;
2603 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2606 =item total_owed_date_pkgnum TIME PKGNUM
2608 Returns the total owed for this customer's specific package when using
2609 experimental package balances on all invoices with date earlier than
2610 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2611 see L<Time::Local> and L<Date::Parse> for conversion functions.
2615 sub total_owed_date_pkgnum {
2616 my( $self, $time, $pkgnum ) = @_;
2619 foreach my $cust_bill (
2620 grep { $_->_date <= $time }
2621 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2623 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2625 sprintf( "%.2f", $total_bill );
2631 Returns the total amount of all payments.
2638 $total += $_->paid foreach $self->cust_pay;
2639 sprintf( "%.2f", $total );
2642 =item total_unapplied_credits
2644 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2645 customer. See L<FS::cust_credit/credited>.
2647 =item total_credited
2649 Old name for total_unapplied_credits. Don't use.
2653 sub total_credited {
2654 #carp "total_credited deprecated, use total_unapplied_credits";
2655 shift->total_unapplied_credits(@_);
2658 sub total_unapplied_credits {
2661 my $custnum = $self->custnum;
2663 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2666 SELECT SUM($unapplied_sql) FROM cust_credit
2667 WHERE custnum = $custnum
2670 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2674 =item total_unapplied_credits_pkgnum PKGNUM
2676 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2677 customer. See L<FS::cust_credit/credited>.
2681 sub total_unapplied_credits_pkgnum {
2682 my( $self, $pkgnum ) = @_;
2683 my $total_credit = 0;
2684 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2685 sprintf( "%.2f", $total_credit );
2689 =item total_unapplied_payments
2691 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2692 See L<FS::cust_pay/unapplied>.
2696 sub total_unapplied_payments {
2699 my $custnum = $self->custnum;
2701 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2704 SELECT SUM($unapplied_sql) FROM cust_pay
2705 WHERE custnum = $custnum
2708 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2712 =item total_unapplied_payments_pkgnum PKGNUM
2714 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2715 specific package when using experimental package balances. See
2716 L<FS::cust_pay/unapplied>.
2720 sub total_unapplied_payments_pkgnum {
2721 my( $self, $pkgnum ) = @_;
2722 my $total_unapplied = 0;
2723 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2724 sprintf( "%.2f", $total_unapplied );
2728 =item total_unapplied_refunds
2730 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2731 customer. See L<FS::cust_refund/unapplied>.
2735 sub total_unapplied_refunds {
2737 my $custnum = $self->custnum;
2739 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2742 SELECT SUM($unapplied_sql) FROM cust_refund
2743 WHERE custnum = $custnum
2746 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2752 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2753 total_unapplied_credits minus total_unapplied_payments).
2759 $self->balance_date_range;
2762 =item balance_date TIME
2764 Returns the balance for this customer, only considering invoices with date
2765 earlier than TIME (total_owed_date minus total_credited minus
2766 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2767 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2774 $self->balance_date_range(shift);
2777 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2779 Returns the balance for this customer, optionally considering invoices with
2780 date earlier than START_TIME, and not later than END_TIME
2781 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2783 Times are specified as SQL fragments or numeric
2784 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2785 L<Date::Parse> for conversion functions. The empty string can be passed
2786 to disable that time constraint completely.
2788 Available options are:
2792 =item unapplied_date
2794 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)
2800 sub balance_date_range {
2802 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2803 ') FROM cust_main WHERE custnum='. $self->custnum;
2804 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2807 =item balance_pkgnum PKGNUM
2809 Returns the balance for this customer's specific package when using
2810 experimental package balances (total_owed plus total_unrefunded, minus
2811 total_unapplied_credits minus total_unapplied_payments)
2815 sub balance_pkgnum {
2816 my( $self, $pkgnum ) = @_;
2819 $self->total_owed_pkgnum($pkgnum)
2820 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2821 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2822 - $self->total_unapplied_credits_pkgnum($pkgnum)
2823 - $self->total_unapplied_payments_pkgnum($pkgnum)
2827 =item in_transit_payments
2829 Returns the total of requests for payments for this customer pending in
2830 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2834 sub in_transit_payments {
2836 my $in_transit_payments = 0;
2837 foreach my $pay_batch ( qsearch('pay_batch', {
2840 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2841 'batchnum' => $pay_batch->batchnum,
2842 'custnum' => $self->custnum,
2844 $in_transit_payments += $cust_pay_batch->amount;
2847 sprintf( "%.2f", $in_transit_payments );
2852 Returns a hash of useful information for making a payment.
2862 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2863 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2864 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2868 For credit card transactions:
2880 For electronic check transactions:
2895 $return{balance} = $self->balance;
2897 $return{payname} = $self->payname
2898 || ( $self->first. ' '. $self->get('last') );
2900 $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
2902 $return{payby} = $self->payby;
2903 $return{stateid_state} = $self->stateid_state;
2905 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2906 $return{card_type} = cardtype($self->payinfo);
2907 $return{payinfo} = $self->paymask;
2909 @return{'month', 'year'} = $self->paydate_monthyear;
2913 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2914 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2915 $return{payinfo1} = $payinfo1;
2916 $return{payinfo2} = $payinfo2;
2917 $return{paytype} = $self->paytype;
2918 $return{paystate} = $self->paystate;
2922 #doubleclick protection
2924 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2930 =item paydate_monthyear
2932 Returns a two-element list consisting of the month and year of this customer's
2933 paydate (credit card expiration date for CARD customers)
2937 sub paydate_monthyear {
2939 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2941 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2950 Returns the exact time in seconds corresponding to the payment method
2951 expiration date. For CARD/DCRD customers this is the end of the month;
2952 for others (COMP is the only other payby that uses paydate) it's the start.
2953 Returns 0 if the paydate is empty or set to the far future.
2959 my ($month, $year) = $self->paydate_monthyear;
2960 return 0 if !$year or $year >= 2037;
2961 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2963 if ( $month == 13 ) {
2967 return timelocal(0,0,0,1,$month-1,$year) - 1;
2970 return timelocal(0,0,0,1,$month-1,$year);
2974 =item paydate_epoch_sql
2976 Class method. Returns an SQL expression to obtain the payment expiration date
2977 as a number of seconds.
2981 # Special expiration date behavior for non-CARD/DCRD customers has been
2982 # carefully preserved. Do we really use that?
2983 sub paydate_epoch_sql {
2985 my $table = shift || 'cust_main';
2986 my ($case1, $case2);
2987 if ( driver_name eq 'Pg' ) {
2988 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2989 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2991 elsif ( lc(driver_name) eq 'mysql' ) {
2992 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2993 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2996 return "CASE WHEN $table.payby IN('CARD','DCRD')
3002 =item tax_exemption TAXNAME
3007 my( $self, $taxname ) = @_;
3009 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3010 'taxname' => $taxname,
3015 =item cust_main_exemption
3019 sub cust_main_exemption {
3021 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3024 =item invoicing_list [ ARRAYREF ]
3026 If an arguement is given, sets these email addresses as invoice recipients
3027 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3028 (except as warnings), so use check_invoicing_list first.
3030 Returns a list of email addresses (with svcnum entries expanded).
3032 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3033 check it without disturbing anything by passing nothing.
3035 This interface may change in the future.
3039 sub invoicing_list {
3040 my( $self, $arrayref ) = @_;
3043 my @cust_main_invoice;
3044 if ( $self->custnum ) {
3045 @cust_main_invoice =
3046 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3048 @cust_main_invoice = ();
3050 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3051 #warn $cust_main_invoice->destnum;
3052 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3053 #warn $cust_main_invoice->destnum;
3054 my $error = $cust_main_invoice->delete;
3055 warn $error if $error;
3058 if ( $self->custnum ) {
3059 @cust_main_invoice =
3060 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3062 @cust_main_invoice = ();
3064 my %seen = map { $_->address => 1 } @cust_main_invoice;
3065 foreach my $address ( @{$arrayref} ) {
3066 next if exists $seen{$address} && $seen{$address};
3067 $seen{$address} = 1;
3068 my $cust_main_invoice = new FS::cust_main_invoice ( {
3069 'custnum' => $self->custnum,
3072 my $error = $cust_main_invoice->insert;
3073 warn $error if $error;
3077 if ( $self->custnum ) {
3079 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3086 =item check_invoicing_list ARRAYREF
3088 Checks these arguements as valid input for the invoicing_list method. If there
3089 is an error, returns the error, otherwise returns false.
3093 sub check_invoicing_list {
3094 my( $self, $arrayref ) = @_;
3096 foreach my $address ( @$arrayref ) {
3098 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3099 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3102 my $cust_main_invoice = new FS::cust_main_invoice ( {
3103 'custnum' => $self->custnum,
3106 my $error = $self->custnum
3107 ? $cust_main_invoice->check
3108 : $cust_main_invoice->checkdest
3110 return $error if $error;
3114 return "Email address required"
3115 if $conf->exists('cust_main-require_invoicing_list_email')
3116 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3121 =item set_default_invoicing_list
3123 Sets the invoicing list to all accounts associated with this customer,
3124 overwriting any previous invoicing list.
3128 sub set_default_invoicing_list {
3130 $self->invoicing_list($self->all_emails);
3135 Returns the email addresses of all accounts provisioned for this customer.
3142 foreach my $cust_pkg ( $self->all_pkgs ) {
3143 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3145 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3146 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3148 $list{$_}=1 foreach map { $_->email } @svc_acct;
3153 =item invoicing_list_addpost
3155 Adds postal invoicing to this customer. If this customer is already configured
3156 to receive postal invoices, does nothing.
3160 sub invoicing_list_addpost {
3162 return if grep { $_ eq 'POST' } $self->invoicing_list;
3163 my @invoicing_list = $self->invoicing_list;
3164 push @invoicing_list, 'POST';
3165 $self->invoicing_list(\@invoicing_list);
3168 =item invoicing_list_emailonly
3170 Returns the list of email invoice recipients (invoicing_list without non-email
3171 destinations such as POST and FAX).
3175 sub invoicing_list_emailonly {
3177 warn "$me invoicing_list_emailonly called"
3179 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3182 =item invoicing_list_emailonly_scalar
3184 Returns the list of email invoice recipients (invoicing_list without non-email
3185 destinations such as POST and FAX) as a comma-separated scalar.
3189 sub invoicing_list_emailonly_scalar {
3191 warn "$me invoicing_list_emailonly_scalar called"
3193 join(', ', $self->invoicing_list_emailonly);
3196 =item referral_custnum_cust_main
3198 Returns the customer who referred this customer (or the empty string, if
3199 this customer was not referred).
3201 Note the difference with referral_cust_main method: This method,
3202 referral_custnum_cust_main returns the single customer (if any) who referred
3203 this customer, while referral_cust_main returns an array of customers referred
3208 sub referral_custnum_cust_main {
3210 return '' unless $self->referral_custnum;
3211 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3214 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3216 Returns an array of customers referred by this customer (referral_custnum set
3217 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3218 customers referred by customers referred by this customer and so on, inclusive.
3219 The default behavior is DEPTH 1 (no recursion).
3221 Note the difference with referral_custnum_cust_main method: This method,
3222 referral_cust_main, returns an array of customers referred BY this customer,
3223 while referral_custnum_cust_main returns the single customer (if any) who
3224 referred this customer.
3228 sub referral_cust_main {
3230 my $depth = @_ ? shift : 1;
3231 my $exclude = @_ ? shift : {};
3234 map { $exclude->{$_->custnum}++; $_; }
3235 grep { ! $exclude->{ $_->custnum } }
3236 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3240 map { $_->referral_cust_main($depth-1, $exclude) }
3247 =item referral_cust_main_ncancelled
3249 Same as referral_cust_main, except only returns customers with uncancelled
3254 sub referral_cust_main_ncancelled {
3256 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3259 =item referral_cust_pkg [ DEPTH ]
3261 Like referral_cust_main, except returns a flat list of all unsuspended (and
3262 uncancelled) packages for each customer. The number of items in this list may
3263 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3267 sub referral_cust_pkg {
3269 my $depth = @_ ? shift : 1;
3271 map { $_->unsuspended_pkgs }
3272 grep { $_->unsuspended_pkgs }
3273 $self->referral_cust_main($depth);
3276 =item referring_cust_main
3278 Returns the single cust_main record for the customer who referred this customer
3279 (referral_custnum), or false.
3283 sub referring_cust_main {
3285 return '' unless $self->referral_custnum;
3286 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3289 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3291 Applies a credit to this customer. If there is an error, returns the error,
3292 otherwise returns false.
3294 REASON can be a text string, an FS::reason object, or a scalar reference to
3295 a reasonnum. If a text string, it will be automatically inserted as a new
3296 reason, and a 'reason_type' option must be passed to indicate the
3297 FS::reason_type for the new reason.
3299 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3301 Any other options are passed to FS::cust_credit::insert.
3306 my( $self, $amount, $reason, %options ) = @_;
3308 my $cust_credit = new FS::cust_credit {
3309 'custnum' => $self->custnum,
3310 'amount' => $amount,
3313 if ( ref($reason) ) {
3315 if ( ref($reason) eq 'SCALAR' ) {
3316 $cust_credit->reasonnum( $$reason );
3318 $cust_credit->reasonnum( $reason->reasonnum );
3322 $cust_credit->set('reason', $reason)
3325 for (qw( addlinfo eventnum )) {
3326 $cust_credit->$_( delete $options{$_} )
3327 if exists($options{$_});
3330 $cust_credit->insert(%options);
3334 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3336 Creates a one-time charge for this customer. If there is an error, returns
3337 the error, otherwise returns false.
3339 New-style, with a hashref of options:
3341 my $error = $cust_main->charge(
3345 'start_date' => str2time('7/4/2009'),
3346 'pkg' => 'Description',
3347 'comment' => 'Comment',
3348 'additional' => [], #extra invoice detail
3349 'classnum' => 1, #pkg_class
3351 'setuptax' => '', # or 'Y' for tax exempt
3354 'taxclass' => 'Tax class',
3357 'taxproduct' => 2, #part_pkg_taxproduct
3358 'override' => {}, #XXX describe
3360 #will be filled in with the new object
3361 'cust_pkg_ref' => \$cust_pkg,
3363 #generate an invoice immediately
3365 'invoice_terms' => '', #with these terms
3371 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3377 my ( $amount, $quantity, $start_date, $classnum );
3378 my ( $pkg, $comment, $additional );
3379 my ( $setuptax, $taxclass ); #internal taxes
3380 my ( $taxproduct, $override ); #vendor (CCH) taxes
3382 my $cust_pkg_ref = '';
3383 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3384 if ( ref( $_[0] ) ) {
3385 $amount = $_[0]->{amount};
3386 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3387 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3388 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3389 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3390 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3391 : '$'. sprintf("%.2f",$amount);
3392 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3393 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3394 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3395 $additional = $_[0]->{additional} || [];
3396 $taxproduct = $_[0]->{taxproductnum};
3397 $override = { '' => $_[0]->{tax_override} };
3398 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3399 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3400 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3405 $pkg = @_ ? shift : 'One-time charge';
3406 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3408 $taxclass = @_ ? shift : '';
3412 local $SIG{HUP} = 'IGNORE';
3413 local $SIG{INT} = 'IGNORE';
3414 local $SIG{QUIT} = 'IGNORE';
3415 local $SIG{TERM} = 'IGNORE';
3416 local $SIG{TSTP} = 'IGNORE';
3417 local $SIG{PIPE} = 'IGNORE';
3419 my $oldAutoCommit = $FS::UID::AutoCommit;
3420 local $FS::UID::AutoCommit = 0;
3423 my $part_pkg = new FS::part_pkg ( {
3425 'comment' => $comment,
3429 'classnum' => ( $classnum ? $classnum : '' ),
3430 'setuptax' => $setuptax,
3431 'taxclass' => $taxclass,
3432 'taxproductnum' => $taxproduct,
3435 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3436 ( 0 .. @$additional - 1 )
3438 'additional_count' => scalar(@$additional),
3439 'setup_fee' => $amount,
3442 my $error = $part_pkg->insert( options => \%options,
3443 tax_overrides => $override,
3446 $dbh->rollback if $oldAutoCommit;
3450 my $pkgpart = $part_pkg->pkgpart;
3451 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3452 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3453 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3454 $error = $type_pkgs->insert;
3456 $dbh->rollback if $oldAutoCommit;
3461 my $cust_pkg = new FS::cust_pkg ( {
3462 'custnum' => $self->custnum,
3463 'pkgpart' => $pkgpart,
3464 'quantity' => $quantity,
3465 'start_date' => $start_date,
3466 'no_auto' => $no_auto,
3469 $error = $cust_pkg->insert;
3471 $dbh->rollback if $oldAutoCommit;
3473 } elsif ( $cust_pkg_ref ) {
3474 ${$cust_pkg_ref} = $cust_pkg;
3478 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3479 'pkg_list' => [ $cust_pkg ],
3482 $dbh->rollback if $oldAutoCommit;
3487 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3492 #=item charge_postal_fee
3494 #Applies a one time charge this customer. If there is an error,
3495 #returns the error, returns the cust_pkg charge object or false
3496 #if there was no charge.
3500 # This should be a customer event. For that to work requires that bill
3501 # also be a customer event.
3503 sub charge_postal_fee {
3506 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3507 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3509 my $cust_pkg = new FS::cust_pkg ( {
3510 'custnum' => $self->custnum,
3511 'pkgpart' => $pkgpart,
3515 my $error = $cust_pkg->insert;
3516 $error ? $error : $cust_pkg;
3519 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3521 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3523 Optionally, a list or hashref of additional arguments to the qsearch call can
3530 my $opt = ref($_[0]) ? shift : { @_ };
3532 #return $self->num_cust_bill unless wantarray || keys %$opt;
3534 $opt->{'table'} = 'cust_bill';
3535 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3536 $opt->{'hashref'}{'custnum'} = $self->custnum;
3537 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3539 map { $_ } #behavior of sort undefined in scalar context
3540 sort { $a->_date <=> $b->_date }
3544 =item open_cust_bill
3546 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3551 sub open_cust_bill {
3555 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3561 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3563 Returns all the statements (see L<FS::cust_statement>) for this customer.
3565 Optionally, a list or hashref of additional arguments to the qsearch call can
3570 sub cust_statement {
3572 my $opt = ref($_[0]) ? shift : { @_ };
3574 #return $self->num_cust_statement unless wantarray || keys %$opt;
3576 $opt->{'table'} = 'cust_statement';
3577 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3578 $opt->{'hashref'}{'custnum'} = $self->custnum;
3579 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3581 map { $_ } #behavior of sort undefined in scalar context
3582 sort { $a->_date <=> $b->_date }
3586 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3588 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3590 Optionally, a list or hashref of additional arguments to the qsearch call can
3591 be passed following the SVCDB.
3598 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3599 warn "$me svc_x requires a svcdb";
3602 my $opt = ref($_[0]) ? shift : { @_ };
3604 $opt->{'table'} = $svcdb;
3605 $opt->{'addl_from'} =
3606 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3607 ($opt->{'addl_from'} || '');
3609 my $custnum = $self->custnum;
3610 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3611 my $where = "cust_pkg.custnum = $custnum";
3613 my $extra_sql = $opt->{'extra_sql'} || '';
3614 if ( keys %{ $opt->{'hashref'} } ) {
3615 $extra_sql = " AND $where $extra_sql";
3618 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3619 $extra_sql = "WHERE $where AND $1";
3622 $extra_sql = "WHERE $where $extra_sql";
3625 $opt->{'extra_sql'} = $extra_sql;
3630 # required for use as an eventtable;
3633 $self->svc_x('svc_acct', @_);
3638 Returns all the credits (see L<FS::cust_credit>) for this customer.
3644 map { $_ } #return $self->num_cust_credit unless wantarray;
3645 sort { $a->_date <=> $b->_date }
3646 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3649 =item cust_credit_pkgnum
3651 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3652 package when using experimental package balances.
3656 sub cust_credit_pkgnum {
3657 my( $self, $pkgnum ) = @_;
3658 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3659 sort { $a->_date <=> $b->_date }
3660 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3661 'pkgnum' => $pkgnum,
3668 Returns all the payments (see L<FS::cust_pay>) for this customer.
3674 return $self->num_cust_pay unless wantarray;
3675 sort { $a->_date <=> $b->_date }
3676 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3681 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3682 called automatically when the cust_pay method is used in a scalar context.
3688 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3689 my $sth = dbh->prepare($sql) or die dbh->errstr;
3690 $sth->execute($self->custnum) or die $sth->errstr;
3691 $sth->fetchrow_arrayref->[0];
3694 =item cust_pay_pkgnum
3696 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3697 package when using experimental package balances.
3701 sub cust_pay_pkgnum {
3702 my( $self, $pkgnum ) = @_;
3703 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3704 sort { $a->_date <=> $b->_date }
3705 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3706 'pkgnum' => $pkgnum,
3713 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3719 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3720 sort { $a->_date <=> $b->_date }
3721 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3724 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3726 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3728 Optionally, a list or hashref of additional arguments to the qsearch call can
3733 sub cust_pay_batch {
3735 my $opt = ref($_[0]) ? shift : { @_ };
3737 #return $self->num_cust_statement unless wantarray || keys %$opt;
3739 $opt->{'table'} = 'cust_pay_batch';
3740 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3741 $opt->{'hashref'}{'custnum'} = $self->custnum;
3742 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3744 map { $_ } #behavior of sort undefined in scalar context
3745 sort { $a->paybatchnum <=> $b->paybatchnum }
3749 =item cust_pay_pending
3751 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3752 (without status "done").
3756 sub cust_pay_pending {
3758 return $self->num_cust_pay_pending unless wantarray;
3759 sort { $a->_date <=> $b->_date }
3760 qsearch( 'cust_pay_pending', {
3761 'custnum' => $self->custnum,
3762 'status' => { op=>'!=', value=>'done' },
3767 =item cust_pay_pending_attempt
3769 Returns all payment attempts / declined payments for this customer, as pending
3770 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3771 a corresponding payment (see L<FS::cust_pay>).
3775 sub cust_pay_pending_attempt {
3777 return $self->num_cust_pay_pending_attempt unless wantarray;
3778 sort { $a->_date <=> $b->_date }
3779 qsearch( 'cust_pay_pending', {
3780 'custnum' => $self->custnum,
3787 =item num_cust_pay_pending
3789 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3790 customer (without status "done"). Also called automatically when the
3791 cust_pay_pending method is used in a scalar context.
3795 sub num_cust_pay_pending {
3798 " SELECT COUNT(*) FROM cust_pay_pending ".
3799 " WHERE custnum = ? AND status != 'done' ",
3804 =item num_cust_pay_pending_attempt
3806 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3807 customer, with status "done" but without a corresp. Also called automatically when the
3808 cust_pay_pending method is used in a scalar context.
3812 sub num_cust_pay_pending_attempt {
3815 " SELECT COUNT(*) FROM cust_pay_pending ".
3816 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3823 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3829 map { $_ } #return $self->num_cust_refund unless wantarray;
3830 sort { $a->_date <=> $b->_date }
3831 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3834 =item display_custnum
3836 Returns the displayed customer number for this customer: agent_custid if
3837 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3841 sub display_custnum {
3843 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3844 return $self->agent_custid;
3846 return $self->custnum;
3852 Returns a name string for this customer, either "Company (Last, First)" or
3859 my $name = $self->contact;
3860 $name = $self->company. " ($name)" if $self->company;
3866 Returns a name string for this (service/shipping) contact, either
3867 "Company (Last, First)" or "Last, First".
3873 if ( $self->get('ship_last') ) {
3874 my $name = $self->ship_contact;
3875 $name = $self->ship_company. " ($name)" if $self->ship_company;
3884 Returns a name string for this customer, either "Company" or "First Last".
3890 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3893 =item ship_name_short
3895 Returns a name string for this (service/shipping) contact, either "Company"
3900 sub ship_name_short {
3902 if ( $self->get('ship_last') ) {
3903 $self->ship_company !~ /^\s*$/
3904 ? $self->ship_company
3905 : $self->ship_contact_firstlast;
3907 $self->name_company_or_firstlast;
3913 Returns this customer's full (billing) contact name only, "Last, First"
3919 $self->get('last'). ', '. $self->first;
3924 Returns this customer's full (shipping) contact name only, "Last, First"
3930 $self->get('ship_last')
3931 ? $self->get('ship_last'). ', '. $self->ship_first
3935 =item contact_firstlast
3937 Returns this customers full (billing) contact name only, "First Last".
3941 sub contact_firstlast {
3943 $self->first. ' '. $self->get('last');
3946 =item ship_contact_firstlast
3948 Returns this customer's full (shipping) contact name only, "First Last".
3952 sub ship_contact_firstlast {
3954 $self->get('ship_last')
3955 ? $self->first. ' '. $self->get('ship_last')
3956 : $self->contact_firstlast;
3961 Returns this customer's full country name
3967 code2country($self->country);
3970 =item geocode DATA_VENDOR
3972 Returns a value for the customer location as encoded by DATA_VENDOR.
3973 Currently this only makes sense for "CCH" as DATA_VENDOR.
3981 Returns a status string for this customer, currently:
3985 =item prospect - No packages have ever been ordered
3987 =item ordered - Recurring packages all are new (not yet billed).
3989 =item active - One or more recurring packages is active
3991 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3993 =item suspended - All non-cancelled recurring packages are suspended
3995 =item cancelled - All recurring packages are cancelled
3999 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4000 cust_main-status_module configuration option.
4004 sub status { shift->cust_status(@_); }
4008 for my $status ( FS::cust_main->statuses() ) {
4009 my $method = $status.'_sql';
4010 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4011 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4012 $sth->execute( ($self->custnum) x $numnum )
4013 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4014 return $status if $sth->fetchrow_arrayref->[0];
4018 =item ucfirst_cust_status
4020 =item ucfirst_status
4022 Returns the status with the first character capitalized.
4026 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4028 sub ucfirst_cust_status {
4030 ucfirst($self->cust_status);
4035 Returns a hex triplet color string for this customer's status.
4039 sub statuscolor { shift->cust_statuscolor(@_); }
4041 sub cust_statuscolor {
4043 __PACKAGE__->statuscolors->{$self->cust_status};
4048 Returns an array of hashes representing the customer's RT tickets.
4055 my $num = $conf->config('cust_main-max_tickets') || 10;
4058 if ( $conf->config('ticket_system') ) {
4059 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4061 @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
4065 foreach my $priority (
4066 $conf->config('ticket_system-custom_priority_field-values'), ''
4068 last if scalar(@tickets) >= $num;
4070 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4071 $num - scalar(@tickets),
4081 # Return services representing svc_accts in customer support packages
4082 sub support_services {
4084 my %packages = map { $_ => 1 } $conf->config('support_packages');
4086 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4087 grep { $_->part_svc->svcdb eq 'svc_acct' }
4088 map { $_->cust_svc }
4089 grep { exists $packages{ $_->pkgpart } }
4090 $self->ncancelled_pkgs;
4094 # Return a list of latitude/longitude for one of the services (if any)
4095 sub service_coordinates {
4099 grep { $_->latitude && $_->longitude }
4101 map { $_->cust_svc }
4102 $self->ncancelled_pkgs;
4104 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4109 Returns a masked version of the named field
4114 my ($self,$field) = @_;
4118 'x'x(length($self->getfield($field))-4).
4119 substr($self->getfield($field), (length($self->getfield($field))-4));
4125 =head1 CLASS METHODS
4131 Class method that returns the list of possible status strings for customers
4132 (see L<the status method|/status>). For example:
4134 @statuses = FS::cust_main->statuses();
4140 keys %{ $self->statuscolors };
4143 =item cust_status_sql
4145 Returns an SQL fragment to determine the status of a cust_main record, as a
4150 sub cust_status_sql {
4152 for my $status ( FS::cust_main->statuses() ) {
4153 my $method = $status.'_sql';
4154 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4163 Returns an SQL expression identifying prospective cust_main records (customers
4164 with no packages ever ordered)
4168 use vars qw($select_count_pkgs);
4169 $select_count_pkgs =
4170 "SELECT COUNT(*) FROM cust_pkg
4171 WHERE cust_pkg.custnum = cust_main.custnum";
4173 sub select_count_pkgs_sql {
4178 " 0 = ( $select_count_pkgs ) ";
4183 Returns an SQL expression identifying ordered cust_main records (customers with
4184 no active packages, but recurring packages not yet setup or one time charges
4190 FS::cust_main->none_active_sql.
4191 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4196 Returns an SQL expression identifying active cust_main records (customers with
4197 active recurring packages).
4202 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4205 =item none_active_sql
4207 Returns an SQL expression identifying cust_main records with no active
4208 recurring packages. This includes customers of status prospect, ordered,
4209 inactive, and suspended.
4213 sub none_active_sql {
4214 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4219 Returns an SQL expression identifying inactive cust_main records (customers with
4220 no active recurring packages, but otherwise unsuspended/uncancelled).
4225 FS::cust_main->none_active_sql.
4226 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4232 Returns an SQL expression identifying suspended cust_main records.
4237 sub suspended_sql { susp_sql(@_); }
4239 FS::cust_main->none_active_sql.
4240 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4246 Returns an SQL expression identifying cancelled cust_main records.
4250 sub cancel_sql { shift->cancelled_sql(@_); }
4253 =item uncancelled_sql
4255 Returns an SQL expression identifying un-cancelled cust_main records.
4259 sub uncancelled_sql { uncancel_sql(@_); }
4260 sub uncancel_sql { "
4261 ( 0 < ( $select_count_pkgs
4262 AND ( cust_pkg.cancel IS NULL
4263 OR cust_pkg.cancel = 0
4266 OR 0 = ( $select_count_pkgs )
4272 Returns an SQL fragment to retreive the balance.
4277 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4278 WHERE cust_bill.custnum = cust_main.custnum )
4279 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4280 WHERE cust_pay.custnum = cust_main.custnum )
4281 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4282 WHERE cust_credit.custnum = cust_main.custnum )
4283 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4284 WHERE cust_refund.custnum = cust_main.custnum )
4287 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4289 Returns an SQL fragment to retreive the balance for this customer, optionally
4290 considering invoices with date earlier than START_TIME, and not
4291 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4292 total_unapplied_payments).
4294 Times are specified as SQL fragments or numeric
4295 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4296 L<Date::Parse> for conversion functions. The empty string can be passed
4297 to disable that time constraint completely.
4299 Available options are:
4303 =item unapplied_date
4305 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)
4310 set to true to remove all customer comparison clauses, for totals
4315 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4320 JOIN clause (typically used with the total option)
4324 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4325 time will be ignored. Note that START_TIME and END_TIME only limit the date
4326 range for invoices and I<unapplied> payments, credits, and refunds.
4332 sub balance_date_sql {
4333 my( $class, $start, $end, %opt ) = @_;
4335 my $cutoff = $opt{'cutoff'};
4337 my $owed = FS::cust_bill->owed_sql($cutoff);
4338 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4339 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4340 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4342 my $j = $opt{'join'} || '';
4344 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4345 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4346 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4347 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4349 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4350 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4351 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4352 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4357 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4359 Returns an SQL fragment to retreive the total unapplied payments for this
4360 customer, only considering payments with date earlier than START_TIME, and
4361 optionally not later than END_TIME.
4363 Times are specified as SQL fragments or numeric
4364 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4365 L<Date::Parse> for conversion functions. The empty string can be passed
4366 to disable that time constraint completely.
4368 Available options are:
4372 sub unapplied_payments_date_sql {
4373 my( $class, $start, $end, %opt ) = @_;
4375 my $cutoff = $opt{'cutoff'};
4377 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4379 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4380 'unapplied_date'=>1 );
4382 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4385 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4387 Helper method for balance_date_sql; name (and usage) subject to change
4388 (suggestions welcome).
4390 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4391 cust_refund, cust_credit or cust_pay).
4393 If TABLE is "cust_bill" or the unapplied_date option is true, only
4394 considers records with date earlier than START_TIME, and optionally not
4395 later than END_TIME .
4399 sub _money_table_where {
4400 my( $class, $table, $start, $end, %opt ) = @_;
4403 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4404 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4405 push @where, "$table._date <= $start" if defined($start) && length($start);
4406 push @where, "$table._date > $end" if defined($end) && length($end);
4408 push @where, @{$opt{'where'}} if $opt{'where'};
4409 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4415 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4416 use FS::cust_main::Search;
4419 FS::cust_main::Search->search(@_);
4428 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4432 use FS::cust_main::Search;
4433 sub append_fuzzyfiles {
4434 #my( $first, $last, $company ) = @_;
4436 FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4438 use Fcntl qw(:flock);
4440 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4442 foreach my $field (@fuzzyfields) {
4447 open(CACHE,">>$dir/cust_main.$field")
4448 or die "can't open $dir/cust_main.$field: $!";
4449 flock(CACHE,LOCK_EX)
4450 or die "can't lock $dir/cust_main.$field: $!";
4452 print CACHE "$value\n";
4454 flock(CACHE,LOCK_UN)
4455 or die "can't unlock $dir/cust_main.$field: $!";
4470 #warn join('-',keys %$param);
4471 my $fh = $param->{filehandle};
4472 my $agentnum = $param->{agentnum};
4473 my $format = $param->{format};
4475 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4478 if ( $format eq 'simple' ) {
4479 @fields = qw( custnum agent_custid amount pkg );
4481 die "unknown format $format";
4484 eval "use Text::CSV_XS;";
4487 my $csv = new Text::CSV_XS;
4494 local $SIG{HUP} = 'IGNORE';
4495 local $SIG{INT} = 'IGNORE';
4496 local $SIG{QUIT} = 'IGNORE';
4497 local $SIG{TERM} = 'IGNORE';
4498 local $SIG{TSTP} = 'IGNORE';
4499 local $SIG{PIPE} = 'IGNORE';
4501 my $oldAutoCommit = $FS::UID::AutoCommit;
4502 local $FS::UID::AutoCommit = 0;
4505 #while ( $columns = $csv->getline($fh) ) {
4507 while ( defined($line=<$fh>) ) {
4509 $csv->parse($line) or do {
4510 $dbh->rollback if $oldAutoCommit;
4511 return "can't parse: ". $csv->error_input();
4514 my @columns = $csv->fields();
4515 #warn join('-',@columns);
4518 foreach my $field ( @fields ) {
4519 $row{$field} = shift @columns;
4522 if ( $row{custnum} && $row{agent_custid} ) {
4523 dbh->rollback if $oldAutoCommit;
4524 return "can't specify custnum with agent_custid $row{agent_custid}";
4528 if ( $row{agent_custid} && $agentnum ) {
4529 %hash = ( 'agent_custid' => $row{agent_custid},
4530 'agentnum' => $agentnum,
4534 if ( $row{custnum} ) {
4535 %hash = ( 'custnum' => $row{custnum} );
4538 unless ( scalar(keys %hash) ) {
4539 $dbh->rollback if $oldAutoCommit;
4540 return "can't find customer without custnum or agent_custid and agentnum";
4543 my $cust_main = qsearchs('cust_main', { %hash } );
4544 unless ( $cust_main ) {
4545 $dbh->rollback if $oldAutoCommit;
4546 my $custnum = $row{custnum} || $row{agent_custid};
4547 return "unknown custnum $custnum";
4550 if ( $row{'amount'} > 0 ) {
4551 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4553 $dbh->rollback if $oldAutoCommit;
4557 } elsif ( $row{'amount'} < 0 ) {
4558 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4561 $dbh->rollback if $oldAutoCommit;
4571 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4573 return "Empty file!" unless $imported;
4579 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4581 Deprecated. Use event notification and message templates
4582 (L<FS::msg_template>) instead.
4584 Sends a templated email notification to the customer (see L<Text::Template>).
4586 OPTIONS is a hash and may include
4588 I<from> - the email sender (default is invoice_from)
4590 I<to> - comma-separated scalar or arrayref of recipients
4591 (default is invoicing_list)
4593 I<subject> - The subject line of the sent email notification
4594 (default is "Notice from company_name")
4596 I<extra_fields> - a hashref of name/value pairs which will be substituted
4599 The following variables are vavailable in the template.
4601 I<$first> - the customer first name
4602 I<$last> - the customer last name
4603 I<$company> - the customer company
4604 I<$payby> - a description of the method of payment for the customer
4605 # would be nice to use FS::payby::shortname
4606 I<$payinfo> - the account information used to collect for this customer
4607 I<$expdate> - the expiration of the customer payment in seconds from epoch
4612 my ($self, $template, %options) = @_;
4614 return unless $conf->exists($template);
4616 my $from = $conf->config('invoice_from', $self->agentnum)
4617 if $conf->exists('invoice_from', $self->agentnum);
4618 $from = $options{from} if exists($options{from});
4620 my $to = join(',', $self->invoicing_list_emailonly);
4621 $to = $options{to} if exists($options{to});
4623 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4624 if $conf->exists('company_name', $self->agentnum);
4625 $subject = $options{subject} if exists($options{subject});
4627 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4628 SOURCE => [ map "$_\n",
4629 $conf->config($template)]
4631 or die "can't create new Text::Template object: Text::Template::ERROR";
4632 $notify_template->compile()
4633 or die "can't compile template: Text::Template::ERROR";
4635 $FS::notify_template::_template::company_name =
4636 $conf->config('company_name', $self->agentnum);
4637 $FS::notify_template::_template::company_address =
4638 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4640 my $paydate = $self->paydate || '2037-12-31';
4641 $FS::notify_template::_template::first = $self->first;
4642 $FS::notify_template::_template::last = $self->last;
4643 $FS::notify_template::_template::company = $self->company;
4644 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4645 my $payby = $self->payby;
4646 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4647 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4649 #credit cards expire at the end of the month/year of their exp date
4650 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4651 $FS::notify_template::_template::payby = 'credit card';
4652 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4653 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4655 }elsif ($payby eq 'COMP') {
4656 $FS::notify_template::_template::payby = 'complimentary account';
4658 $FS::notify_template::_template::payby = 'current method';
4660 $FS::notify_template::_template::expdate = $expire_time;
4662 for (keys %{$options{extra_fields}}){
4664 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4667 send_email(from => $from,
4669 subject => $subject,
4670 body => $notify_template->fill_in( PACKAGE =>
4671 'FS::notify_template::_template' ),
4676 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4678 Generates a templated notification to the customer (see L<Text::Template>).
4680 OPTIONS is a hash and may include
4682 I<extra_fields> - a hashref of name/value pairs which will be substituted
4683 into the template. These values may override values mentioned below
4684 and those from the customer record.
4686 The following variables are available in the template instead of or in addition
4687 to the fields of the customer record.
4689 I<$payby> - a description of the method of payment for the customer
4690 # would be nice to use FS::payby::shortname
4691 I<$payinfo> - the masked account information used to collect for this customer
4692 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4693 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4697 # a lot like cust_bill::print_latex
4698 sub generate_letter {
4699 my ($self, $template, %options) = @_;
4701 return unless $conf->exists($template);
4703 my $letter_template = new Text::Template
4705 SOURCE => [ map "$_\n", $conf->config($template)],
4706 DELIMITERS => [ '[@--', '--@]' ],
4708 or die "can't create new Text::Template object: Text::Template::ERROR";
4710 $letter_template->compile()
4711 or die "can't compile template: Text::Template::ERROR";
4713 my %letter_data = map { $_ => $self->$_ } $self->fields;
4714 $letter_data{payinfo} = $self->mask_payinfo;
4716 #my $paydate = $self->paydate || '2037-12-31';
4717 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4719 my $payby = $self->payby;
4720 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4721 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4723 #credit cards expire at the end of the month/year of their exp date
4724 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4725 $letter_data{payby} = 'credit card';
4726 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4727 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4729 }elsif ($payby eq 'COMP') {
4730 $letter_data{payby} = 'complimentary account';
4732 $letter_data{payby} = 'current method';
4734 $letter_data{expdate} = $expire_time;
4736 for (keys %{$options{extra_fields}}){
4737 $letter_data{$_} = $options{extra_fields}->{$_};
4740 unless(exists($letter_data{returnaddress})){
4741 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4742 $self->agent_template)
4744 if ( length($retadd) ) {
4745 $letter_data{returnaddress} = $retadd;
4746 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4747 $letter_data{returnaddress} =
4748 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4752 ( $conf->config('company_name', $self->agentnum),
4753 $conf->config('company_address', $self->agentnum),
4757 $letter_data{returnaddress} = '~';
4761 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4763 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4765 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4767 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4771 ) or die "can't open temp file: $!\n";
4772 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4773 or die "can't write temp file: $!\n";
4775 $letter_data{'logo_file'} = $lh->filename;
4777 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4781 ) or die "can't open temp file: $!\n";
4783 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4785 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4786 return ($1, $letter_data{'logo_file'});
4790 =item print_ps TEMPLATE
4792 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4798 my($file, $lfile) = $self->generate_letter(@_);
4799 my $ps = FS::Misc::generate_ps($file);
4800 unlink($file.'.tex');
4806 =item print TEMPLATE
4808 Prints the filled in template.
4810 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4814 sub queueable_print {
4817 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4818 or die "invalid customer number: " . $opt{custvnum};
4820 my $error = $self->print( $opt{template} );
4821 die $error if $error;
4825 my ($self, $template) = (shift, shift);
4826 do_print [ $self->print_ps($template) ];
4829 #these three subs should just go away once agent stuff is all config overrides
4831 sub agent_template {
4833 $self->_agent_plandata('agent_templatename');
4836 sub agent_invoice_from {
4838 $self->_agent_plandata('agent_invoice_from');
4841 sub _agent_plandata {
4842 my( $self, $option ) = @_;
4844 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4845 #agent-specific Conf
4847 use FS::part_event::Condition;
4849 my $agentnum = $self->agentnum;
4851 my $regexp = regexp_sql();
4853 my $part_event_option =
4855 'select' => 'part_event_option.*',
4856 'table' => 'part_event_option',
4858 LEFT JOIN part_event USING ( eventpart )
4859 LEFT JOIN part_event_option AS peo_agentnum
4860 ON ( part_event.eventpart = peo_agentnum.eventpart
4861 AND peo_agentnum.optionname = 'agentnum'
4862 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4864 LEFT JOIN part_event_condition
4865 ON ( part_event.eventpart = part_event_condition.eventpart
4866 AND part_event_condition.conditionname = 'cust_bill_age'
4868 LEFT JOIN part_event_condition_option
4869 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4870 AND part_event_condition_option.optionname = 'age'
4873 #'hashref' => { 'optionname' => $option },
4874 #'hashref' => { 'part_event_option.optionname' => $option },
4876 " WHERE part_event_option.optionname = ". dbh->quote($option).
4877 " AND action = 'cust_bill_send_agent' ".
4878 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4879 " AND peo_agentnum.optionname = 'agentnum' ".
4880 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4882 CASE WHEN part_event_condition_option.optionname IS NULL
4884 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4886 , part_event.weight".
4890 unless ( $part_event_option ) {
4891 return $self->agent->invoice_template || ''
4892 if $option eq 'agent_templatename';
4896 $part_event_option->optionvalue;
4900 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4902 Subroutine (not a method), designed to be called from the queue.
4904 Takes a list of options and values.
4906 Pulls up the customer record via the custnum option and calls bill_and_collect.
4911 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4913 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4914 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4916 $cust_main->bill_and_collect( %args );
4919 sub process_bill_and_collect {
4921 my $param = thaw(decode_base64(shift));
4922 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4923 or die "custnum '$param->{custnum}' not found!\n";
4924 $param->{'job'} = $job;
4925 $param->{'fatal'} = 1; # runs from job queue, will be caught
4926 $param->{'retry'} = 1;
4928 $cust_main->bill_and_collect( %$param );
4931 sub _upgrade_data { #class method
4932 my ($class, %opts) = @_;
4935 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4936 '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',
4938 # fix yyyy-m-dd formatted paydates
4939 if ( driver_name =~ /^mysql$/i ) {
4941 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4943 else { # the SQL standard
4945 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4948 foreach my $sql ( @statements ) {
4949 my $sth = dbh->prepare($sql) or die dbh->errstr;
4950 $sth->execute or die $sth->errstr;
4953 local($ignore_expired_card) = 1;
4954 local($ignore_illegal_zip) = 1;
4955 local($ignore_banned_card) = 1;
4956 local($skip_fuzzyfiles) = 1;
4957 $class->_upgrade_otaker(%opts);
4967 The delete method should possibly take an FS::cust_main object reference
4968 instead of a scalar customer number.
4970 Bill and collect options should probably be passed as references instead of a
4973 There should probably be a configuration file with a list of allowed credit
4976 No multiple currency support (probably a larger project than just this module).
4978 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4980 Birthdates rely on negative epoch values.
4982 The payby for card/check batches is broken. With mixed batching, bad
4985 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4989 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4990 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4991 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.