5 use base qw( FS::cust_main::Packages FS::cust_main::Status
6 FS::cust_main::NationalID
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
12 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
17 use vars qw( $DEBUG $me $conf $default_agent_custid $custnum_display_length
20 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
31 use Digest::MD5 qw(md5_base64);
34 use File::Temp; #qw( tempfile );
36 use Business::CreditCard 0.28;
38 use FS::UID qw( getotaker dbh driver_name );
39 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
40 use FS::Misc qw( generate_email send_email generate_ps do_print money_pretty card_types );
41 use FS::Msgcat qw(gettext);
48 use FS::cust_bill_void;
49 use FS::legacy_cust_bill;
51 use FS::cust_pay_pending;
52 use FS::cust_pay_void;
53 use FS::cust_pay_batch;
56 use FS::part_referral;
57 use FS::cust_main_county;
58 use FS::cust_location;
60 use FS::cust_main_exemption;
61 use FS::cust_tax_adjustment;
62 use FS::cust_tax_location;
64 use FS::cust_main_invoice;
66 use FS::prepay_credit;
72 use FS::payment_gateway;
73 use FS::agent_payment_gateway;
75 use FS::cust_main_note;
76 use FS::cust_attachment;
79 use FS::upgrade_journal;
83 # 1 is mostly method/subroutine entry and options
84 # 2 traces progress of some operations
85 # 3 is even more information including possibly sensitive data
87 $me = '[FS::cust_main]';
90 $ignore_expired_card = 0;
91 $ignore_banned_card = 0;
95 @encrypted_fields = ('payinfo', 'paycvv');
96 sub nohistory_fields { ('payinfo', 'paycvv'); }
98 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
100 #ask FS::UID to run this stuff for us later
101 #$FS::UID::callback{'FS::cust_main'} = sub {
102 install_callback FS::UID sub {
103 $conf = new FS::Conf;
104 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
105 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
110 my ( $hashref, $cache ) = @_;
111 if ( exists $hashref->{'pkgnum'} ) {
112 #@{ $self->{'_pkgnum'} } = ();
113 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
114 $self->{'_pkgnum'} = $subcache;
115 #push @{ $self->{'_pkgnum'} },
116 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
122 FS::cust_main - Object methods for cust_main records
128 $record = new FS::cust_main \%hash;
129 $record = new FS::cust_main { 'column' => 'value' };
131 $error = $record->insert;
133 $error = $new_record->replace($old_record);
135 $error = $record->delete;
137 $error = $record->check;
139 @cust_pkg = $record->all_pkgs;
141 @cust_pkg = $record->ncancelled_pkgs;
143 @cust_pkg = $record->suspended_pkgs;
145 $error = $record->bill;
146 $error = $record->bill %options;
147 $error = $record->bill 'time' => $time;
149 $error = $record->collect;
150 $error = $record->collect %options;
151 $error = $record->collect 'invoice_time' => $time,
156 An FS::cust_main object represents a customer. FS::cust_main inherits from
157 FS::Record. The following fields are currently supported:
163 Primary key (assigned automatically for new customers)
167 Agent (see L<FS::agent>)
171 Advertising source (see L<FS::part_referral>)
183 Cocial security number (optional)
207 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
211 Payment Information (See L<FS::payinfo_Mixin> for data format)
215 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
219 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
223 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
227 Start date month (maestro/solo cards only)
231 Start date year (maestro/solo cards only)
235 Issue number (maestro/solo cards only)
239 Name on card or billing name
243 IP address from which payment information was received
247 The credit card type (deduced from the card number).
251 Tax exempt, empty or `Y'
255 Order taker (see L<FS::access_user>)
261 =item referral_custnum
263 Referring customer number
267 Enable individual CDR spooling, empty or `Y'
271 A suggestion to events (see L<FS::part_bill_event>) to delay until this unix timestamp
275 Discourage individual CDR printing, empty or `Y'
279 Allow self-service editing of ticket subjects, empty or 'Y'
281 =item calling_list_exempt
283 Do not call, empty or 'Y'
285 =item invoice_ship_address
287 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
297 Creates a new customer. To add the customer to the database, see L<"insert">.
299 Note that this stores the hash reference, not a distinct copy of the hash it
300 points to. You can ask the object for a copy with the I<hash> method.
304 sub table { 'cust_main'; }
306 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
308 Adds this customer to the database. If there is an error, returns the error,
309 otherwise returns false.
311 Usually the customer's location will not yet exist in the database, and
312 the C<bill_location> and C<ship_location> pseudo-fields must be set to
313 uninserted L<FS::cust_location> objects. These will be inserted and linked
314 (in both directions) to the new customer record. If they're references
315 to the same object, they will become the same location.
317 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
318 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
319 are inserted atomicly, or the transaction is rolled back. Passing an empty
320 hash reference is equivalent to not supplying this parameter. There should be
321 a better explanation of this, but until then, here's an example:
324 tie %hash, 'Tie::RefHash'; #this part is important
326 $cust_pkg => [ $svc_acct ],
329 $cust_main->insert( \%hash );
331 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
332 be set as the invoicing list (see L<"invoicing_list">). Errors return as
333 expected and rollback the entire transaction; it is not necessary to call
334 check_invoicing_list first. The invoicing_list is set after the records in the
335 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
336 invoicing_list destination to the newly-created svc_acct. Here's an example:
338 $cust_main->insert( {}, [ $email, 'POST' ] );
340 Currently available options are: I<depend_jobnum>, I<noexport>,
341 I<tax_exemption> and I<prospectnum>.
343 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
344 on the supplied jobnum (they will not run until the specific job completes).
345 This can be used to defer provisioning until some action completes (such
346 as running the customer's credit card successfully).
348 The I<noexport> option is deprecated. If I<noexport> is set true, no
349 provisioning jobs (exports) are scheduled. (You can schedule them later with
350 the B<reexport> method.)
352 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
353 of tax names and exemption numbers. FS::cust_main_exemption records will be
354 created and inserted.
356 If I<prospectnum> is set, moves contacts and locations from that prospect.
362 my $cust_pkgs = @_ ? shift : {};
363 my $invoicing_list = @_ ? shift : '';
365 warn "$me insert called with options ".
366 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
369 local $SIG{HUP} = 'IGNORE';
370 local $SIG{INT} = 'IGNORE';
371 local $SIG{QUIT} = 'IGNORE';
372 local $SIG{TERM} = 'IGNORE';
373 local $SIG{TSTP} = 'IGNORE';
374 local $SIG{PIPE} = 'IGNORE';
376 my $oldAutoCommit = $FS::UID::AutoCommit;
377 local $FS::UID::AutoCommit = 0;
380 my $prepay_identifier = '';
381 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
383 if ( $self->payby eq 'PREPAY' ) {
385 $self->payby('BILL');
386 $prepay_identifier = $self->payinfo;
389 warn " looking up prepaid card $prepay_identifier\n"
392 my $error = $self->get_prepay( $prepay_identifier,
393 'amount_ref' => \$amount,
394 'seconds_ref' => \$seconds,
395 'upbytes_ref' => \$upbytes,
396 'downbytes_ref' => \$downbytes,
397 'totalbytes_ref' => \$totalbytes,
400 $dbh->rollback if $oldAutoCommit;
401 #return "error applying prepaid card (transaction rolled back): $error";
405 $payby = 'PREP' if $amount;
407 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
410 $self->payby('BILL');
411 $amount = $self->paid;
416 foreach my $l (qw(bill_location ship_location)) {
418 my $loc = delete $self->hashref->{$l} or return "$l not set";
420 if ( !$loc->locationnum ) {
421 # warn the location that we're going to insert it with no custnum
422 $loc->set(custnum_pending => 1);
423 warn " inserting $l\n"
425 my $error = $loc->insert;
427 $dbh->rollback if $oldAutoCommit;
428 my $label = $l eq 'ship_location' ? 'service' : 'billing';
429 return "$error (in $label location)";
432 } elsif ( $loc->prospectnum ) {
434 $loc->prospectnum('');
435 $loc->set(custnum_pending => 1);
436 my $error = $loc->replace;
438 $dbh->rollback if $oldAutoCommit;
439 my $label = $l eq 'ship_location' ? 'service' : 'billing';
440 return "$error (moving $label location)";
443 } elsif ( ($loc->custnum || 0) > 0 ) {
444 # then it somehow belongs to another customer--shouldn't happen
445 $dbh->rollback if $oldAutoCommit;
446 return "$l belongs to customer ".$loc->custnum;
448 # else it already belongs to this customer
449 # (happens when ship_location is identical to bill_location)
451 $self->set($l.'num', $loc->locationnum);
453 if ( $self->get($l.'num') eq '' ) {
454 $dbh->rollback if $oldAutoCommit;
459 warn " inserting $self\n"
462 $self->signupdate(time) unless $self->signupdate;
464 $self->auto_agent_custid()
465 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
467 my $error = $self->check_payinfo_cardtype
468 || $self->SUPER::insert;
470 $dbh->rollback if $oldAutoCommit;
471 #return "inserting cust_main record (transaction rolled back): $error";
475 # now set cust_location.custnum
476 foreach my $l (qw(bill_location ship_location)) {
477 warn " setting $l.custnum\n"
480 unless ( $loc->custnum ) {
481 $loc->set(custnum => $self->custnum);
482 $error ||= $loc->replace;
486 $dbh->rollback if $oldAutoCommit;
487 return "error setting $l custnum: $error";
491 warn " setting invoicing list\n"
494 if ( $invoicing_list ) {
495 $error = $self->check_invoicing_list( $invoicing_list );
497 $dbh->rollback if $oldAutoCommit;
498 #return "checking invoicing_list (transaction rolled back): $error";
501 $self->invoicing_list( $invoicing_list );
504 warn " setting customer tags\n"
507 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
508 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
509 'custnum' => $self->custnum };
510 my $error = $cust_tag->insert;
512 $dbh->rollback if $oldAutoCommit;
517 my $prospectnum = delete $options{'prospectnum'};
518 if ( $prospectnum ) {
520 warn " moving contacts and locations from prospect $prospectnum\n"
524 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
525 unless ( $prospect_main ) {
526 $dbh->rollback if $oldAutoCommit;
527 return "Unknown prospectnum $prospectnum";
529 $prospect_main->custnum($self->custnum);
530 $prospect_main->disabled('Y');
531 my $error = $prospect_main->replace;
533 $dbh->rollback if $oldAutoCommit;
537 my @contact = $prospect_main->contact;
538 my @cust_location = $prospect_main->cust_location;
539 my @qual = $prospect_main->qual;
541 foreach my $r ( @contact, @cust_location, @qual ) {
543 $r->custnum($self->custnum);
544 my $error = $r->replace;
546 $dbh->rollback if $oldAutoCommit;
553 # validate card (needs custnum already set)
554 if ( $self->payby =~ /^(CARD|DCRD)$/
555 && $conf->exists('business-onlinepayment-verification') ) {
556 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
558 $dbh->rollback if $oldAutoCommit;
563 warn " setting contacts\n"
566 if ( my $contact = delete $options{'contact'} ) {
568 foreach my $c ( @$contact ) {
569 $c->custnum($self->custnum);
570 my $error = $c->insert;
572 $dbh->rollback if $oldAutoCommit;
578 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
580 my $error = $self->process_o2m( 'table' => 'contact',
581 'fields' => FS::contact->cgi_contact_fields,
582 'params' => $contact_params,
585 $dbh->rollback if $oldAutoCommit;
590 warn " setting cust_main_exemption\n"
593 my $tax_exemption = delete $options{'tax_exemption'};
594 if ( $tax_exemption ) {
596 $tax_exemption = { map { $_ => '' } @$tax_exemption }
597 if ref($tax_exemption) eq 'ARRAY';
599 foreach my $taxname ( keys %$tax_exemption ) {
600 my $cust_main_exemption = new FS::cust_main_exemption {
601 'custnum' => $self->custnum,
602 'taxname' => $taxname,
603 'exempt_number' => $tax_exemption->{$taxname},
605 my $error = $cust_main_exemption->insert;
607 $dbh->rollback if $oldAutoCommit;
608 return "inserting cust_main_exemption (transaction rolled back): $error";
613 warn " ordering packages\n"
616 $error = $self->order_pkgs( $cust_pkgs,
618 'seconds_ref' => \$seconds,
619 'upbytes_ref' => \$upbytes,
620 'downbytes_ref' => \$downbytes,
621 'totalbytes_ref' => \$totalbytes,
624 $dbh->rollback if $oldAutoCommit;
629 $dbh->rollback if $oldAutoCommit;
630 return "No svc_acct record to apply pre-paid time";
632 if ( $upbytes || $downbytes || $totalbytes ) {
633 $dbh->rollback if $oldAutoCommit;
634 return "No svc_acct record to apply pre-paid data";
638 warn " inserting initial $payby payment of $amount\n"
640 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
642 $dbh->rollback if $oldAutoCommit;
643 return "inserting payment (transaction rolled back): $error";
647 unless ( $import || $skip_fuzzyfiles ) {
648 warn " queueing fuzzyfiles update\n"
650 $error = $self->queue_fuzzyfiles_update;
652 $dbh->rollback if $oldAutoCommit;
653 return "updating fuzzy search cache: $error";
657 # FS::geocode_Mixin::after_insert or something?
658 if ( $conf->config('tax_district_method') and !$import ) {
659 # if anything non-empty, try to look it up
660 my $queue = new FS::queue {
661 'job' => 'FS::geocode_Mixin::process_district_update',
662 'custnum' => $self->custnum,
664 my $error = $queue->insert( ref($self), $self->custnum );
666 $dbh->rollback if $oldAutoCommit;
667 return "queueing tax district update: $error";
672 warn " exporting\n" if $DEBUG > 1;
674 my $export_args = $options{'export_args'} || [];
677 map qsearch( 'part_export', {exportnum=>$_} ),
678 $conf->config('cust_main-exports'); #, $agentnum
680 foreach my $part_export ( @part_export ) {
681 my $error = $part_export->export_insert($self, @$export_args);
683 $dbh->rollback if $oldAutoCommit;
684 return "exporting to ". $part_export->exporttype.
685 " (transaction rolled back): $error";
689 #foreach my $depend_jobnum ( @$depend_jobnums ) {
690 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
692 # foreach my $jobnum ( @jobnums ) {
693 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
694 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
696 # my $error = $queue->depend_insert($depend_jobnum);
698 # $dbh->rollback if $oldAutoCommit;
699 # return "error queuing job dependancy: $error";
706 #if ( exists $options{'jobnums'} ) {
707 # push @{ $options{'jobnums'} }, @jobnums;
710 warn " insert complete; committing transaction\n"
713 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
718 use File::CounterFile;
719 sub auto_agent_custid {
722 my $format = $conf->config('cust_main-auto_agent_custid');
724 if ( $format eq '1YMMXXXXXXXX' ) {
726 my $counter = new File::CounterFile 'cust_main.agent_custid';
729 my $ym = 100000000000 + time2str('%y%m00000000', time);
730 if ( $ym > $counter->value ) {
731 $counter->{'value'} = $agent_custid = $ym;
732 $counter->{'updated'} = 1;
734 $agent_custid = $counter->inc;
740 die "Unknown cust_main-auto_agent_custid format: $format";
743 $self->agent_custid($agent_custid);
747 =item PACKAGE METHODS
749 Documentation on customer package methods has been moved to
750 L<FS::cust_main::Packages>.
752 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
754 Recharges this (existing) customer with the specified prepaid card (see
755 L<FS::prepay_credit>), specified either by I<identifier> or as an
756 FS::prepay_credit object. If there is an error, returns the error, otherwise
759 Optionally, five scalar references can be passed as well. They will have their
760 values filled in with the amount, number of seconds, and number of upload,
761 download, and total bytes applied by this prepaid card.
765 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
766 #the only place that uses these args
767 sub recharge_prepay {
768 my( $self, $prepay_credit, $amountref, $secondsref,
769 $upbytesref, $downbytesref, $totalbytesref ) = @_;
771 local $SIG{HUP} = 'IGNORE';
772 local $SIG{INT} = 'IGNORE';
773 local $SIG{QUIT} = 'IGNORE';
774 local $SIG{TERM} = 'IGNORE';
775 local $SIG{TSTP} = 'IGNORE';
776 local $SIG{PIPE} = 'IGNORE';
778 my $oldAutoCommit = $FS::UID::AutoCommit;
779 local $FS::UID::AutoCommit = 0;
782 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
784 my $error = $self->get_prepay( $prepay_credit,
785 'amount_ref' => \$amount,
786 'seconds_ref' => \$seconds,
787 'upbytes_ref' => \$upbytes,
788 'downbytes_ref' => \$downbytes,
789 'totalbytes_ref' => \$totalbytes,
791 || $self->increment_seconds($seconds)
792 || $self->increment_upbytes($upbytes)
793 || $self->increment_downbytes($downbytes)
794 || $self->increment_totalbytes($totalbytes)
795 || $self->insert_cust_pay_prepay( $amount,
797 ? $prepay_credit->identifier
802 $dbh->rollback if $oldAutoCommit;
806 if ( defined($amountref) ) { $$amountref = $amount; }
807 if ( defined($secondsref) ) { $$secondsref = $seconds; }
808 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
809 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
810 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
812 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
817 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
819 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
820 specified either by I<identifier> or as an FS::prepay_credit object.
822 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
823 incremented by the values of the prepaid card.
825 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
826 check or set this customer's I<agentnum>.
828 If there is an error, returns the error, otherwise returns false.
834 my( $self, $prepay_credit, %opt ) = @_;
836 local $SIG{HUP} = 'IGNORE';
837 local $SIG{INT} = 'IGNORE';
838 local $SIG{QUIT} = 'IGNORE';
839 local $SIG{TERM} = 'IGNORE';
840 local $SIG{TSTP} = 'IGNORE';
841 local $SIG{PIPE} = 'IGNORE';
843 my $oldAutoCommit = $FS::UID::AutoCommit;
844 local $FS::UID::AutoCommit = 0;
847 unless ( ref($prepay_credit) ) {
849 my $identifier = $prepay_credit;
851 $prepay_credit = qsearchs(
853 { 'identifier' => $identifier },
858 unless ( $prepay_credit ) {
859 $dbh->rollback if $oldAutoCommit;
860 return "Invalid prepaid card: ". $identifier;
865 if ( $prepay_credit->agentnum ) {
866 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
867 $dbh->rollback if $oldAutoCommit;
868 return "prepaid card not valid for agent ". $self->agentnum;
870 $self->agentnum($prepay_credit->agentnum);
873 my $error = $prepay_credit->delete;
875 $dbh->rollback if $oldAutoCommit;
876 return "removing prepay_credit (transaction rolled back): $error";
879 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
880 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
882 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
887 =item increment_upbytes SECONDS
889 Updates this customer's single or primary account (see L<FS::svc_acct>) by
890 the specified number of upbytes. If there is an error, returns the error,
891 otherwise returns false.
895 sub increment_upbytes {
896 _increment_column( shift, 'upbytes', @_);
899 =item increment_downbytes SECONDS
901 Updates this customer's single or primary account (see L<FS::svc_acct>) by
902 the specified number of downbytes. If there is an error, returns the error,
903 otherwise returns false.
907 sub increment_downbytes {
908 _increment_column( shift, 'downbytes', @_);
911 =item increment_totalbytes SECONDS
913 Updates this customer's single or primary account (see L<FS::svc_acct>) by
914 the specified number of totalbytes. If there is an error, returns the error,
915 otherwise returns false.
919 sub increment_totalbytes {
920 _increment_column( shift, 'totalbytes', @_);
923 =item increment_seconds SECONDS
925 Updates this customer's single or primary account (see L<FS::svc_acct>) by
926 the specified number of seconds. If there is an error, returns the error,
927 otherwise returns false.
931 sub increment_seconds {
932 _increment_column( shift, 'seconds', @_);
935 =item _increment_column AMOUNT
937 Updates this customer's single or primary account (see L<FS::svc_acct>) by
938 the specified number of seconds or bytes. If there is an error, returns
939 the error, otherwise returns false.
943 sub _increment_column {
944 my( $self, $column, $amount ) = @_;
945 warn "$me increment_column called: $column, $amount\n"
948 return '' unless $amount;
950 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
951 $self->ncancelled_pkgs;
954 return 'No packages with primary or single services found'.
955 ' to apply pre-paid time';
956 } elsif ( scalar(@cust_pkg) > 1 ) {
957 #maybe have a way to specify the package/account?
958 return 'Multiple packages found to apply pre-paid time';
961 my $cust_pkg = $cust_pkg[0];
962 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
966 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
969 return 'No account found to apply pre-paid time';
970 } elsif ( scalar(@cust_svc) > 1 ) {
971 return 'Multiple accounts found to apply pre-paid time';
974 my $svc_acct = $cust_svc[0]->svc_x;
975 warn " found service svcnum ". $svc_acct->pkgnum.
976 ' ('. $svc_acct->email. ")\n"
979 $column = "increment_$column";
980 $svc_acct->$column($amount);
984 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
986 Inserts a prepayment in the specified amount for this customer. An optional
987 second argument can specify the prepayment identifier for tracking purposes.
988 If there is an error, returns the error, otherwise returns false.
992 sub insert_cust_pay_prepay {
993 shift->insert_cust_pay('PREP', @_);
996 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
998 Inserts a cash payment in the specified amount for this customer. An optional
999 second argument can specify the payment identifier for tracking purposes.
1000 If there is an error, returns the error, otherwise returns false.
1004 sub insert_cust_pay_cash {
1005 shift->insert_cust_pay('CASH', @_);
1008 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1010 Inserts a Western Union payment in the specified amount for this customer. An
1011 optional second argument can specify the prepayment identifier for tracking
1012 purposes. If there is an error, returns the error, otherwise returns false.
1016 sub insert_cust_pay_west {
1017 shift->insert_cust_pay('WEST', @_);
1020 sub insert_cust_pay {
1021 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1022 my $payinfo = scalar(@_) ? shift : '';
1024 my $cust_pay = new FS::cust_pay {
1025 'custnum' => $self->custnum,
1026 'paid' => sprintf('%.2f', $amount),
1027 #'_date' => #date the prepaid card was purchased???
1029 'payinfo' => $payinfo,
1037 This method is deprecated. See the I<depend_jobnum> option to the insert and
1038 order_pkgs methods for a better way to defer provisioning.
1040 Re-schedules all exports by calling the B<reexport> method of all associated
1041 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
1042 otherwise returns false.
1049 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1050 "use the depend_jobnum option to insert or order_pkgs to delay export";
1052 local $SIG{HUP} = 'IGNORE';
1053 local $SIG{INT} = 'IGNORE';
1054 local $SIG{QUIT} = 'IGNORE';
1055 local $SIG{TERM} = 'IGNORE';
1056 local $SIG{TSTP} = 'IGNORE';
1057 local $SIG{PIPE} = 'IGNORE';
1059 my $oldAutoCommit = $FS::UID::AutoCommit;
1060 local $FS::UID::AutoCommit = 0;
1063 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1064 my $error = $cust_pkg->reexport;
1066 $dbh->rollback if $oldAutoCommit;
1071 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1076 =item delete [ OPTION => VALUE ... ]
1078 This deletes the customer. If there is an error, returns the error, otherwise
1081 This will completely remove all traces of the customer record. This is not
1082 what you want when a customer cancels service; for that, cancel all of the
1083 customer's packages (see L</cancel>).
1085 If the customer has any uncancelled packages, you need to pass a new (valid)
1086 customer number for those packages to be transferred to, as the "new_customer"
1087 option. Cancelled packages will be deleted. Did I mention that this is NOT
1088 what you want when a customer cancels service and that you really should be
1089 looking at L<FS::cust_pkg/cancel>?
1091 You can't delete a customer with invoices (see L<FS::cust_bill>),
1092 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1093 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1094 set the "delete_financials" option to a true value.
1099 my( $self, %opt ) = @_;
1101 local $SIG{HUP} = 'IGNORE';
1102 local $SIG{INT} = 'IGNORE';
1103 local $SIG{QUIT} = 'IGNORE';
1104 local $SIG{TERM} = 'IGNORE';
1105 local $SIG{TSTP} = 'IGNORE';
1106 local $SIG{PIPE} = 'IGNORE';
1108 my $oldAutoCommit = $FS::UID::AutoCommit;
1109 local $FS::UID::AutoCommit = 0;
1112 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1113 $dbh->rollback if $oldAutoCommit;
1114 return "Can't delete a master agent customer";
1117 #use FS::access_user
1118 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1119 $dbh->rollback if $oldAutoCommit;
1120 return "Can't delete a master employee customer";
1123 tie my %financial_tables, 'Tie::IxHash',
1124 'cust_bill' => 'invoices',
1125 'cust_statement' => 'statements',
1126 'cust_credit' => 'credits',
1127 'cust_pay' => 'payments',
1128 'cust_refund' => 'refunds',
1131 foreach my $table ( keys %financial_tables ) {
1133 my @records = $self->$table();
1135 if ( @records && ! $opt{'delete_financials'} ) {
1136 $dbh->rollback if $oldAutoCommit;
1137 return "Can't delete a customer with ". $financial_tables{$table};
1140 foreach my $record ( @records ) {
1141 my $error = $record->delete;
1143 $dbh->rollback if $oldAutoCommit;
1144 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1150 my @cust_pkg = $self->ncancelled_pkgs;
1152 my $new_custnum = $opt{'new_custnum'};
1153 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1154 $dbh->rollback if $oldAutoCommit;
1155 return "Invalid new customer number: $new_custnum";
1157 foreach my $cust_pkg ( @cust_pkg ) {
1158 my %hash = $cust_pkg->hash;
1159 $hash{'custnum'} = $new_custnum;
1160 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1161 my $error = $new_cust_pkg->replace($cust_pkg,
1162 options => { $cust_pkg->options },
1165 $dbh->rollback if $oldAutoCommit;
1170 my @cancelled_cust_pkg = $self->all_pkgs;
1171 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1172 my $error = $cust_pkg->delete;
1174 $dbh->rollback if $oldAutoCommit;
1179 #cust_tax_adjustment in financials?
1180 #cust_pay_pending? ouch
1182 foreach my $table (qw(
1183 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1184 cust_location cust_main_note cust_tax_adjustment
1185 cust_pay_void cust_pay_batch queue cust_tax_exempt
1187 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1188 my $error = $record->delete;
1190 $dbh->rollback if $oldAutoCommit;
1196 my $sth = $dbh->prepare(
1197 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1199 my $errstr = $dbh->errstr;
1200 $dbh->rollback if $oldAutoCommit;
1203 $sth->execute($self->custnum) or do {
1204 my $errstr = $sth->errstr;
1205 $dbh->rollback if $oldAutoCommit;
1211 my $ticket_dbh = '';
1212 if ($conf->config('ticket_system') eq 'RT_Internal') {
1214 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1215 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1216 $ticket_dbh = FS::DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1217 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1220 if ( $ticket_dbh ) {
1222 my $ticket_sth = $ticket_dbh->prepare(
1223 'DELETE FROM Links WHERE Target = ?'
1225 my $errstr = $ticket_dbh->errstr;
1226 $dbh->rollback if $oldAutoCommit;
1229 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1231 my $errstr = $ticket_sth->errstr;
1232 $dbh->rollback if $oldAutoCommit;
1236 #check and see if the customer is the only link on the ticket, and
1237 #if so, set the ticket to deleted status in RT?
1238 #maybe someday, for now this will at least fix tickets not displaying
1242 #delete the customer record
1244 my $error = $self->SUPER::delete;
1246 $dbh->rollback if $oldAutoCommit;
1250 # cust_main exports!
1252 #my $export_args = $options{'export_args'} || [];
1255 map qsearch( 'part_export', {exportnum=>$_} ),
1256 $conf->config('cust_main-exports'); #, $agentnum
1258 foreach my $part_export ( @part_export ) {
1259 my $error = $part_export->export_delete( $self ); #, @$export_args);
1261 $dbh->rollback if $oldAutoCommit;
1262 return "exporting to ". $part_export->exporttype.
1263 " (transaction rolled back): $error";
1267 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1272 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1274 This merges this customer into the provided new custnum, and then deletes the
1275 customer. If there is an error, returns the error, otherwise returns false.
1277 The source customer's name, company name, phone numbers, agent,
1278 referring customer, customer class, advertising source, order taker, and
1279 billing information (except balance) are discarded.
1281 All packages are moved to the target customer. Packages with package locations
1282 are preserved. Packages without package locations are moved to a new package
1283 location with the source customer's service/shipping address.
1285 All invoices, statements, payments, credits and refunds are moved to the target
1286 customer. The source customer's balance is added to the target customer.
1288 All notes, attachments, tickets and customer tags are moved to the target
1291 Change history is not currently moved.
1296 my( $self, $new_custnum, %opt ) = @_;
1298 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1300 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1301 or return "Invalid new customer number: $new_custnum";
1303 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1304 if $self->agentnum != $new_cust_main->agentnum
1305 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1307 local $SIG{HUP} = 'IGNORE';
1308 local $SIG{INT} = 'IGNORE';
1309 local $SIG{QUIT} = 'IGNORE';
1310 local $SIG{TERM} = 'IGNORE';
1311 local $SIG{TSTP} = 'IGNORE';
1312 local $SIG{PIPE} = 'IGNORE';
1314 my $oldAutoCommit = $FS::UID::AutoCommit;
1315 local $FS::UID::AutoCommit = 0;
1318 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1319 $dbh->rollback if $oldAutoCommit;
1320 return "Can't merge a master agent customer";
1323 #use FS::access_user
1324 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1325 $dbh->rollback if $oldAutoCommit;
1326 return "Can't merge a master employee customer";
1329 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1330 'status' => { op=>'!=', value=>'done' },
1334 $dbh->rollback if $oldAutoCommit;
1335 return "Can't merge a customer with pending payments";
1338 tie my %financial_tables, 'Tie::IxHash',
1339 'cust_bill' => 'invoices',
1340 'cust_bill_void' => 'voided invoices',
1341 'cust_statement' => 'statements',
1342 'cust_credit' => 'credits',
1343 'cust_credit_void' => 'voided credits',
1344 'cust_pay' => 'payments',
1345 'cust_pay_void' => 'voided payments',
1346 'cust_refund' => 'refunds',
1349 foreach my $table ( keys %financial_tables ) {
1351 my @records = $self->$table();
1353 foreach my $record ( @records ) {
1354 $record->custnum($new_custnum);
1355 my $error = $record->replace;
1357 $dbh->rollback if $oldAutoCommit;
1358 return "Error merging ". $financial_tables{$table}. ": $error\n";
1364 my $name = $self->ship_name; #?
1366 my $locationnum = '';
1367 foreach my $cust_pkg ( $self->all_pkgs ) {
1368 $cust_pkg->custnum($new_custnum);
1370 unless ( $cust_pkg->locationnum ) {
1371 unless ( $locationnum ) {
1372 my $cust_location = new FS::cust_location {
1373 $self->location_hash,
1374 'custnum' => $new_custnum,
1376 my $error = $cust_location->insert;
1378 $dbh->rollback if $oldAutoCommit;
1381 $locationnum = $cust_location->locationnum;
1383 $cust_pkg->locationnum($locationnum);
1386 my $error = $cust_pkg->replace;
1388 $dbh->rollback if $oldAutoCommit;
1392 # add customer (ship) name to svc_phone.phone_name if blank
1393 my @cust_svc = $cust_pkg->cust_svc;
1394 foreach my $cust_svc (@cust_svc) {
1395 my($label, $value, $svcdb) = $cust_svc->label;
1396 next unless $svcdb eq 'svc_phone';
1397 my $svc_phone = $cust_svc->svc_x;
1398 next if $svc_phone->phone_name;
1399 $svc_phone->phone_name($name);
1400 my $error = $svc_phone->replace;
1402 $dbh->rollback if $oldAutoCommit;
1410 # cust_tax_exempt (texas tax exemptions)
1411 # cust_recon (some sort of not-well understood thing for OnPac)
1413 #these are moved over
1414 foreach my $table (qw(
1415 cust_tag cust_location contact cust_attachment cust_main_note
1416 cust_tax_adjustment cust_pay_batch queue
1418 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1419 $record->custnum($new_custnum);
1420 my $error = $record->replace;
1422 $dbh->rollback if $oldAutoCommit;
1428 #these aren't preserved
1429 foreach my $table (qw(
1430 cust_main_exemption cust_main_invoice
1432 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1433 my $error = $record->delete;
1435 $dbh->rollback if $oldAutoCommit;
1442 my $sth = $dbh->prepare(
1443 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1445 my $errstr = $dbh->errstr;
1446 $dbh->rollback if $oldAutoCommit;
1449 $sth->execute($new_custnum, $self->custnum) or do {
1450 my $errstr = $sth->errstr;
1451 $dbh->rollback if $oldAutoCommit;
1457 my $ticket_dbh = '';
1458 if ($conf->config('ticket_system') eq 'RT_Internal') {
1460 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1461 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1462 $ticket_dbh = FS::DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1463 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1466 if ( $ticket_dbh ) {
1468 my $ticket_sth = $ticket_dbh->prepare(
1469 'UPDATE Links SET Target = ? WHERE Target = ?'
1471 my $errstr = $ticket_dbh->errstr;
1472 $dbh->rollback if $oldAutoCommit;
1475 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1476 'freeside://freeside/cust_main/'.$self->custnum)
1478 my $errstr = $ticket_sth->errstr;
1479 $dbh->rollback if $oldAutoCommit;
1485 #delete the customer record
1487 my $error = $self->delete;
1489 $dbh->rollback if $oldAutoCommit;
1493 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1498 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1500 Replaces the OLD_RECORD with this one in the database. If there is an error,
1501 returns the error, otherwise returns false.
1503 To change the customer's address, set the pseudo-fields C<bill_location> and
1504 C<ship_location>. The address will still only change if at least one of the
1505 address fields differs from the existing values.
1507 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1508 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1509 expected and rollback the entire transaction; it is not necessary to call
1510 check_invoicing_list first. Here's an example:
1512 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1514 Currently available options are: I<tax_exemption>.
1516 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1517 of tax names and exemption numbers. FS::cust_main_exemption records will be
1518 deleted and inserted as appropriate.
1525 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1527 : $self->replace_old;
1531 warn "$me replace called\n"
1534 my $curuser = $FS::CurrentUser::CurrentUser;
1535 if ( $self->payby eq 'COMP'
1536 && $self->payby ne $old->payby
1537 && ! $curuser->access_right('Complimentary customer')
1540 return "You are not permitted to create complimentary accounts.";
1543 local($ignore_expired_card) = 1
1544 if $old->payby =~ /^(CARD|DCRD)$/
1545 && $self->payby =~ /^(CARD|DCRD)$/
1546 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1548 local($ignore_banned_card) = 1
1549 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1550 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1551 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1553 if ( $self->payby =~ /^(CARD|DCRD)$/
1554 && $old->payinfo ne $self->payinfo
1555 && $old->paymask ne $self->paymask )
1557 my $error = $self->check_payinfo_cardtype;
1558 return $error if $error;
1560 if ( $conf->exists('business-onlinepayment-verification') ) {
1561 #need to standardize paydate for this, false laziness with check
1563 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1564 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1565 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1566 ( $m, $y ) = ( $2, "19$1" );
1567 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1568 ( $m, $y ) = ( $3, "20$2" );
1570 return "Illegal expiration date: ". $self->paydate;
1572 $m = sprintf('%02d',$m);
1573 $self->paydate("$y-$m-01");
1575 $error = $self->realtime_verify_bop({ 'method'=>'CC' });
1576 return $error if $error;
1580 return "Invoicing locale is required"
1583 && $conf->exists('cust_main-require_locale');
1585 local $SIG{HUP} = 'IGNORE';
1586 local $SIG{INT} = 'IGNORE';
1587 local $SIG{QUIT} = 'IGNORE';
1588 local $SIG{TERM} = 'IGNORE';
1589 local $SIG{TSTP} = 'IGNORE';
1590 local $SIG{PIPE} = 'IGNORE';
1592 my $oldAutoCommit = $FS::UID::AutoCommit;
1593 local $FS::UID::AutoCommit = 0;
1596 for my $l (qw(bill_location ship_location)) {
1597 my $old_loc = $old->$l;
1598 my $new_loc = $self->$l;
1600 # find the existing location if there is one
1601 $new_loc->set('custnum' => $self->custnum);
1602 my $error = $new_loc->find_or_insert;
1604 $dbh->rollback if $oldAutoCommit;
1607 $self->set($l.'num', $new_loc->locationnum);
1610 # replace the customer record
1611 my $error = $self->SUPER::replace($old);
1614 $dbh->rollback if $oldAutoCommit;
1618 # now move packages to the new service location
1619 $self->set('ship_location', ''); #flush cache
1620 if ( $old->ship_locationnum and # should only be null during upgrade...
1621 $old->ship_locationnum != $self->ship_locationnum ) {
1622 $error = $old->ship_location->move_to($self->ship_location);
1624 $dbh->rollback if $oldAutoCommit;
1628 # don't move packages based on the billing location, but
1629 # disable it if it's no longer in use
1630 if ( $old->bill_locationnum and
1631 $old->bill_locationnum != $self->bill_locationnum ) {
1632 $error = $old->bill_location->disable_if_unused;
1634 $dbh->rollback if $oldAutoCommit;
1639 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1640 my $invoicing_list = shift @param;
1641 $error = $self->check_invoicing_list( $invoicing_list );
1643 $dbh->rollback if $oldAutoCommit;
1646 $self->invoicing_list( $invoicing_list );
1649 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1651 #this could be more efficient than deleting and re-inserting, if it matters
1652 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1653 my $error = $cust_tag->delete;
1655 $dbh->rollback if $oldAutoCommit;
1659 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1660 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1661 'custnum' => $self->custnum };
1662 my $error = $cust_tag->insert;
1664 $dbh->rollback if $oldAutoCommit;
1671 my %options = @param;
1673 my $tax_exemption = delete $options{'tax_exemption'};
1674 if ( $tax_exemption ) {
1676 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1677 if ref($tax_exemption) eq 'ARRAY';
1679 my %cust_main_exemption =
1680 map { $_->taxname => $_ }
1681 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1683 foreach my $taxname ( keys %$tax_exemption ) {
1685 if ( $cust_main_exemption{$taxname} &&
1686 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1689 delete $cust_main_exemption{$taxname};
1693 my $cust_main_exemption = new FS::cust_main_exemption {
1694 'custnum' => $self->custnum,
1695 'taxname' => $taxname,
1696 'exempt_number' => $tax_exemption->{$taxname},
1698 my $error = $cust_main_exemption->insert;
1700 $dbh->rollback if $oldAutoCommit;
1701 return "inserting cust_main_exemption (transaction rolled back): $error";
1705 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1706 my $error = $cust_main_exemption->delete;
1708 $dbh->rollback if $oldAutoCommit;
1709 return "deleting cust_main_exemption (transaction rolled back): $error";
1715 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1716 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1717 && $self->get('payinfo') !~ /^99\d{14}$/
1719 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1724 # card/check/lec info has changed, want to retry realtime_ invoice events
1725 my $error = $self->retry_realtime;
1727 $dbh->rollback if $oldAutoCommit;
1732 unless ( $import || $skip_fuzzyfiles ) {
1733 $error = $self->queue_fuzzyfiles_update;
1735 $dbh->rollback if $oldAutoCommit;
1736 return "updating fuzzy search cache: $error";
1740 # tax district update in cust_location
1742 # cust_main exports!
1744 my $export_args = $options{'export_args'} || [];
1747 map qsearch( 'part_export', {exportnum=>$_} ),
1748 $conf->config('cust_main-exports'); #, $agentnum
1750 foreach my $part_export ( @part_export ) {
1751 my $error = $part_export->export_replace( $self, $old, @$export_args);
1753 $dbh->rollback if $oldAutoCommit;
1754 return "exporting to ". $part_export->exporttype.
1755 " (transaction rolled back): $error";
1759 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1764 =item queue_fuzzyfiles_update
1766 Used by insert & replace to update the fuzzy search cache
1770 use FS::cust_main::Search;
1771 sub queue_fuzzyfiles_update {
1774 local $SIG{HUP} = 'IGNORE';
1775 local $SIG{INT} = 'IGNORE';
1776 local $SIG{QUIT} = 'IGNORE';
1777 local $SIG{TERM} = 'IGNORE';
1778 local $SIG{TSTP} = 'IGNORE';
1779 local $SIG{PIPE} = 'IGNORE';
1781 my $oldAutoCommit = $FS::UID::AutoCommit;
1782 local $FS::UID::AutoCommit = 0;
1785 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1786 my $queue = new FS::queue {
1787 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1789 my @args = "cust_main.$field", $self->get($field);
1790 my $error = $queue->insert( @args );
1792 $dbh->rollback if $oldAutoCommit;
1793 return "queueing job (transaction rolled back): $error";
1797 my @locations = $self->bill_location;
1798 push @locations, $self->ship_location if $self->has_ship_address;
1799 foreach my $location (@locations) {
1800 my $queue = new FS::queue {
1801 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1803 my @args = 'cust_location.address1', $location->address1;
1804 my $error = $queue->insert( @args );
1806 $dbh->rollback if $oldAutoCommit;
1807 return "queueing job (transaction rolled back): $error";
1811 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1818 Checks all fields to make sure this is a valid customer record. If there is
1819 an error, returns the error, otherwise returns false. Called by the insert
1820 and replace methods.
1827 warn "$me check BEFORE: \n". $self->_dump
1831 $self->ut_numbern('custnum')
1832 || $self->ut_number('agentnum')
1833 || $self->ut_textn('agent_custid')
1834 || $self->ut_number('refnum')
1835 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1836 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1837 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1838 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1839 || $self->ut_textn('custbatch')
1840 || $self->ut_name('last')
1841 || $self->ut_name('first')
1842 || $self->ut_snumbern('signupdate')
1843 || $self->ut_snumbern('birthdate')
1844 || $self->ut_namen('spouse_last')
1845 || $self->ut_namen('spouse_first')
1846 || $self->ut_snumbern('spouse_birthdate')
1847 || $self->ut_snumbern('anniversary_date')
1848 || $self->ut_textn('company')
1849 || $self->ut_textn('ship_company')
1850 || $self->ut_anything('comments')
1851 || $self->ut_numbern('referral_custnum')
1852 || $self->ut_textn('stateid')
1853 || $self->ut_textn('stateid_state')
1854 || $self->ut_textn('invoice_terms')
1855 || $self->ut_floatn('cdr_termination_percentage')
1856 || $self->ut_floatn('credit_limit')
1857 || $self->ut_numbern('billday')
1858 || $self->ut_numbern('prorate_day')
1859 || $self->ut_flag('force_prorate_day')
1860 || $self->ut_flag('edit_subject')
1861 || $self->ut_flag('calling_list_exempt')
1862 || $self->ut_flag('invoice_noemail')
1863 || $self->ut_flag('message_noemail')
1864 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1865 || $self->ut_flag('invoice_ship_address')
1868 foreach (qw(company ship_company)) {
1869 my $company = $self->get($_);
1870 $company =~ s/^\s+//;
1871 $company =~ s/\s+$//;
1872 $company =~ s/\s+/ /g;
1873 $self->set($_, $company);
1876 #barf. need message catalogs. i18n. etc.
1877 $error .= "Please select an advertising source."
1878 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1879 return $error if $error;
1881 return "Unknown agent"
1882 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1884 return "Unknown refnum"
1885 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1887 return "Unknown referring custnum: ". $self->referral_custnum
1888 unless ! $self->referral_custnum
1889 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1891 if ( $self->ss eq '' ) {
1896 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1897 or return "Illegal social security number: ". $self->ss;
1898 $self->ss("$1-$2-$3");
1901 #turn off invoice_ship_address if ship & bill are the same
1902 if ($self->bill_locationnum eq $self->ship_locationnum) {
1903 $self->invoice_ship_address('');
1906 # cust_main_county verification now handled by cust_location check
1909 $self->ut_phonen('daytime', $self->country)
1910 || $self->ut_phonen('night', $self->country)
1911 || $self->ut_phonen('fax', $self->country)
1912 || $self->ut_phonen('mobile', $self->country)
1914 return $error if $error;
1916 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1918 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1921 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1923 : FS::Msgcat::_gettext('daytime');
1924 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1926 : FS::Msgcat::_gettext('night');
1928 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1930 : FS::Msgcat::_gettext('mobile');
1932 return "$daytime_label, $night_label or $mobile_label is required"
1936 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1937 # or return "Illegal payby: ". $self->payby;
1939 FS::payby->can_payby($self->table, $self->payby)
1940 or return "Illegal payby: ". $self->payby;
1942 $error = $self->ut_numbern('paystart_month')
1943 || $self->ut_numbern('paystart_year')
1944 || $self->ut_numbern('payissue')
1945 || $self->ut_textn('paytype')
1947 return $error if $error;
1949 if ( $self->payip eq '' ) {
1952 $error = $self->ut_ip('payip');
1953 return $error if $error;
1956 # If it is encrypted and the private key is not availaible then we can't
1957 # check the credit card.
1958 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1960 # Need some kind of global flag to accept invalid cards, for testing
1962 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1964 my $payinfo = $self->payinfo;
1965 $payinfo =~ s/\D//g;
1966 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1967 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1969 $self->payinfo($payinfo);
1971 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1973 my $cardtype = $self->paycardtype;
1974 if ( $payinfo =~ /^99\d{14}$/ ) {
1975 $self->set('is_tokenized', 'Y'); #so we don't try to do it again
1976 if ( $self->paymask =~ /^\d+x/ ) {
1977 $cardtype = cardtype($self->paymask);
1979 #return "paycardtype required ".
1980 # "(can't derive from a token and no paymask w/prefix provided)"
1984 $cardtype = cardtype($self->payinfo);
1987 return gettext('unknown_card_type') if $cardtype eq 'Unknown';
1989 $self->set('paycardtype', $cardtype);
1991 unless ( $ignore_banned_card ) {
1992 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1994 if ( $ban->bantype eq 'warn' ) {
1995 #or others depending on value of $ban->reason ?
1996 return '_duplicate_card'.
1997 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1998 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1999 ' (ban# '. $ban->bannum. ')'
2000 unless $self->override_ban_warn;
2002 return 'Banned credit card: banned on '.
2003 time2str('%a %h %o at %r', $ban->_date).
2004 ' by '. $ban->otaker.
2005 ' (ban# '. $ban->bannum. ')';
2010 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
2011 if ( $cardtype eq 'American Express card' ) {
2012 $self->paycvv =~ /^(\d{4})$/
2013 or return "CVV2 (CID) for American Express cards is four digits.";
2016 $self->paycvv =~ /^(\d{3})$/
2017 or return "CVV2 (CVC2/CID) is three digits.";
2024 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
2026 return "Start date or issue number is required for $cardtype cards"
2027 unless $self->paystart_month && $self->paystart_year or $self->payissue;
2029 return "Start month must be between 1 and 12"
2030 if $self->paystart_month
2031 and $self->paystart_month < 1 || $self->paystart_month > 12;
2033 return "Start year must be 1990 or later"
2034 if $self->paystart_year
2035 and $self->paystart_year < 1990;
2037 return "Issue number must be beween 1 and 99"
2039 and $self->payissue < 1 || $self->payissue > 99;
2042 $self->paystart_month('');
2043 $self->paystart_year('');
2044 $self->payissue('');
2047 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
2049 my $payinfo = $self->payinfo;
2050 $payinfo =~ s/[^\d\@\.]//g;
2051 if ( $conf->config('echeck-country') eq 'CA' ) {
2052 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
2053 or return 'invalid echeck account@branch.bank';
2054 $payinfo = "$1\@$2.$3";
2055 } elsif ( $conf->config('echeck-country') eq 'US' ) {
2056 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
2057 $payinfo = "$1\@$2";
2059 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2060 $payinfo = "$1\@$2";
2062 $self->payinfo($payinfo);
2065 unless ( $ignore_banned_card ) {
2066 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2068 if ( $ban->bantype eq 'warn' ) {
2069 #or others depending on value of $ban->reason ?
2070 return '_duplicate_ach' unless $self->override_ban_warn;
2072 return 'Banned ACH account: banned on '.
2073 time2str('%a %h %o at %r', $ban->_date).
2074 ' by '. $ban->otaker.
2075 ' (ban# '. $ban->bannum. ')';
2080 } elsif ( $self->payby eq 'LECB' ) {
2082 my $payinfo = $self->payinfo;
2083 $payinfo =~ s/\D//g;
2084 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2086 $self->payinfo($payinfo);
2089 } elsif ( $self->payby eq 'BILL' ) {
2091 $error = $self->ut_textn('payinfo');
2092 return "Illegal P.O. number: ". $self->payinfo if $error;
2095 } elsif ( $self->payby eq 'COMP' ) {
2097 my $curuser = $FS::CurrentUser::CurrentUser;
2098 if ( ! $self->custnum
2099 && ! $curuser->access_right('Complimentary customer')
2102 return "You are not permitted to create complimentary accounts."
2105 $error = $self->ut_textn('payinfo');
2106 return "Illegal comp account issuer: ". $self->payinfo if $error;
2109 } elsif ( $self->payby eq 'PREPAY' ) {
2111 my $payinfo = $self->payinfo;
2112 $payinfo =~ s/\W//g; #anything else would just confuse things
2113 $self->payinfo($payinfo);
2114 $error = $self->ut_alpha('payinfo');
2115 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2116 return "Unknown prepayment identifier"
2117 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2120 } elsif ( $self->payby =~ /^CARD|DCRD$/ and $self->paymask ) {
2121 # either ignoring invalid cards, or we can't decrypt the payinfo, but
2122 # try to detect the card type anyway. this never returns failure, so
2123 # the contract of $ignore_invalid_cards is maintained.
2124 $self->set('paycardtype', cardtype($self->paymask));
2127 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2128 return "Expiration date required"
2129 # shouldn't payinfo_check do this?
2130 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2134 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2135 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2136 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2137 ( $m, $y ) = ( $2, "19$1" );
2138 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2139 ( $m, $y ) = ( $3, "20$2" );
2141 return "Illegal expiration date: ". $self->paydate;
2143 $m = sprintf('%02d',$m);
2144 $self->paydate("$y-$m-01");
2145 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2146 return gettext('expired_card')
2148 && !$ignore_expired_card
2149 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2151 if ( my $error = $self->ut_daten('paydate') ) {
2156 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2157 ( ! $conf->exists('require_cardname')
2158 || $self->payby !~ /^(CARD|DCRD)$/ )
2160 $self->payname( $self->first. " ". $self->getfield('last') );
2163 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2164 $self->payname =~ /^([\w \,\.\-\']*)$/
2165 or return gettext('illegal_name'). " payname: ". $self->payname;
2168 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2169 or return gettext('illegal_name'). " payname: ". $self->payname;
2175 return "Please select an invoicing locale"
2178 && $conf->exists('cust_main-require_locale');
2180 return "Please select a customer class"
2181 if ! $self->classnum
2182 && $conf->exists('cust_main-require_classnum');
2184 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2185 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2189 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2191 warn "$me check AFTER: \n". $self->_dump
2194 $self->SUPER::check;
2197 sub check_payinfo_cardtype {
2200 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
2202 my $payinfo = $self->payinfo;
2203 $payinfo =~ s/\D//g;
2205 if ( $payinfo =~ /^99\d{14}$/ ) {
2209 my %bop_card_types = map { $_=>1 } values %{ card_types() };
2210 my $cardtype = cardtype($payinfo);
2211 $self->set('paycardtype', $cardtype);
2213 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
2221 Additional checks for replace only.
2226 my ($new,$old) = @_;
2227 #preserve old value if global config is set
2228 if ($old && $conf->exists('invoice-ship_address')) {
2229 $new->invoice_ship_address($old->invoice_ship_address);
2236 Returns a list of fields which have ship_ duplicates.
2241 qw( last first company
2243 address1 address2 city county state zip country
2245 daytime night fax mobile
2249 =item has_ship_address
2251 Returns true if this customer record has a separate shipping address.
2255 sub has_ship_address {
2257 $self->bill_locationnum != $self->ship_locationnum;
2262 Returns a list of key/value pairs, with the following keys: address1,
2263 adddress2, city, county, state, zip, country, district, and geocode. The
2264 shipping address is used if present.
2270 $self->ship_location->location_hash;
2275 Returns all locations (see L<FS::cust_location>) for this customer.
2281 qsearch('cust_location', { 'custnum' => $self->custnum,
2282 'prospectnum' => '' } );
2287 Returns all contacts (see L<FS::contact>) for this customer.
2291 #already used :/ sub contact {
2294 qsearch('contact', { 'custnum' => $self->custnum } );
2299 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2300 and L<FS::cust_pkg>) for this customer, except those on hold.
2302 Returns a list: an empty list on success or a list of errors.
2308 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs(@_);
2313 Unsuspends all suspended packages in the on-hold state (those without setup
2314 dates) for this customer.
2320 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2325 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2327 Returns a list: an empty list on success or a list of errors.
2333 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2336 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2338 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2339 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2340 of a list of pkgparts; the hashref has the following keys:
2344 =item pkgparts - listref of pkgparts
2346 =item (other options are passed to the suspend method)
2351 Returns a list: an empty list on success or a list of errors.
2355 sub suspend_if_pkgpart {
2357 my (@pkgparts, %opt);
2358 if (ref($_[0]) eq 'HASH'){
2359 @pkgparts = @{$_[0]{pkgparts}};
2364 grep { $_->suspend(%opt) }
2365 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2366 $self->unsuspended_pkgs;
2369 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2371 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2372 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2373 instead of a list of pkgparts; the hashref has the following keys:
2377 =item pkgparts - listref of pkgparts
2379 =item (other options are passed to the suspend method)
2383 Returns a list: an empty list on success or a list of errors.
2387 sub suspend_unless_pkgpart {
2389 my (@pkgparts, %opt);
2390 if (ref($_[0]) eq 'HASH'){
2391 @pkgparts = @{$_[0]{pkgparts}};
2396 grep { $_->suspend(%opt) }
2397 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2398 $self->unsuspended_pkgs;
2401 =item cancel [ OPTION => VALUE ... ]
2403 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2404 The cancellation time will be now.
2408 Always returns a list: an empty list on success or a list of errors.
2415 warn "$me cancel called on customer ". $self->custnum. " with options ".
2416 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2418 my @pkgs = $self->ncancelled_pkgs;
2420 $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2423 =item cancel_pkgs OPTIONS
2425 Cancels a specified list of packages. OPTIONS can include:
2429 =item cust_pkg - an arrayref of the packages. Required.
2431 =item time - the cancellation time, used to calculate final bills and
2432 unused-time credits if any. Will be passed through to the bill() and
2433 FS::cust_pkg::cancel() methods.
2435 =item quiet - can be set true to supress email cancellation notices.
2437 =item reason - can be set to a cancellation reason (see L<FS::reason>), either a
2438 reasonnum of an existing reason, or passing a hashref will create a new reason.
2439 The hashref should have the following keys:
2440 typenum - Reason type (see L<FS::reason_type>)
2441 reason - Text of the new reason.
2443 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2444 for the individual packages, parallel to the C<cust_pkg> argument. The
2445 reason and reason_otaker arguments will be taken from those objects.
2447 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2449 =item nobill - can be set true to skip billing if it might otherwise be done.
2454 my( $self, %opt ) = @_;
2456 # we're going to cancel services, which is not reversible
2457 # but on 3.x, don't strictly enforce this
2458 warn "cancel_pkgs should not be run inside a transaction"
2459 if $FS::UID::AutoCommit == 0;
2461 local $FS::UID::AutoCommit = 0;
2463 return ( 'access denied' )
2464 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2466 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2468 #should try decryption (we might have the private key)
2469 # and if not maybe queue a job for the server that does?
2470 return ( "Can't (yet) ban encrypted credit cards" )
2471 if $self->is_encrypted($self->payinfo);
2473 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2474 my $error = $ban->insert;
2482 my @pkgs = @{ delete $opt{'cust_pkg'} };
2483 my $cancel_time = $opt{'time'} || time;
2485 # bill all packages first, so we don't lose usage, service counts for
2486 # bulk billing, etc.
2487 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2489 my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2491 'time' => $cancel_time );
2493 warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2495 return ( "Error billing during cancellation: $error" );
2501 # try to cancel each service, the same way we would for individual packages,
2502 # but in cancel weight order.
2503 my @cust_svc = map { $_->cust_svc } @pkgs;
2504 my @sorted_cust_svc =
2506 sort { $a->[1] <=> $b->[1] }
2507 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2509 warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2512 foreach my $cust_svc (@sorted_cust_svc) {
2513 my $part_svc = $cust_svc->part_svc;
2514 next if ( defined($part_svc) and $part_svc->preserve );
2515 # immediate cancel, no date option
2516 # transactionize individually
2517 my $error = try { $cust_svc->cancel } catch { $_ };
2520 push @errors, $error;
2529 warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2530 $self->custnum. "\n"
2534 if ($opt{'cust_pkg_reason'}) {
2535 @cprs = @{ delete $opt{'cust_pkg_reason'} };
2541 my $cpr = shift @cprs;
2543 $lopt{'reason'} = $cpr->reasonnum;
2544 $lopt{'reason_otaker'} = $cpr->otaker;
2546 warn "no reason found when canceling package ".$_->pkgnum."\n";
2547 $lopt{'reason'} = '';
2550 my $error = $_->cancel(%lopt);
2553 push @errors, 'pkgnum '.$_->pkgnum.': '.$error;
2562 sub _banned_pay_hashref {
2573 'payby' => $payby2ban{$self->payby},
2574 'payinfo' => $self->payinfo,
2575 #don't ever *search* on reason! #'reason' =>
2579 sub _new_banned_pay_hashref {
2581 my $hr = $self->_banned_pay_hashref;
2582 $hr->{payinfo} = md5_base64($hr->{payinfo});
2588 Returns all notes (see L<FS::cust_main_note>) for this customer.
2593 my($self,$orderby_classnum) = (shift,shift);
2594 my $orderby = "sticky DESC, _date DESC";
2595 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2596 qsearch( 'cust_main_note',
2597 { 'custnum' => $self->custnum },
2599 "ORDER BY $orderby",
2605 Returns the agent (see L<FS::agent>) for this customer.
2611 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2616 Returns the agent name (see L<FS::agent>) for this customer.
2622 $self->agent->agent;
2627 Returns any tags associated with this customer, as FS::cust_tag objects,
2628 or an empty list if there are no tags.
2634 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2639 Returns any tags associated with this customer, as FS::part_tag objects,
2640 or an empty list if there are no tags.
2646 map $_->part_tag, $self->cust_tag;
2652 Returns the customer class, as an FS::cust_class object, or the empty string
2653 if there is no customer class.
2659 if ( $self->classnum ) {
2660 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2668 Returns the customer category name, or the empty string if there is no customer
2675 my $cust_class = $self->cust_class;
2677 ? $cust_class->categoryname
2683 Returns the customer class name, or the empty string if there is no customer
2690 my $cust_class = $self->cust_class;
2692 ? $cust_class->classname
2696 =item BILLING METHODS
2698 Documentation on billing methods has been moved to
2699 L<FS::cust_main::Billing>.
2701 =item REALTIME BILLING METHODS
2703 Documentation on realtime billing methods has been moved to
2704 L<FS::cust_main::Billing_Realtime>.
2708 Removes the I<paycvv> field from the database directly.
2710 If there is an error, returns the error, otherwise returns false.
2716 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2717 or return dbh->errstr;
2718 $sth->execute($self->custnum)
2719 or return $sth->errstr;
2724 =item batch_card OPTION => VALUE...
2726 Adds a payment for this invoice to the pending credit card batch (see
2727 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2728 runs the payment using a realtime gateway.
2730 Options may include:
2732 B<amount>: the amount to be paid; defaults to the customer's balance minus
2733 any payments in transit.
2735 B<payby>: the payment method; defaults to cust_main.payby
2737 B<realtime>: runs this as a realtime payment instead of adding it to a
2740 B<invnum>: sets cust_pay_batch.invnum.
2742 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2743 the billing address for the payment; defaults to the customer's billing
2746 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2747 date, and name; defaults to those fields in cust_main.
2752 my ($self, %options) = @_;
2755 if (exists($options{amount})) {
2756 $amount = $options{amount};
2758 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2761 warn(sprintf("Customer balance %.2f - in transit amount %.2f is <= 0.\n",
2763 $self->in_transit_payments
2768 my $invnum = delete $options{invnum};
2769 my $payby = $options{payby} || $self->payby; #still dubious
2771 if ($options{'realtime'}) {
2772 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2778 my $oldAutoCommit = $FS::UID::AutoCommit;
2779 local $FS::UID::AutoCommit = 0;
2782 #this needs to handle mysql as well as Pg, like svc_acct.pm
2783 #(make it into a common function if folks need to do batching with mysql)
2784 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2785 or return "Cannot lock pay_batch: " . $dbh->errstr;
2789 'payby' => FS::payby->payby2payment($payby),
2791 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2793 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2795 unless ( $pay_batch ) {
2796 $pay_batch = new FS::pay_batch \%pay_batch;
2797 my $error = $pay_batch->insert;
2799 $dbh->rollback if $oldAutoCommit;
2800 die "error creating new batch: $error\n";
2804 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2805 'batchnum' => $pay_batch->batchnum,
2806 'custnum' => $self->custnum,
2809 foreach (qw( address1 address2 city state zip country latitude longitude
2810 payby payinfo paydate payname paycode paytype ))
2812 $options{$_} = '' unless exists($options{$_});
2815 my $loc = $self->bill_location;
2817 my $cust_pay_batch = new FS::cust_pay_batch ( {
2818 'batchnum' => $pay_batch->batchnum,
2819 'invnum' => $invnum || 0, # is there a better value?
2820 # this field should be
2822 # cust_bill_pay_batch now
2823 'custnum' => $self->custnum,
2824 'last' => $self->getfield('last'),
2825 'first' => $self->getfield('first'),
2826 'address1' => $options{address1} || $loc->address1,
2827 'address2' => $options{address2} || $loc->address2,
2828 'city' => $options{city} || $loc->city,
2829 'state' => $options{state} || $loc->state,
2830 'zip' => $options{zip} || $loc->zip,
2831 'country' => $options{country} || $loc->country,
2832 'payby' => $options{payby} || $self->payby,
2833 'payinfo' => $options{payinfo} || $self->payinfo,
2834 'paymask' => ( $options{payinfo}
2835 ? FS::payinfo_Mixin->mask_payinfo( $options{payby},
2839 'exp' => $options{paydate} || $self->paydate,
2840 'payname' => $options{payname} || $self->payname,
2841 'amount' => $amount, # consolidating
2842 'paycode' => $options{paycode} || '',
2845 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2846 if $old_cust_pay_batch;
2849 if ($old_cust_pay_batch) {
2850 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2852 $error = $cust_pay_batch->insert;
2856 $dbh->rollback if $oldAutoCommit;
2860 if ($options{'processing-fee'} > 0) {
2862 my $processing_fee_text = 'Payment Processing Fee';
2864 unless ( $invnum ) { # probably from a payment screen
2865 # do we have any open invoices? pick earliest
2866 # uses the fact that cust_main->cust_bill sorts by date ascending
2867 my @open = $self->open_cust_bill;
2868 $invnum = $open[0]->invnum if scalar(@open);
2871 unless ( $invnum ) { # still nothing? pick last closed invoice
2872 # again uses fact that cust_main->cust_bill sorts by date ascending
2873 my @closed = $self->cust_bill;
2874 $invnum = $closed[$#closed]->invnum if scalar(@closed);
2877 unless ( $invnum ) {
2878 # XXX: unlikely case - pre-paying before any invoices generated
2879 # what it should do is create a new invoice and pick it
2880 warn '\PROCESS FEE AND NO INVOICES PICKED TO APPLY IT!';
2884 my $pf_change_error = $self->charge({
2885 'amount' => $options{'processing-fee'},
2886 'pkg' => $processing_fee_text,
2888 'cust_pkg_ref' => \$pf_cust_pkg,
2891 if($pf_change_error) {
2892 warn 'Unable to add payment processing fee';
2896 $pf_cust_pkg->setup(time);
2897 my $pf_error = $pf_cust_pkg->replace;
2899 warn 'Unable to set setup time on cust_pkg for processing fee';
2903 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
2904 unless ( $cust_bill ) {
2905 warn "race condition + invoice deletion just happened";
2909 my $grand_pf_error =
2910 $cust_bill->add_cc_surcharge($pf_cust_pkg->pkgnum,$options{'processing-fee'});
2912 warn "cannot add Processing fee to invoice #$invnum: $grand_pf_error"
2916 my $unapplied = $self->total_unapplied_credits
2917 + $self->total_unapplied_payments
2918 + $self->in_transit_payments;
2919 foreach my $cust_bill ($self->open_cust_bill) {
2920 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2921 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2922 'invnum' => $cust_bill->invnum,
2923 'paybatchnum' => $cust_pay_batch->paybatchnum,
2924 'amount' => $cust_bill->owed,
2927 if ($unapplied >= $cust_bill_pay_batch->amount){
2928 $unapplied -= $cust_bill_pay_batch->amount;
2931 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2932 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2934 $error = $cust_bill_pay_batch->insert;
2936 $dbh->rollback if $oldAutoCommit;
2941 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2947 Returns the total owed for this customer on all invoices
2948 (see L<FS::cust_bill/owed>).
2954 $self->total_owed_date(2145859200); #12/31/2037
2957 =item total_owed_date TIME
2959 Returns the total owed for this customer on all invoices with date earlier than
2960 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2961 see L<Time::Local> and L<Date::Parse> for conversion functions.
2965 sub total_owed_date {
2969 my $custnum = $self->custnum;
2971 my $owed_sql = FS::cust_bill->owed_sql;
2974 SELECT SUM($owed_sql) FROM cust_bill
2975 WHERE custnum = $custnum
2979 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2983 =item total_owed_pkgnum PKGNUM
2985 Returns the total owed on all invoices for this customer's specific package
2986 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2990 sub total_owed_pkgnum {
2991 my( $self, $pkgnum ) = @_;
2992 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2995 =item total_owed_date_pkgnum TIME PKGNUM
2997 Returns the total owed for this customer's specific package when using
2998 experimental package balances on all invoices with date earlier than
2999 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
3000 see L<Time::Local> and L<Date::Parse> for conversion functions.
3004 sub total_owed_date_pkgnum {
3005 my( $self, $time, $pkgnum ) = @_;
3008 foreach my $cust_bill (
3009 grep { $_->_date <= $time }
3010 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3012 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
3014 sprintf( "%.2f", $total_bill );
3020 Returns the total amount of all payments.
3027 $total += $_->paid foreach $self->cust_pay;
3028 sprintf( "%.2f", $total );
3031 =item total_unapplied_credits
3033 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3034 customer. See L<FS::cust_credit/credited>.
3036 =item total_credited
3038 Old name for total_unapplied_credits. Don't use.
3042 sub total_credited {
3043 #carp "total_credited deprecated, use total_unapplied_credits";
3044 shift->total_unapplied_credits(@_);
3047 sub total_unapplied_credits {
3050 my $custnum = $self->custnum;
3052 my $unapplied_sql = FS::cust_credit->unapplied_sql;
3055 SELECT SUM($unapplied_sql) FROM cust_credit
3056 WHERE custnum = $custnum
3059 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
3063 =item total_unapplied_credits_pkgnum PKGNUM
3065 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3066 customer. See L<FS::cust_credit/credited>.
3070 sub total_unapplied_credits_pkgnum {
3071 my( $self, $pkgnum ) = @_;
3072 my $total_credit = 0;
3073 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
3074 sprintf( "%.2f", $total_credit );
3078 =item total_unapplied_payments
3080 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3081 See L<FS::cust_pay/unapplied>.
3085 sub total_unapplied_payments {
3088 my $custnum = $self->custnum;
3090 my $unapplied_sql = FS::cust_pay->unapplied_sql;
3093 SELECT SUM($unapplied_sql) FROM cust_pay
3094 WHERE custnum = $custnum
3097 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
3101 =item total_unapplied_payments_pkgnum PKGNUM
3103 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
3104 specific package when using experimental package balances. See
3105 L<FS::cust_pay/unapplied>.
3109 sub total_unapplied_payments_pkgnum {
3110 my( $self, $pkgnum ) = @_;
3111 my $total_unapplied = 0;
3112 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
3113 sprintf( "%.2f", $total_unapplied );
3117 =item total_unapplied_refunds
3119 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
3120 customer. See L<FS::cust_refund/unapplied>.
3124 sub total_unapplied_refunds {
3126 my $custnum = $self->custnum;
3128 my $unapplied_sql = FS::cust_refund->unapplied_sql;
3131 SELECT SUM($unapplied_sql) FROM cust_refund
3132 WHERE custnum = $custnum
3135 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
3141 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3142 total_unapplied_credits minus total_unapplied_payments).
3148 $self->balance_date_range;
3151 =item balance_date TIME
3153 Returns the balance for this customer, only considering invoices with date
3154 earlier than TIME (total_owed_date minus total_credited minus
3155 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
3156 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
3163 $self->balance_date_range(shift);
3166 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
3168 Returns the balance for this customer, optionally considering invoices with
3169 date earlier than START_TIME, and not later than END_TIME
3170 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
3172 Times are specified as SQL fragments or numeric
3173 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
3174 L<Date::Parse> for conversion functions. The empty string can be passed
3175 to disable that time constraint completely.
3177 Accepts the same options as L</balance_date_sql>:
3181 =item unapplied_date
3183 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)
3187 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
3188 time will be ignored. Note that START_TIME and END_TIME only limit the date
3189 range for invoices and I<unapplied> payments, credits, and refunds.
3195 sub balance_date_range {
3197 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
3198 ') FROM cust_main WHERE custnum='. $self->custnum;
3199 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
3202 =item balance_pkgnum PKGNUM
3204 Returns the balance for this customer's specific package when using
3205 experimental package balances (total_owed plus total_unrefunded, minus
3206 total_unapplied_credits minus total_unapplied_payments)
3210 sub balance_pkgnum {
3211 my( $self, $pkgnum ) = @_;
3214 $self->total_owed_pkgnum($pkgnum)
3215 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
3216 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
3217 - $self->total_unapplied_credits_pkgnum($pkgnum)
3218 - $self->total_unapplied_payments_pkgnum($pkgnum)
3222 =item in_transit_payments
3224 Returns the total of requests for payments for this customer pending in
3225 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
3229 sub in_transit_payments {
3231 my $in_transit_payments = 0;
3232 foreach my $pay_batch ( qsearch('pay_batch', {
3235 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3236 'batchnum' => $pay_batch->batchnum,
3237 'custnum' => $self->custnum,
3240 $in_transit_payments += $cust_pay_batch->amount;
3243 sprintf( "%.2f", $in_transit_payments );
3248 Returns a hash of useful information for making a payment.
3258 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3259 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3260 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3264 For credit card transactions:
3276 For electronic check transactions:
3291 $return{balance} = $self->balance;
3293 $return{payname} = $self->payname
3294 || ( $self->first. ' '. $self->get('last') );
3296 $return{$_} = $self->bill_location->$_
3297 for qw(address1 address2 city state zip);
3299 $return{payby} = $self->payby;
3300 $return{stateid_state} = $self->stateid_state;
3302 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3303 $return{card_type} = cardtype($self->payinfo);
3304 $return{payinfo} = $self->paymask;
3306 @return{'month', 'year'} = $self->paydate_monthyear;
3310 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3311 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3312 $return{payinfo1} = $payinfo1;
3313 $return{payinfo2} = $payinfo2;
3314 $return{paytype} = $self->paytype;
3315 $return{paystate} = $self->paystate;
3319 #doubleclick protection
3321 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3327 =item paydate_monthyear
3329 Returns a two-element list consisting of the month and year of this customer's
3330 paydate (credit card expiration date for CARD customers)
3334 sub paydate_monthyear {
3336 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3338 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3347 Returns the exact time in seconds corresponding to the payment method
3348 expiration date. For CARD/DCRD customers this is the end of the month;
3349 for others (COMP is the only other payby that uses paydate) it's the start.
3350 Returns 0 if the paydate is empty or set to the far future.
3356 my ($month, $year) = $self->paydate_monthyear;
3357 return 0 if !$year or $year >= 2037;
3358 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3360 if ( $month == 13 ) {
3364 return timelocal(0,0,0,1,$month-1,$year) - 1;
3367 return timelocal(0,0,0,1,$month-1,$year);
3371 =item paydate_epoch_sql
3373 Class method. Returns an SQL expression to obtain the payment expiration date
3374 as a number of seconds.
3378 # Special expiration date behavior for non-CARD/DCRD customers has been
3379 # carefully preserved. Do we really use that?
3380 sub paydate_epoch_sql {
3382 my $table = shift || 'cust_main';
3383 my ($case1, $case2);
3384 if ( driver_name eq 'Pg' ) {
3385 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3386 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3388 elsif ( lc(driver_name) eq 'mysql' ) {
3389 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3390 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3393 return "CASE WHEN $table.payby IN('CARD','DCRD')
3399 =item tax_exemption TAXNAME
3404 my( $self, $taxname ) = @_;
3406 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3407 'taxname' => $taxname,
3412 =item cust_main_exemption
3416 sub cust_main_exemption {
3418 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3421 =item invoicing_list [ ARRAYREF ]
3423 If an arguement is given, sets these email addresses as invoice recipients
3424 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3425 (except as warnings), so use check_invoicing_list first.
3427 Returns a list of email addresses (with svcnum entries expanded).
3429 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3430 check it without disturbing anything by passing nothing.
3432 This interface may change in the future.
3436 sub invoicing_list {
3437 my( $self, $arrayref ) = @_;
3440 my @cust_main_invoice;
3441 if ( $self->custnum ) {
3442 @cust_main_invoice =
3443 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3445 @cust_main_invoice = ();
3447 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3448 #warn $cust_main_invoice->destnum;
3449 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3450 #warn $cust_main_invoice->destnum;
3451 my $error = $cust_main_invoice->delete;
3452 warn $error if $error;
3455 if ( $self->custnum ) {
3456 @cust_main_invoice =
3457 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3459 @cust_main_invoice = ();
3461 my %seen = map { $_->address => 1 } @cust_main_invoice;
3462 foreach my $address ( @{$arrayref} ) {
3463 next if exists $seen{$address} && $seen{$address};
3464 $seen{$address} = 1;
3465 my $cust_main_invoice = new FS::cust_main_invoice ( {
3466 'custnum' => $self->custnum,
3469 my $error = $cust_main_invoice->insert;
3470 warn $error if $error;
3474 if ( $self->custnum ) {
3476 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3483 =item check_invoicing_list ARRAYREF
3485 Checks these arguements as valid input for the invoicing_list method. If there
3486 is an error, returns the error, otherwise returns false.
3490 sub check_invoicing_list {
3491 my( $self, $arrayref ) = @_;
3493 foreach my $address ( @$arrayref ) {
3495 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3496 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3499 my $cust_main_invoice = new FS::cust_main_invoice ( {
3500 'custnum' => $self->custnum,
3503 my $error = $self->custnum
3504 ? $cust_main_invoice->check
3505 : $cust_main_invoice->checkdest
3507 return $error if $error;
3511 return "Email address required"
3512 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3513 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3518 =item set_default_invoicing_list
3520 Sets the invoicing list to all accounts associated with this customer,
3521 overwriting any previous invoicing list.
3525 sub set_default_invoicing_list {
3527 $self->invoicing_list($self->all_emails);
3532 Returns the email addresses of all accounts provisioned for this customer.
3539 foreach my $cust_pkg ( $self->all_pkgs ) {
3540 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3542 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3543 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3545 $list{$_}=1 foreach map { $_->email } @svc_acct;
3550 =item invoicing_list_addpost
3552 Adds postal invoicing to this customer. If this customer is already configured
3553 to receive postal invoices, does nothing.
3557 sub invoicing_list_addpost {
3559 return if grep { $_ eq 'POST' } $self->invoicing_list;
3560 my @invoicing_list = $self->invoicing_list;
3561 push @invoicing_list, 'POST';
3562 $self->invoicing_list(\@invoicing_list);
3565 =item invoicing_list_emailonly
3567 Returns the list of email invoice recipients (invoicing_list without non-email
3568 destinations such as POST and FAX).
3572 sub invoicing_list_emailonly {
3574 warn "$me invoicing_list_emailonly called"
3576 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3579 =item invoicing_list_emailonly_scalar
3581 Returns the list of email invoice recipients (invoicing_list without non-email
3582 destinations such as POST and FAX) as a comma-separated scalar.
3586 sub invoicing_list_emailonly_scalar {
3588 warn "$me invoicing_list_emailonly_scalar called"
3590 join(', ', $self->invoicing_list_emailonly);
3593 =item contact_list [ CLASSNUM, ... ]
3595 Returns a list of contacts (L<FS::contact> objects) for the customer. If
3596 a list of contact classnums is given, returns only contacts in those
3597 classes. If '0' is given, also returns contacts with no class.
3599 If no arguments are given, returns all contacts for the customer.
3607 select => 'contact.*',
3608 extra_sql => ' WHERE contact.custnum = '.$self->custnum,
3615 push @orwhere, 'contact.classnum is null';
3616 } elsif ( /^\d+$/ ) {
3617 push @classnums, $_;
3619 die "bad classnum argument '$_'";
3624 push @orwhere, 'contact.classnum IN ('.join(',', @classnums).')';
3627 $search->{extra_sql} .= ' AND (' .
3628 join(' OR ', map "( $_ )", @orwhere) .
3635 =item contact_list_email [ CLASSNUM, ... ]
3637 Same as L</contact_list>, but returns email destinations instead of contact
3638 objects. Also accepts 'invoice' as an argument, in which case this will also
3639 return the invoice email address if any.
3643 sub contact_list_email {
3651 push @classnums, $_;
3655 # if the only argument passed was 'invoice' then no classnums are
3656 # intended, so skip this.
3658 my @contacts = $self->contact_list(@classnums);
3659 foreach my $contact (@contacts) {
3660 foreach my $contact_email ($contact->contact_email) {
3661 # unlike on 4.x, we have a separate list of invoice email
3663 # make sure they're not redundant with contact emails
3664 $emails{ $contact_email->emailaddress } =
3665 Email::Address->new( $contact->firstlast,
3666 $contact_email->emailaddress
3671 if ( $and_invoice ) {
3672 foreach my $email ($self->invoicing_list_emailonly) {
3673 $emails{ $email } ||=
3674 Email::Address->new( $self->name_short, $email )->format;
3680 =item referral_custnum_cust_main
3682 Returns the customer who referred this customer (or the empty string, if
3683 this customer was not referred).
3685 Note the difference with referral_cust_main method: This method,
3686 referral_custnum_cust_main returns the single customer (if any) who referred
3687 this customer, while referral_cust_main returns an array of customers referred
3692 sub referral_custnum_cust_main {
3694 return '' unless $self->referral_custnum;
3695 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3698 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3700 Returns an array of customers referred by this customer (referral_custnum set
3701 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3702 customers referred by customers referred by this customer and so on, inclusive.
3703 The default behavior is DEPTH 1 (no recursion).
3705 Note the difference with referral_custnum_cust_main method: This method,
3706 referral_cust_main, returns an array of customers referred BY this customer,
3707 while referral_custnum_cust_main returns the single customer (if any) who
3708 referred this customer.
3712 sub referral_cust_main {
3714 my $depth = @_ ? shift : 1;
3715 my $exclude = @_ ? shift : {};
3718 map { $exclude->{$_->custnum}++; $_; }
3719 grep { ! $exclude->{ $_->custnum } }
3720 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3724 map { $_->referral_cust_main($depth-1, $exclude) }
3731 =item referral_cust_main_ncancelled
3733 Same as referral_cust_main, except only returns customers with uncancelled
3738 sub referral_cust_main_ncancelled {
3740 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3743 =item referral_cust_pkg [ DEPTH ]
3745 Like referral_cust_main, except returns a flat list of all unsuspended (and
3746 uncancelled) packages for each customer. The number of items in this list may
3747 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3751 sub referral_cust_pkg {
3753 my $depth = @_ ? shift : 1;
3755 map { $_->unsuspended_pkgs }
3756 grep { $_->unsuspended_pkgs }
3757 $self->referral_cust_main($depth);
3760 =item referring_cust_main
3762 Returns the single cust_main record for the customer who referred this customer
3763 (referral_custnum), or false.
3767 sub referring_cust_main {
3769 return '' unless $self->referral_custnum;
3770 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3773 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3775 Applies a credit to this customer. If there is an error, returns the error,
3776 otherwise returns false.
3778 REASON can be a text string, an FS::reason object, or a scalar reference to
3779 a reasonnum. If a text string, it will be automatically inserted as a new
3780 reason, and a 'reason_type' option must be passed to indicate the
3781 FS::reason_type for the new reason.
3783 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3784 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3785 I<commission_pkgnum>.
3787 Any other options are passed to FS::cust_credit::insert.
3792 my( $self, $amount, $reason, %options ) = @_;
3794 my $cust_credit = new FS::cust_credit {
3795 'custnum' => $self->custnum,
3796 'amount' => $amount,
3799 if ( ref($reason) ) {
3801 if ( ref($reason) eq 'SCALAR' ) {
3802 $cust_credit->reasonnum( $$reason );
3804 $cust_credit->reasonnum( $reason->reasonnum );
3808 $cust_credit->set('reason', $reason)
3811 $cust_credit->$_( delete $options{$_} )
3812 foreach grep exists($options{$_}),
3813 qw( addlinfo eventnum ),
3814 map "commission_$_", qw( agentnum salesnum pkgnum );
3816 $cust_credit->insert(%options);
3820 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3822 Creates a one-time charge for this customer. If there is an error, returns
3823 the error, otherwise returns false.
3825 New-style, with a hashref of options:
3827 my $error = $cust_main->charge(
3831 'start_date' => str2time('7/4/2009'),
3832 'pkg' => 'Description',
3833 'comment' => 'Comment',
3834 'additional' => [], #extra invoice detail
3835 'classnum' => 1, #pkg_class
3837 'setuptax' => '', # or 'Y' for tax exempt
3839 'locationnum'=> 1234, # optional
3842 'taxclass' => 'Tax class',
3845 'taxproduct' => 2, #part_pkg_taxproduct
3846 'override' => {}, #XXX describe
3848 #will be filled in with the new object
3849 'cust_pkg_ref' => \$cust_pkg,
3851 #generate an invoice immediately
3853 'invoice_terms' => '', #with these terms
3859 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3863 #super false laziness w/quotation::charge
3866 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3867 my ( $pkg, $comment, $additional );
3868 my ( $setuptax, $taxclass ); #internal taxes
3869 my ( $taxproduct, $override ); #vendor (CCH) taxes
3871 my $separate_bill = '';
3872 my $cust_pkg_ref = '';
3873 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3875 if ( ref( $_[0] ) ) {
3876 $amount = $_[0]->{amount};
3877 $setup_cost = $_[0]->{setup_cost};
3878 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3879 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3880 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3881 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3882 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3883 : '$'. sprintf("%.2f",$amount);
3884 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3885 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3886 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3887 $additional = $_[0]->{additional} || [];
3888 $taxproduct = $_[0]->{taxproductnum};
3889 $override = { '' => $_[0]->{tax_override} };
3890 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3891 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3892 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3893 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3894 $separate_bill = $_[0]->{separate_bill} || '';
3900 $pkg = @_ ? shift : 'One-time charge';
3901 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3903 $taxclass = @_ ? shift : '';
3907 local $SIG{HUP} = 'IGNORE';
3908 local $SIG{INT} = 'IGNORE';
3909 local $SIG{QUIT} = 'IGNORE';
3910 local $SIG{TERM} = 'IGNORE';
3911 local $SIG{TSTP} = 'IGNORE';
3912 local $SIG{PIPE} = 'IGNORE';
3914 my $oldAutoCommit = $FS::UID::AutoCommit;
3915 local $FS::UID::AutoCommit = 0;
3918 my $part_pkg = new FS::part_pkg ( {
3920 'comment' => $comment,
3924 'classnum' => ( $classnum ? $classnum : '' ),
3925 'setuptax' => $setuptax,
3926 'taxclass' => $taxclass,
3927 'taxproductnum' => $taxproduct,
3928 'setup_cost' => $setup_cost,
3931 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3932 ( 0 .. @$additional - 1 )
3934 'additional_count' => scalar(@$additional),
3935 'setup_fee' => $amount,
3938 my $error = $part_pkg->insert( options => \%options,
3939 tax_overrides => $override,
3942 $dbh->rollback if $oldAutoCommit;
3946 my $pkgpart = $part_pkg->pkgpart;
3947 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3948 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3949 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3950 $error = $type_pkgs->insert;
3952 $dbh->rollback if $oldAutoCommit;
3957 my $cust_pkg = new FS::cust_pkg ( {
3958 'custnum' => $self->custnum,
3959 'pkgpart' => $pkgpart,
3960 'quantity' => $quantity,
3961 'start_date' => $start_date,
3962 'no_auto' => $no_auto,
3963 'separate_bill' => $separate_bill,
3964 'locationnum'=> $locationnum,
3967 $error = $cust_pkg->insert;
3969 $dbh->rollback if $oldAutoCommit;
3971 } elsif ( $cust_pkg_ref ) {
3972 ${$cust_pkg_ref} = $cust_pkg;
3976 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3977 'pkg_list' => [ $cust_pkg ],
3980 $dbh->rollback if $oldAutoCommit;
3985 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3990 #=item charge_postal_fee
3992 #Applies a one time charge this customer. If there is an error,
3993 #returns the error, returns the cust_pkg charge object or false
3994 #if there was no charge.
3998 # This should be a customer event. For that to work requires that bill
3999 # also be a customer event.
4001 sub charge_postal_fee {
4004 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
4005 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4007 my $cust_pkg = new FS::cust_pkg ( {
4008 'custnum' => $self->custnum,
4009 'pkgpart' => $pkgpart,
4013 my $error = $cust_pkg->insert;
4014 $error ? $error : $cust_pkg;
4017 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4019 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4021 Optionally, a list or hashref of additional arguments to the qsearch call can
4028 my $opt = ref($_[0]) ? shift : { @_ };
4030 #return $self->num_cust_bill unless wantarray || keys %$opt;
4032 $opt->{'table'} = 'cust_bill';
4033 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4034 $opt->{'hashref'}{'custnum'} = $self->custnum;
4035 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
4037 map { $_ } #behavior of sort undefined in scalar context
4038 sort { $a->_date <=> $b->_date }
4042 =item open_cust_bill
4044 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4049 sub open_cust_bill {
4053 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
4059 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4061 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
4065 sub legacy_cust_bill {
4068 #return $self->num_legacy_cust_bill unless wantarray;
4070 map { $_ } #behavior of sort undefined in scalar context
4071 sort { $a->_date <=> $b->_date }
4072 qsearch({ 'table' => 'legacy_cust_bill',
4073 'hashref' => { 'custnum' => $self->custnum, },
4074 'order_by' => 'ORDER BY _date ASC',
4078 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4080 Returns all the statements (see L<FS::cust_statement>) for this customer.
4082 Optionally, a list or hashref of additional arguments to the qsearch call can
4087 =item cust_bill_void
4089 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
4093 sub cust_bill_void {
4096 map { $_ } #return $self->num_cust_bill_void unless wantarray;
4097 sort { $a->_date <=> $b->_date }
4098 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
4101 sub cust_statement {
4103 my $opt = ref($_[0]) ? shift : { @_ };
4105 #return $self->num_cust_statement unless wantarray || keys %$opt;
4107 $opt->{'table'} = 'cust_statement';
4108 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4109 $opt->{'hashref'}{'custnum'} = $self->custnum;
4110 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
4112 map { $_ } #behavior of sort undefined in scalar context
4113 sort { $a->_date <=> $b->_date }
4117 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
4119 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
4121 Optionally, a list or hashref of additional arguments to the qsearch call can
4122 be passed following the SVCDB.
4129 if ( ! $svcdb =~ /^svc_\w+$/ ) {
4130 warn "$me svc_x requires a svcdb";
4133 my $opt = ref($_[0]) ? shift : { @_ };
4135 $opt->{'table'} = $svcdb;
4136 $opt->{'addl_from'} =
4137 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
4138 ($opt->{'addl_from'} || '');
4140 my $custnum = $self->custnum;
4141 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
4142 my $where = "cust_pkg.custnum = $custnum";
4144 my $extra_sql = $opt->{'extra_sql'} || '';
4145 if ( keys %{ $opt->{'hashref'} } ) {
4146 $extra_sql = " AND $where $extra_sql";
4149 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
4150 $extra_sql = "WHERE $where AND $1";
4153 $extra_sql = "WHERE $where $extra_sql";
4156 $opt->{'extra_sql'} = $extra_sql;
4161 # required for use as an eventtable;
4164 $self->svc_x('svc_acct', @_);
4169 Returns all the credits (see L<FS::cust_credit>) for this customer.
4175 map { $_ } #return $self->num_cust_credit unless wantarray;
4176 sort { $a->_date <=> $b->_date }
4177 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4180 =item cust_credit_pkgnum
4182 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
4183 package when using experimental package balances.
4187 sub cust_credit_pkgnum {
4188 my( $self, $pkgnum ) = @_;
4189 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
4190 sort { $a->_date <=> $b->_date }
4191 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
4192 'pkgnum' => $pkgnum,
4197 =item cust_credit_void
4199 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
4203 sub cust_credit_void {
4206 sort { $a->_date <=> $b->_date }
4207 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
4212 Returns all the payments (see L<FS::cust_pay>) for this customer.
4218 my $opt = ref($_[0]) ? shift : { @_ };
4220 return $self->num_cust_pay unless wantarray || keys %$opt;
4222 $opt->{'table'} = 'cust_pay';
4223 $opt->{'hashref'}{'custnum'} = $self->custnum;
4225 map { $_ } #behavior of sort undefined in scalar context
4226 sort { $a->_date <=> $b->_date }
4233 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
4234 called automatically when the cust_pay method is used in a scalar context.
4240 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
4241 my $sth = dbh->prepare($sql) or die dbh->errstr;
4242 $sth->execute($self->custnum) or die $sth->errstr;
4243 $sth->fetchrow_arrayref->[0];
4246 =item unapplied_cust_pay
4248 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
4252 sub unapplied_cust_pay {
4256 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
4262 =item cust_pay_pkgnum
4264 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
4265 package when using experimental package balances.
4269 sub cust_pay_pkgnum {
4270 my( $self, $pkgnum ) = @_;
4271 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
4272 sort { $a->_date <=> $b->_date }
4273 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
4274 'pkgnum' => $pkgnum,
4281 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4287 map { $_ } #return $self->num_cust_pay_void unless wantarray;
4288 sort { $a->_date <=> $b->_date }
4289 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4292 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
4294 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
4296 Optionally, a list or hashref of additional arguments to the qsearch call can
4301 sub cust_pay_batch {
4303 my $opt = ref($_[0]) ? shift : { @_ };
4305 #return $self->num_cust_statement unless wantarray || keys %$opt;
4307 $opt->{'table'} = 'cust_pay_batch';
4308 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
4309 $opt->{'hashref'}{'custnum'} = $self->custnum;
4310 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
4312 map { $_ } #behavior of sort undefined in scalar context
4313 sort { $a->paybatchnum <=> $b->paybatchnum }
4317 =item cust_pay_pending
4319 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
4320 (without status "done").
4324 sub cust_pay_pending {
4326 return $self->num_cust_pay_pending unless wantarray;
4327 sort { $a->_date <=> $b->_date }
4328 qsearch( 'cust_pay_pending', {
4329 'custnum' => $self->custnum,
4330 'status' => { op=>'!=', value=>'done' },
4335 =item cust_pay_pending_attempt
4337 Returns all payment attempts / declined payments for this customer, as pending
4338 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
4339 a corresponding payment (see L<FS::cust_pay>).
4343 sub cust_pay_pending_attempt {
4345 return $self->num_cust_pay_pending_attempt unless wantarray;
4346 sort { $a->_date <=> $b->_date }
4347 qsearch( 'cust_pay_pending', {
4348 'custnum' => $self->custnum,
4355 =item num_cust_pay_pending
4357 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4358 customer (without status "done"). Also called automatically when the
4359 cust_pay_pending method is used in a scalar context.
4363 sub num_cust_pay_pending {
4366 " SELECT COUNT(*) FROM cust_pay_pending ".
4367 " WHERE custnum = ? AND status != 'done' ",
4372 =item num_cust_pay_pending_attempt
4374 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4375 customer, with status "done" but without a corresp. Also called automatically when the
4376 cust_pay_pending method is used in a scalar context.
4380 sub num_cust_pay_pending_attempt {
4383 " SELECT COUNT(*) FROM cust_pay_pending ".
4384 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4391 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4397 map { $_ } #return $self->num_cust_refund unless wantarray;
4398 sort { $a->_date <=> $b->_date }
4399 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4402 =item display_custnum
4404 Returns the displayed customer number for this customer: agent_custid if
4405 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4409 sub display_custnum {
4412 return $self->agent_custid
4413 if $default_agent_custid && $self->agent_custid;
4415 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4419 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
4420 } elsif ( $custnum_display_length ) {
4421 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
4423 return $self->custnum;
4429 Returns a name string for this customer, either "Company (Last, First)" or
4436 my $name = $self->contact;
4437 $name = $self->company. " ($name)" if $self->company;
4441 =item service_contact
4443 Returns the L<FS::contact> object for this customer that has the 'Service'
4444 contact class, or undef if there is no such contact. Deprecated; don't use
4449 sub service_contact {
4451 if ( !exists($self->{service_contact}) ) {
4452 my $classnum = $self->scalar_sql(
4453 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4454 ) || 0; #if it's zero, qsearchs will return nothing
4455 $self->{service_contact} = qsearchs('contact', {
4456 'classnum' => $classnum, 'custnum' => $self->custnum
4459 $self->{service_contact};
4464 Returns a name string for this (service/shipping) contact, either
4465 "Company (Last, First)" or "Last, First".
4472 my $name = $self->ship_contact;
4473 $name = $self->company. " ($name)" if $self->company;
4479 Returns a name string for this customer, either "Company" or "First Last".
4485 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4488 =item ship_name_short
4490 Returns a name string for this (service/shipping) contact, either "Company"
4495 sub ship_name_short {
4497 $self->service_contact
4498 ? $self->ship_contact_firstlast
4504 Returns this customer's full (billing) contact name only, "Last, First"
4510 $self->get('last'). ', '. $self->first;
4515 Returns this customer's full (shipping) contact name only, "Last, First"
4521 my $contact = $self->service_contact || $self;
4522 $contact->get('last') . ', ' . $contact->get('first');
4525 =item contact_firstlast
4527 Returns this customers full (billing) contact name only, "First Last".
4531 sub contact_firstlast {
4533 $self->first. ' '. $self->get('last');
4536 =item ship_contact_firstlast
4538 Returns this customer's full (shipping) contact name only, "First Last".
4542 sub ship_contact_firstlast {
4544 my $contact = $self->service_contact || $self;
4545 $contact->get('first') . ' '. $contact->get('last');
4548 sub bill_country_full {
4550 $self->bill_location->country_full;
4553 sub ship_country_full {
4555 $self->ship_location->country_full;
4558 =item county_state_county [ PREFIX ]
4560 Returns a string consisting of just the county, state and country.
4564 sub county_state_country {
4567 if ( @_ && $_[0] && $self->has_ship_address ) {
4568 $locationnum = $self->ship_locationnum;
4570 $locationnum = $self->bill_locationnum;
4572 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4573 $cust_location->county_state_country;
4576 =item geocode DATA_VENDOR
4578 Returns a value for the customer location as encoded by DATA_VENDOR.
4579 Currently this only makes sense for "CCH" as DATA_VENDOR.
4587 Returns a status string for this customer, currently:
4591 =item prospect - No packages have ever been ordered
4593 =item ordered - Recurring packages all are new (not yet billed).
4595 =item active - One or more recurring packages is active
4597 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4599 =item suspended - All non-cancelled recurring packages are suspended
4601 =item cancelled - All recurring packages are cancelled
4605 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4606 cust_main-status_module configuration option.
4610 sub status { shift->cust_status(@_); }
4614 return $self->hashref->{cust_status} if $self->hashref->{cust_status};
4615 for my $status ( FS::cust_main->statuses() ) {
4616 my $method = $status.'_sql';
4617 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4618 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4619 $sth->execute( ($self->custnum) x $numnum )
4620 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4621 if ( $sth->fetchrow_arrayref->[0] ) {
4622 $self->hashref->{cust_status} = $status;
4628 =item is_status_delay_cancel
4630 Returns true if customer status is 'suspended'
4631 and all suspended cust_pkg return true for
4632 cust_pkg->is_status_delay_cancel.
4634 This is not a real status, this only meant for hacking display
4635 values, because otherwise treating the customer as suspended is
4636 really the whole point of the delay_cancel option.
4640 sub is_status_delay_cancel {
4642 return 0 unless $self->status eq 'suspended';
4643 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4644 return 0 unless $cust_pkg->is_status_delay_cancel;
4649 =item ucfirst_cust_status
4651 =item ucfirst_status
4653 Returns the status with the first character capitalized.
4657 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4659 sub ucfirst_cust_status {
4661 ucfirst($self->cust_status);
4666 Returns a hex triplet color string for this customer's status.
4670 sub statuscolor { shift->cust_statuscolor(@_); }
4672 sub cust_statuscolor {
4674 __PACKAGE__->statuscolors->{$self->cust_status};
4677 =item tickets [ STATUS ]
4679 Returns an array of hashes representing the customer's RT tickets.
4681 An optional status (or arrayref or hashref of statuses) may be specified.
4687 my $status = ( @_ && $_[0] ) ? shift : '';
4689 my $num = $conf->config('cust_main-max_tickets') || 10;
4692 if ( $conf->config('ticket_system') ) {
4693 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4695 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4704 foreach my $priority (
4705 $conf->config('ticket_system-custom_priority_field-values'), ''
4707 last if scalar(@tickets) >= $num;
4709 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4710 $num - scalar(@tickets),
4721 =item appointments [ STATUS ]
4723 Returns an array of hashes representing the customer's RT tickets which
4730 my $status = ( @_ && $_[0] ) ? shift : '';
4732 return () unless $conf->config('ticket_system');
4734 my $queueid = $conf->config('ticket_system-appointment-queueid');
4736 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4745 # Return services representing svc_accts in customer support packages
4746 sub support_services {
4748 my %packages = map { $_ => 1 } $conf->config('support_packages');
4750 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4751 grep { $_->part_svc->svcdb eq 'svc_acct' }
4752 map { $_->cust_svc }
4753 grep { exists $packages{ $_->pkgpart } }
4754 $self->ncancelled_pkgs;
4758 # Return a list of latitude/longitude for one of the services (if any)
4759 sub service_coordinates {
4763 grep { $_->latitude && $_->longitude }
4765 map { $_->cust_svc }
4766 $self->ncancelled_pkgs;
4768 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4773 Returns a masked version of the named field
4778 my ($self,$field) = @_;
4782 'x'x(length($self->getfield($field))-4).
4783 substr($self->getfield($field), (length($self->getfield($field))-4));
4787 =item payment_history
4789 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4790 cust_credit and cust_refund objects. Each hashref has the following fields:
4792 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4794 I<date> - value of _date field, unix timestamp
4796 I<date_pretty> - user-friendly date
4798 I<description> - user-friendly description of item
4800 I<amount> - impact of item on user's balance
4801 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4802 Not to be confused with the native 'amount' field in cust_credit, see below.
4804 I<amount_pretty> - includes money char
4806 I<balance> - customer balance, chronologically as of this item
4808 I<balance_pretty> - includes money char
4810 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4812 I<paid> - amount paid for cust_pay records, undef for other types
4814 I<credit> - amount credited for cust_credit records, undef for other types.
4815 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4817 I<refund> - amount refunded for cust_refund records, undef for other types
4819 The four table-specific keys always have positive values, whether they reflect charges or payments.
4821 The following options may be passed to this method:
4823 I<line_items> - if true, returns charges ('Line item') rather than invoices
4825 I<start_date> - unix timestamp, only include records on or after.
4826 If specified, an item of type 'Previous' will also be included.
4827 It does not have table-specific fields.
4829 I<end_date> - unix timestamp, only include records before
4831 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4833 I<conf> - optional already-loaded FS::Conf object.
4837 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4838 # and also for sending customer statements, which should both be kept customer-friendly.
4839 # If you add anything that shouldn't be passed on through the API or exposed
4840 # to customers, add a new option to include it, don't include it by default
4841 sub payment_history {
4843 my $opt = ref($_[0]) ? $_[0] : { @_ };
4845 my $conf = $$opt{'conf'} || new FS::Conf;
4846 my $money_char = $conf->config("money_char") || '$',
4848 #first load entire history,
4849 #need previous to calculate previous balance
4850 #loading after end_date shouldn't hurt too much?
4852 if ( $$opt{'line_items'} ) {
4854 foreach my $cust_bill ( $self->cust_bill ) {
4857 'type' => 'Line item',
4858 'description' => $_->desc( $self->locale ).
4859 ( $_->sdate && $_->edate
4860 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4861 ' To '. time2str('%d-%b-%Y', $_->edate)
4864 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4865 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4866 'date' => $cust_bill->_date,
4867 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4869 foreach $cust_bill->cust_bill_pkg;
4876 'type' => 'Invoice',
4877 'description' => 'Invoice #'. $_->display_invnum,
4878 'amount' => sprintf('%.2f', $_->charged ),
4879 'charged' => sprintf('%.2f', $_->charged ),
4880 'date' => $_->_date,
4881 'date_pretty' => $self->time2str_local('short', $_->_date ),
4883 foreach $self->cust_bill;
4888 'type' => 'Payment',
4889 'description' => 'Payment', #XXX type
4890 'amount' => sprintf('%.2f', 0 - $_->paid ),
4891 'paid' => sprintf('%.2f', $_->paid ),
4892 'date' => $_->_date,
4893 'date_pretty' => $self->time2str_local('short', $_->_date ),
4895 foreach $self->cust_pay;
4899 'description' => 'Credit', #more info?
4900 'amount' => sprintf('%.2f', 0 -$_->amount ),
4901 'credit' => sprintf('%.2f', $_->amount ),
4902 'date' => $_->_date,
4903 'date_pretty' => $self->time2str_local('short', $_->_date ),
4905 foreach $self->cust_credit;
4909 'description' => 'Refund', #more info? type, like payment?
4910 'amount' => $_->refund,
4911 'refund' => $_->refund,
4912 'date' => $_->_date,
4913 'date_pretty' => $self->time2str_local('short', $_->_date ),
4915 foreach $self->cust_refund;
4917 #put it all in chronological order
4918 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4920 #calculate balance, filter items outside date range
4924 foreach my $item (@history) {
4925 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4926 $balance += $$item{'amount'};
4927 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4928 $previous += $$item{'amount'};
4931 $$item{'balance'} = sprintf("%.2f",$balance);
4932 foreach my $key ( qw(amount balance) ) {
4933 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4938 # start with previous balance, if there was one
4941 'type' => 'Previous',
4942 'description' => 'Previous balance',
4943 'amount' => sprintf("%.2f",$previous),
4944 'balance' => sprintf("%.2f",$previous),
4945 'date' => $$opt{'start_date'},
4946 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4948 #false laziness with above
4949 foreach my $key ( qw(amount balance) ) {
4950 $$item{$key.'_pretty'} = $$item{$key};
4951 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4953 unshift(@out,$item);
4956 @out = reverse @history if $$opt{'reverse_sort'};
4963 =head1 CLASS METHODS
4969 Class method that returns the list of possible status strings for customers
4970 (see L<the status method|/status>). For example:
4972 @statuses = FS::cust_main->statuses();
4978 keys %{ $self->statuscolors };
4981 =item cust_status_sql
4983 Returns an SQL fragment to determine the status of a cust_main record, as a
4988 sub cust_status_sql {
4990 for my $status ( FS::cust_main->statuses() ) {
4991 my $method = $status.'_sql';
4992 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
5001 Returns an SQL expression identifying prospective cust_main records (customers
5002 with no packages ever ordered)
5006 use vars qw($select_count_pkgs);
5007 $select_count_pkgs =
5008 "SELECT COUNT(*) FROM cust_pkg
5009 WHERE cust_pkg.custnum = cust_main.custnum";
5011 sub select_count_pkgs_sql {
5016 " 0 = ( $select_count_pkgs ) ";
5021 Returns an SQL expression identifying ordered cust_main records (customers with
5022 no active packages, but recurring packages not yet setup or one time charges
5028 FS::cust_main->none_active_sql.
5029 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
5034 Returns an SQL expression identifying active cust_main records (customers with
5035 active recurring packages).
5040 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
5043 =item none_active_sql
5045 Returns an SQL expression identifying cust_main records with no active
5046 recurring packages. This includes customers of status prospect, ordered,
5047 inactive, and suspended.
5051 sub none_active_sql {
5052 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
5057 Returns an SQL expression identifying inactive cust_main records (customers with
5058 no active recurring packages, but otherwise unsuspended/uncancelled).
5063 FS::cust_main->none_active_sql.
5064 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
5070 Returns an SQL expression identifying suspended cust_main records.
5075 sub suspended_sql { susp_sql(@_); }
5077 FS::cust_main->none_active_sql.
5078 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
5084 Returns an SQL expression identifying cancelled cust_main records.
5088 sub cancel_sql { shift->cancelled_sql(@_); }
5091 =item uncancelled_sql
5093 Returns an SQL expression identifying un-cancelled cust_main records.
5097 sub uncancelled_sql { uncancel_sql(@_); }
5100 "( NOT (".$self->cancelled_sql.") )"; #sensitive to cust_main-status_module
5105 Returns an SQL fragment to retreive the balance.
5110 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5111 WHERE cust_bill.custnum = cust_main.custnum )
5112 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
5113 WHERE cust_pay.custnum = cust_main.custnum )
5114 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
5115 WHERE cust_credit.custnum = cust_main.custnum )
5116 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
5117 WHERE cust_refund.custnum = cust_main.custnum )
5120 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
5122 Returns an SQL fragment to retreive the balance for this customer, optionally
5123 considering invoices with date earlier than START_TIME, and not
5124 later than END_TIME (total_owed_date minus total_unapplied_credits minus
5125 total_unapplied_payments).
5127 Times are specified as SQL fragments or numeric
5128 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5129 L<Date::Parse> for conversion functions. The empty string can be passed
5130 to disable that time constraint completely.
5132 Available options are:
5136 =item unapplied_date
5138 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)
5143 set to true to remove all customer comparison clauses, for totals
5148 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5153 JOIN clause (typically used with the total option)
5157 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
5158 time will be ignored. Note that START_TIME and END_TIME only limit the date
5159 range for invoices and I<unapplied> payments, credits, and refunds.
5165 sub balance_date_sql {
5166 my( $class, $start, $end, %opt ) = @_;
5168 my $cutoff = $opt{'cutoff'};
5170 my $owed = FS::cust_bill->owed_sql($cutoff);
5171 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
5172 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
5173 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5175 my $j = $opt{'join'} || '';
5177 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
5178 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5179 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5180 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
5182 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
5183 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5184 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5185 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
5190 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
5192 Returns an SQL fragment to retreive the total unapplied payments for this
5193 customer, only considering payments with date earlier than START_TIME, and
5194 optionally not later than END_TIME.
5196 Times are specified as SQL fragments or numeric
5197 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
5198 L<Date::Parse> for conversion functions. The empty string can be passed
5199 to disable that time constraint completely.
5201 Available options are:
5205 sub unapplied_payments_date_sql {
5206 my( $class, $start, $end, %opt ) = @_;
5208 my $cutoff = $opt{'cutoff'};
5210 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
5212 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
5213 'unapplied_date'=>1 );
5215 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
5218 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5220 Helper method for balance_date_sql; name (and usage) subject to change
5221 (suggestions welcome).
5223 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5224 cust_refund, cust_credit or cust_pay).
5226 If TABLE is "cust_bill" or the unapplied_date option is true, only
5227 considers records with date earlier than START_TIME, and optionally not
5228 later than END_TIME .
5232 sub _money_table_where {
5233 my( $class, $table, $start, $end, %opt ) = @_;
5236 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5237 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5238 push @where, "$table._date <= $start" if defined($start) && length($start);
5239 push @where, "$table._date > $end" if defined($end) && length($end);
5241 push @where, @{$opt{'where'}} if $opt{'where'};
5242 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5248 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
5249 use FS::cust_main::Search;
5252 FS::cust_main::Search->search(@_);
5261 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5263 Deprecated. Use event notification and message templates
5264 (L<FS::msg_template>) instead.
5266 Sends a templated email notification to the customer (see L<Text::Template>).
5268 OPTIONS is a hash and may include
5270 I<from> - the email sender (default is invoice_from)
5272 I<to> - comma-separated scalar or arrayref of recipients
5273 (default is invoicing_list)
5275 I<subject> - The subject line of the sent email notification
5276 (default is "Notice from company_name")
5278 I<extra_fields> - a hashref of name/value pairs which will be substituted
5281 The following variables are vavailable in the template.
5283 I<$first> - the customer first name
5284 I<$last> - the customer last name
5285 I<$company> - the customer company
5286 I<$payby> - a description of the method of payment for the customer
5287 # would be nice to use FS::payby::shortname
5288 I<$payinfo> - the account information used to collect for this customer
5289 I<$expdate> - the expiration of the customer payment in seconds from epoch
5294 my ($self, $template, %options) = @_;
5296 return unless $conf->exists($template);
5298 my $from = $conf->invoice_from_full($self->agentnum)
5299 if $conf->exists('invoice_from', $self->agentnum);
5300 $from = $options{from} if exists($options{from});
5302 my $to = join(',', $self->invoicing_list_emailonly);
5303 $to = $options{to} if exists($options{to});
5305 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5306 if $conf->exists('company_name', $self->agentnum);
5307 $subject = $options{subject} if exists($options{subject});
5309 my $notify_template = new Text::Template (TYPE => 'ARRAY',
5310 SOURCE => [ map "$_\n",
5311 $conf->config($template)]
5313 or die "can't create new Text::Template object: Text::Template::ERROR";
5314 $notify_template->compile()
5315 or die "can't compile template: Text::Template::ERROR";
5317 $FS::notify_template::_template::company_name =
5318 $conf->config('company_name', $self->agentnum);
5319 $FS::notify_template::_template::company_address =
5320 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5322 my $paydate = $self->paydate || '2037-12-31';
5323 $FS::notify_template::_template::first = $self->first;
5324 $FS::notify_template::_template::last = $self->last;
5325 $FS::notify_template::_template::company = $self->company;
5326 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5327 my $payby = $self->payby;
5328 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5329 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5331 #credit cards expire at the end of the month/year of their exp date
5332 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5333 $FS::notify_template::_template::payby = 'credit card';
5334 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5335 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5337 }elsif ($payby eq 'COMP') {
5338 $FS::notify_template::_template::payby = 'complimentary account';
5340 $FS::notify_template::_template::payby = 'current method';
5342 $FS::notify_template::_template::expdate = $expire_time;
5344 for (keys %{$options{extra_fields}}){
5346 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5349 send_email(from => $from,
5351 subject => $subject,
5352 body => $notify_template->fill_in( PACKAGE =>
5353 'FS::notify_template::_template' ),
5358 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5360 Generates a templated notification to the customer (see L<Text::Template>).
5362 OPTIONS is a hash and may include
5364 I<extra_fields> - a hashref of name/value pairs which will be substituted
5365 into the template. These values may override values mentioned below
5366 and those from the customer record.
5368 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5370 The following variables are available in the template instead of or in addition
5371 to the fields of the customer record.
5373 I<$payby> - a description of the method of payment for the customer
5374 # would be nice to use FS::payby::shortname
5375 I<$payinfo> - the masked account information used to collect for this customer
5376 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5377 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5381 # a lot like cust_bill::print_latex
5382 sub generate_letter {
5383 my ($self, $template, %options) = @_;
5385 warn "Template $template does not exist" && return
5386 unless $conf->exists($template) || $options{'template_text'};
5388 my $template_source = $options{'template_text'}
5389 ? [ $options{'template_text'} ]
5390 : [ map "$_\n", $conf->config($template) ];
5392 my $letter_template = new Text::Template
5394 SOURCE => $template_source,
5395 DELIMITERS => [ '[@--', '--@]' ],
5397 or die "can't create new Text::Template object: Text::Template::ERROR";
5399 $letter_template->compile()
5400 or die "can't compile template: Text::Template::ERROR";
5402 my %letter_data = map { $_ => $self->$_ } $self->fields;
5403 $letter_data{payinfo} = $self->mask_payinfo;
5405 #my $paydate = $self->paydate || '2037-12-31';
5406 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5408 my $payby = $self->payby;
5409 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5410 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5412 #credit cards expire at the end of the month/year of their exp date
5413 if ($payby eq 'CARD' || $payby eq 'DCRD') {
5414 $letter_data{payby} = 'credit card';
5415 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5416 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5418 }elsif ($payby eq 'COMP') {
5419 $letter_data{payby} = 'complimentary account';
5421 $letter_data{payby} = 'current method';
5423 $letter_data{expdate} = $expire_time;
5425 for (keys %{$options{extra_fields}}){
5426 $letter_data{$_} = $options{extra_fields}->{$_};
5429 unless(exists($letter_data{returnaddress})){
5430 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5431 $self->agent_template)
5433 if ( length($retadd) ) {
5434 $letter_data{returnaddress} = $retadd;
5435 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5436 $letter_data{returnaddress} =
5437 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5441 ( $conf->config('company_name', $self->agentnum),
5442 $conf->config('company_address', $self->agentnum),
5446 $letter_data{returnaddress} = '~';
5450 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5452 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5454 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5456 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5460 ) or die "can't open temp file: $!\n";
5461 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5462 or die "can't write temp file: $!\n";
5464 $letter_data{'logo_file'} = $lh->filename;
5466 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5470 ) or die "can't open temp file: $!\n";
5472 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5474 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5475 return ($1, $letter_data{'logo_file'});
5479 =item print_ps TEMPLATE
5481 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5487 my($file, $lfile) = $self->generate_letter(@_);
5488 my $ps = FS::Misc::generate_ps($file);
5489 unlink($file.'.tex');
5495 =item print TEMPLATE
5497 Prints the filled in template.
5499 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5503 sub queueable_print {
5506 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5507 or die "invalid customer number: " . $opt{custnum};
5509 my $error = $self->print( { 'template' => $opt{template} } );
5510 die $error if $error;
5514 my ($self, $template) = (shift, shift);
5516 [ $self->print_ps($template) ],
5517 'agentnum' => $self->agentnum,
5521 #these three subs should just go away once agent stuff is all config overrides
5523 sub agent_template {
5525 $self->_agent_plandata('agent_templatename');
5528 sub agent_invoice_from {
5530 $self->_agent_plandata('agent_invoice_from');
5533 sub _agent_plandata {
5534 my( $self, $option ) = @_;
5536 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5537 #agent-specific Conf
5539 use FS::part_event::Condition;
5541 my $agentnum = $self->agentnum;
5543 my $regexp = regexp_sql();
5545 my $part_event_option =
5547 'select' => 'part_event_option.*',
5548 'table' => 'part_event_option',
5550 LEFT JOIN part_event USING ( eventpart )
5551 LEFT JOIN part_event_option AS peo_agentnum
5552 ON ( part_event.eventpart = peo_agentnum.eventpart
5553 AND peo_agentnum.optionname = 'agentnum'
5554 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5556 LEFT JOIN part_event_condition
5557 ON ( part_event.eventpart = part_event_condition.eventpart
5558 AND part_event_condition.conditionname = 'cust_bill_age'
5560 LEFT JOIN part_event_condition_option
5561 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5562 AND part_event_condition_option.optionname = 'age'
5565 #'hashref' => { 'optionname' => $option },
5566 #'hashref' => { 'part_event_option.optionname' => $option },
5568 " WHERE part_event_option.optionname = ". dbh->quote($option).
5569 " AND action = 'cust_bill_send_agent' ".
5570 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5571 " AND peo_agentnum.optionname = 'agentnum' ".
5572 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5574 CASE WHEN part_event_condition_option.optionname IS NULL
5576 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5578 , part_event.weight".
5582 unless ( $part_event_option ) {
5583 return $self->agent->invoice_template || ''
5584 if $option eq 'agent_templatename';
5588 $part_event_option->optionvalue;
5592 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5594 Subroutine (not a method), designed to be called from the queue.
5596 Takes a list of options and values.
5598 Pulls up the customer record via the custnum option and calls bill_and_collect.
5603 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5605 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5606 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5608 #without this errors don't get rolled back
5609 $args{'fatal'} = 1; # runs from job queue, will be caught
5611 $cust_main->bill_and_collect( %args );
5614 sub process_bill_and_collect {
5616 my $param = thaw(decode_base64(shift));
5617 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5618 or die "custnum '$param->{custnum}' not found!\n";
5619 $param->{'job'} = $job;
5620 $param->{'fatal'} = 1; # runs from job queue, will be caught
5621 $param->{'retry'} = 1;
5623 $cust_main->bill_and_collect( %$param );
5626 #starting to take quite a while for big dbs
5627 # (JRNL: journaled so it only happens once per database)
5628 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5629 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5630 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5631 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5632 # JRNL leading/trailing spaces in first, last, company
5633 # - otaker upgrade? journal and call it good? (double check to make sure
5634 # we're not still setting otaker here)
5636 #only going to get worse with new location stuff...
5638 sub _upgrade_data { #class method
5639 my ($class, %opts) = @_;
5642 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5645 #this seems to be the only expensive one.. why does it take so long?
5646 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5648 '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';
5649 FS::upgrade_journal->set_done('cust_main__signupdate');
5652 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5654 # fix yyyy-m-dd formatted paydates
5655 if ( driver_name =~ /^mysql/i ) {
5657 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5658 } else { # the SQL standard
5660 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5662 FS::upgrade_journal->set_done('cust_main__paydate');
5665 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5667 push @statements, #fix the weird BILL with a cc# in payinfo problem
5669 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5671 FS::upgrade_journal->set_done('cust_main__payinfo');
5676 foreach my $sql ( @statements ) {
5677 my $sth = dbh->prepare($sql) or die dbh->errstr;
5678 $sth->execute or die $sth->errstr;
5679 #warn ( (time - $t). " seconds\n" );
5683 local($ignore_expired_card) = 1;
5684 local($ignore_banned_card) = 1;
5685 local($skip_fuzzyfiles) = 1;
5686 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5688 FS::cust_main::Location->_upgrade_data(%opts);
5690 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5692 foreach my $cust_main ( qsearch({
5693 'table' => 'cust_main',
5695 'extra_sql' => 'WHERE '.
5697 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5698 qw( first last company )
5701 my $error = $cust_main->replace;
5702 die $error if $error;
5705 FS::upgrade_journal->set_done('cust_main__trimspaces');
5709 $class->_upgrade_otaker(%opts);
5711 # turn on encryption as part of regular upgrade, so all new records are immediately encrypted
5712 # existing records will be encrypted in queueable_upgrade (below)
5713 unless ($conf->exists('encryptionpublickey') || $conf->exists('encryptionprivatekey')) {
5714 eval "use FS::Setup";
5716 FS::Setup::enable_encryption();
5719 $class->_upgrade_data_paydate_edgebug;
5722 =item _upgrade_data_paydate_edgebug
5724 Correct bad data injected into payment expire date column by Edge browser bug
5726 The month and year values may have an extra character injected into form POST
5727 data by Edge browser. It was possible for some bad month values to slip
5728 past data validation.
5730 If the stored value was out of range, it was causing payments screen to crash.
5731 We can detect and fix this by dropping the second digit.
5733 If the stored value is is 11 or 12, it's possible the user inputted a 1. In
5734 this case, the payment method will fail to authorize, but the record will
5735 not cause crashdumps for being out of range.
5737 In short, check for any expiration month > 12, and drop the extra digit
5741 sub _upgrade_data_paydate_edgebug {
5742 my $journal_label = 'cust_main_paydate_edgebug';
5743 return if FS::upgrade_journal->is_done( $journal_label );
5745 my $oldAutoCommit = $FS::UID::AutoCommit;
5746 local $FS::UID::AutoCommit = 0;
5749 FS::Record::qsearch(
5750 cust_main => { paydate => { op => '!=', value => '' }}
5753 next unless $row->ut_daten('paydate');
5755 # paydate column stored in database has failed date validation
5756 my $bad_paydate = $row->paydate;
5758 my @date = split /[\-\/]/, $bad_paydate;
5759 @date = @date[2,0,1] if $date[2] > 1900;
5761 # Only autocorrecting when month > 12 - notify operator
5762 unless ( $date[1] > 12 ) {
5764 'Unable to correct bad paydate stored in cust_main row '.
5765 'custnum(%s) paydate(%s)',
5771 $date[1] = substr( $date[1], 0, 1 );
5772 $row->paydate( join('-', @date ));
5774 if ( my $error = $row->replace ) {
5776 'Failed to autocorrect bad paydate stored in cust_main row '.
5777 'custnum(%s) paydate(%s) - error: %s',
5785 'Autocorrected bad paydate stored in cust_main row '.
5786 "custnum(%s) old-paydate(%s) new-paydate(%s)\n",
5794 FS::upgrade_journal->set_done( $journal_label );
5795 dbh->commit unless $oldAutoCommit;
5799 sub queueable_upgrade {
5802 ### encryption gets turned on in _upgrade_data, above
5804 eval "use FS::upgrade_journal";
5807 # prior to 2013 (commit f16665c9) payinfo was stored in history if not encrypted,
5808 # clear that out before encrypting/tokenizing anything else
5809 if (!FS::upgrade_journal->is_done('clear_payinfo_history')) {
5810 foreach my $table ('cust_main','cust_pay_pending','cust_pay','cust_pay_void','cust_refund') {
5811 my $sql = 'UPDATE h_'.$table.' SET payinfo = NULL WHERE payinfo IS NOT NULL';
5812 my $sth = dbh->prepare($sql) or die dbh->errstr;
5813 $sth->execute or die $sth->errstr;
5815 FS::upgrade_journal->set_done('clear_payinfo_history');
5818 # fix Tokenized paycardtype and encrypt old records
5819 if ( ! FS::upgrade_journal->is_done('paycardtype_Tokenized')
5820 || ! FS::upgrade_journal->is_done('encryption_check')
5824 # allow replacement of closed cust_pay/cust_refund records
5825 local $FS::payinfo_Mixin::allow_closed_replace = 1;
5827 # because it looks like nothing's changing
5828 local $FS::Record::no_update_diff = 1;
5830 # commit everything immediately
5831 local $FS::UID::AutoCommit = 1;
5833 # encrypt what's there
5834 foreach my $table ('cust_main','cust_pay_pending','cust_pay','cust_pay_void','cust_refund') {
5835 my $tclass = 'FS::'.$table;
5838 while (my $recnum = _upgrade_next_recnum(dbh,$table,\$lastrecnum,\@recnums)) {
5839 my $record = $tclass->by_key($recnum);
5840 next unless $record; # small chance it's been deleted, that's ok
5841 next unless grep { $record->payby eq $_ } @FS::Record::encrypt_payby;
5842 # window for possible conflict is practically nonexistant,
5843 # but just in case...
5844 $record = $record->select_for_update;
5845 if (!$record->custnum && $table eq 'cust_pay_pending') {
5846 $record->set('custnum_pending',1);
5848 $record->paycardtype('') if $record->paycardtype eq 'Tokenized';
5850 local($ignore_expired_card) = 1;
5851 local($ignore_banned_card) = 1;
5852 local($skip_fuzzyfiles) = 1;
5853 local($import) = 1;#prevent automatic geocoding (need its own variable?)
5855 my $error = $record->replace;
5856 die "Error replacing $table ".$record->get($record->primary_key).": $error" if $error;
5860 FS::upgrade_journal->set_done('paycardtype_Tokenized');
5861 FS::upgrade_journal->set_done('encryption_check') if $conf->exists('encryption');
5866 # not entirely false laziness w/ Billing_Realtime::_token_check_next_recnum
5867 # cust_payby might get deleted while this runs
5869 sub _upgrade_next_recnum {
5870 my ($dbh,$table,$lastrecnum,$recnums) = @_;
5871 my $recnum = shift @$recnums;
5872 return $recnum if $recnum;
5873 my $tclass = 'FS::'.$table;
5874 my $paycardtypecheck = ($table ne 'cust_pay_pending') ? q( OR paycardtype = 'Tokenized') : '';
5875 my $sql = 'SELECT '.$tclass->primary_key.
5877 ' WHERE '.$tclass->primary_key.' > '.$$lastrecnum.
5878 " AND payby IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
5879 " AND ( length(payinfo) < 80$paycardtypecheck ) ".
5880 ' ORDER BY '.$tclass->primary_key.' LIMIT 500';
5881 my $sth = $dbh->prepare($sql) or die $dbh->errstr;
5882 $sth->execute() or die $sth->errstr;
5884 while (my $rec = $sth->fetchrow_hashref) {
5885 push @$recnums, $rec->{$tclass->primary_key};
5888 $$lastrecnum = $$recnums[-1];
5889 return shift @$recnums;
5898 The delete method should possibly take an FS::cust_main object reference
5899 instead of a scalar customer number.
5901 Bill and collect options should probably be passed as references instead of a
5904 There should probably be a configuration file with a list of allowed credit
5907 No multiple currency support (probably a larger project than just this module).
5909 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5911 Birthdates rely on negative epoch values.
5913 The payby for card/check batches is broken. With mixed batching, bad
5916 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5920 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5921 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5922 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.