2 use base qw( FS::cust_main::Packages
4 FS::cust_main::NationalID
6 FS::cust_main::Billing_Realtime
7 FS::cust_main::Billing_Batch
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
14 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
15 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
23 use Scalar::Util qw( blessed );
24 use Time::Local qw(timelocal);
29 use File::Temp; #qw( tempfile );
30 use Business::CreditCard 0.28;
32 use FS::UID qw( dbh driver_name );
33 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
35 use FS::Misc qw( generate_ps do_print money_pretty );
36 use FS::Msgcat qw(gettext);
43 use FS::cust_bill_void;
44 use FS::legacy_cust_bill;
46 use FS::cust_pay_pending;
47 use FS::cust_pay_void;
48 use FS::cust_pay_batch;
51 use FS::part_referral;
52 use FS::cust_main_county;
53 use FS::cust_location;
56 use FS::cust_main_exemption;
57 use FS::cust_tax_adjustment;
58 use FS::cust_tax_location;
59 use FS::agent_currency;
60 use FS::cust_main_invoice;
62 use FS::prepay_credit;
68 use FS::payment_gateway;
69 use FS::agent_payment_gateway;
71 use FS::cust_main_note;
72 use FS::cust_attachment;
75 use FS::upgrade_journal;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 our $me = '[FS::cust_main]';
87 our $ignore_expired_card = 0;
88 our $ignore_banned_card = 0;
89 our $ignore_invalid_card = 0;
91 our $skip_fuzzyfiles = 0;
93 our $ucfirst_nowarn = 0;
95 #this info is in cust_payby as of 4.x
96 #this and the fields themselves can be removed in 5.x
97 our @encrypted_fields = ('payinfo', 'paycvv');
98 sub nohistory_fields { ('payinfo', 'paycvv'); }
101 #ask FS::UID to run this stuff for us later
102 #$FS::UID::callback{'FS::cust_main'} = sub {
103 install_callback FS::UID sub {
104 $conf = new FS::Conf;
105 #yes, need it for stuff below (prolly should be cached)
106 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
111 my ( $hashref, $cache ) = @_;
112 if ( exists $hashref->{'pkgnum'} ) {
113 #@{ $self->{'_pkgnum'} } = ();
114 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
115 $self->{'_pkgnum'} = $subcache;
116 #push @{ $self->{'_pkgnum'} },
117 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
123 FS::cust_main - Object methods for cust_main records
129 $record = new FS::cust_main \%hash;
130 $record = new FS::cust_main { 'column' => 'value' };
132 $error = $record->insert;
134 $error = $new_record->replace($old_record);
136 $error = $record->delete;
138 $error = $record->check;
140 @cust_pkg = $record->all_pkgs;
142 @cust_pkg = $record->ncancelled_pkgs;
144 @cust_pkg = $record->suspended_pkgs;
146 $error = $record->bill;
147 $error = $record->bill %options;
148 $error = $record->bill 'time' => $time;
150 $error = $record->collect;
151 $error = $record->collect %options;
152 $error = $record->collect 'invoice_time' => $time,
157 An FS::cust_main object represents a customer. FS::cust_main inherits from
158 FS::Record. The following fields are currently supported:
164 Primary key (assigned automatically for new customers)
168 Agent (see L<FS::agent>)
172 Advertising source (see L<FS::part_referral>)
184 Cocial security number (optional)
208 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
212 Payment Information (See L<FS::payinfo_Mixin> for data format)
216 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
220 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
224 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
228 Start date month (maestro/solo cards only)
232 Start date year (maestro/solo cards only)
236 Issue number (maestro/solo cards only)
240 Name on card or billing name
244 IP address from which payment information was received
248 Tax exempt, empty or `Y'
252 Order taker (see L<FS::access_user>)
258 =item referral_custnum
260 Referring customer number
264 Enable individual CDR spooling, empty or `Y'
268 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
272 Discourage individual CDR printing, empty or `Y'
276 Allow self-service editing of ticket subjects, empty or 'Y'
278 =item calling_list_exempt
280 Do not call, empty or 'Y'
282 =item invoice_ship_address
284 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
294 Creates a new customer. To add the customer to the database, see L<"insert">.
296 Note that this stores the hash reference, not a distinct copy of the hash it
297 points to. You can ask the object for a copy with the I<hash> method.
301 sub table { 'cust_main'; }
303 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
305 Adds this customer to the database. If there is an error, returns the error,
306 otherwise returns false.
308 Usually the customer's location will not yet exist in the database, and
309 the C<bill_location> and C<ship_location> pseudo-fields must be set to
310 uninserted L<FS::cust_location> objects. These will be inserted and linked
311 (in both directions) to the new customer record. If they're references
312 to the same object, they will become the same location.
314 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
315 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
316 are inserted atomicly, or the transaction is rolled back. Passing an empty
317 hash reference is equivalent to not supplying this parameter. There should be
318 a better explanation of this, but until then, here's an example:
321 tie %hash, 'Tie::RefHash'; #this part is important
323 $cust_pkg => [ $svc_acct ],
326 $cust_main->insert( \%hash );
328 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
329 be set as the invoicing list (see L<"invoicing_list">). Errors return as
330 expected and rollback the entire transaction; it is not necessary to call
331 check_invoicing_list first. The invoicing_list is set after the records in the
332 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
333 invoicing_list destination to the newly-created svc_acct. Here's an example:
335 $cust_main->insert( {}, [ $email, 'POST' ] );
337 Currently available options are: I<depend_jobnum>, I<noexport>,
338 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
340 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
341 on the supplied jobnum (they will not run until the specific job completes).
342 This can be used to defer provisioning until some action completes (such
343 as running the customer's credit card successfully).
345 The I<noexport> option is deprecated. If I<noexport> is set true, no
346 provisioning jobs (exports) are scheduled. (You can schedule them later with
347 the B<reexport> method.)
349 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
350 of tax names and exemption numbers. FS::cust_main_exemption records will be
351 created and inserted.
353 If I<prospectnum> is set, moves contacts and locations from that prospect.
355 If I<contact> is set to an arrayref of FS::contact objects, inserts those
356 new contacts with this new customer.
358 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
359 unset), inserts those new contacts with this new customer. Handles CGI
360 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
362 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
363 new stored payment records with this new customer. Handles CGI parameters
364 for an "m2" multiple entry field as passed by edit/cust_main.cgi
370 my $cust_pkgs = @_ ? shift : {};
371 my $invoicing_list = @_ ? shift : '';
373 warn "$me insert called with options ".
374 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
377 local $SIG{HUP} = 'IGNORE';
378 local $SIG{INT} = 'IGNORE';
379 local $SIG{QUIT} = 'IGNORE';
380 local $SIG{TERM} = 'IGNORE';
381 local $SIG{TSTP} = 'IGNORE';
382 local $SIG{PIPE} = 'IGNORE';
384 my $oldAutoCommit = $FS::UID::AutoCommit;
385 local $FS::UID::AutoCommit = 0;
388 my $prepay_identifier = '';
389 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
391 if ( $self->payby eq 'PREPAY' ) {
393 $self->payby(''); #'BILL');
394 $prepay_identifier = $self->payinfo;
397 warn " looking up prepaid card $prepay_identifier\n"
400 my $error = $self->get_prepay( $prepay_identifier,
401 'amount_ref' => \$amount,
402 'seconds_ref' => \$seconds,
403 'upbytes_ref' => \$upbytes,
404 'downbytes_ref' => \$downbytes,
405 'totalbytes_ref' => \$totalbytes,
408 $dbh->rollback if $oldAutoCommit;
409 #return "error applying prepaid card (transaction rolled back): $error";
413 $payby = 'PREP' if $amount;
415 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
418 $self->payby(''); #'BILL');
419 $amount = $self->paid;
424 foreach my $l (qw(bill_location ship_location)) {
426 my $loc = delete $self->hashref->{$l} or next;
428 if ( !$loc->locationnum ) {
429 # warn the location that we're going to insert it with no custnum
430 $loc->set(custnum_pending => 1);
431 warn " inserting $l\n"
433 my $error = $loc->insert;
435 $dbh->rollback if $oldAutoCommit;
436 my $label = $l eq 'ship_location' ? 'service' : 'billing';
437 return "$error (in $label location)";
440 } elsif ( $loc->prospectnum ) {
442 $loc->prospectnum('');
443 $loc->set(custnum_pending => 1);
444 my $error = $loc->replace;
446 $dbh->rollback if $oldAutoCommit;
447 my $label = $l eq 'ship_location' ? 'service' : 'billing';
448 return "$error (moving $label location)";
451 } elsif ( ($loc->custnum || 0) > 0 ) {
452 # then it somehow belongs to another customer--shouldn't happen
453 $dbh->rollback if $oldAutoCommit;
454 return "$l belongs to customer ".$loc->custnum;
456 # else it already belongs to this customer
457 # (happens when ship_location is identical to bill_location)
459 $self->set($l.'num', $loc->locationnum);
461 if ( $self->get($l.'num') eq '' ) {
462 $dbh->rollback if $oldAutoCommit;
467 warn " inserting $self\n"
470 $self->signupdate(time) unless $self->signupdate;
472 $self->auto_agent_custid()
473 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
475 my $error = $self->SUPER::insert;
477 $dbh->rollback if $oldAutoCommit;
478 #return "inserting cust_main record (transaction rolled back): $error";
482 # now set cust_location.custnum
483 foreach my $l (qw(bill_location ship_location)) {
484 warn " setting $l.custnum\n"
486 my $loc = $self->$l or next;
487 unless ( $loc->custnum ) {
488 $loc->set(custnum => $self->custnum);
489 $error ||= $loc->replace;
493 $dbh->rollback if $oldAutoCommit;
494 return "error setting $l custnum: $error";
498 warn " setting invoicing list\n"
501 if ( $invoicing_list ) {
502 $error = $self->check_invoicing_list( $invoicing_list );
504 $dbh->rollback if $oldAutoCommit;
505 #return "checking invoicing_list (transaction rolled back): $error";
508 $self->invoicing_list( $invoicing_list );
511 warn " setting customer tags\n"
514 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
515 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
516 'custnum' => $self->custnum };
517 my $error = $cust_tag->insert;
519 $dbh->rollback if $oldAutoCommit;
524 my $prospectnum = delete $options{'prospectnum'};
525 if ( $prospectnum ) {
527 warn " moving contacts and locations from prospect $prospectnum\n"
531 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
532 unless ( $prospect_main ) {
533 $dbh->rollback if $oldAutoCommit;
534 return "Unknown prospectnum $prospectnum";
536 $prospect_main->custnum($self->custnum);
537 $prospect_main->disabled('Y');
538 my $error = $prospect_main->replace;
540 $dbh->rollback if $oldAutoCommit;
544 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
545 my $cust_contact = new FS::cust_contact {
546 'custnum' => $self->custnum,
547 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
549 my $error = $cust_contact->insert
550 || $prospect_contact->delete;
552 $dbh->rollback if $oldAutoCommit;
557 my @cust_location = $prospect_main->cust_location;
558 my @qual = $prospect_main->qual;
560 foreach my $r ( @cust_location, @qual ) {
562 $r->custnum($self->custnum);
563 my $error = $r->replace;
565 $dbh->rollback if $oldAutoCommit;
572 warn " setting contacts\n"
575 if ( my $contact = delete $options{'contact'} ) {
577 foreach my $c ( @$contact ) {
578 $c->custnum($self->custnum);
579 my $error = $c->insert;
581 $dbh->rollback if $oldAutoCommit;
587 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
589 my $error = $self->process_o2m( 'table' => 'contact',
590 'fields' => FS::contact->cgi_contact_fields,
591 'params' => $contact_params,
594 $dbh->rollback if $oldAutoCommit;
599 warn " setting cust_payby\n"
602 if ( $options{cust_payby} ) {
604 foreach my $cust_payby ( @{ $options{cust_payby} } ) {
605 $cust_payby->custnum($self->custnum);
606 my $error = $cust_payby->insert;
608 $dbh->rollback if $oldAutoCommit;
613 } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
615 my $error = $self->process_o2m(
616 'table' => 'cust_payby',
617 'fields' => FS::cust_payby->cgi_cust_payby_fields,
618 'params' => $cust_payby_params,
619 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
622 $dbh->rollback if $oldAutoCommit;
628 warn " setting cust_main_exemption\n"
631 my $tax_exemption = delete $options{'tax_exemption'};
632 if ( $tax_exemption ) {
634 $tax_exemption = { map { $_ => '' } @$tax_exemption }
635 if ref($tax_exemption) eq 'ARRAY';
637 foreach my $taxname ( keys %$tax_exemption ) {
638 my $cust_main_exemption = new FS::cust_main_exemption {
639 'custnum' => $self->custnum,
640 'taxname' => $taxname,
641 'exempt_number' => $tax_exemption->{$taxname},
643 my $error = $cust_main_exemption->insert;
645 $dbh->rollback if $oldAutoCommit;
646 return "inserting cust_main_exemption (transaction rolled back): $error";
651 warn " ordering packages\n"
654 $error = $self->order_pkgs( $cust_pkgs,
656 'seconds_ref' => \$seconds,
657 'upbytes_ref' => \$upbytes,
658 'downbytes_ref' => \$downbytes,
659 'totalbytes_ref' => \$totalbytes,
662 $dbh->rollback if $oldAutoCommit;
667 $dbh->rollback if $oldAutoCommit;
668 return "No svc_acct record to apply pre-paid time";
670 if ( $upbytes || $downbytes || $totalbytes ) {
671 $dbh->rollback if $oldAutoCommit;
672 return "No svc_acct record to apply pre-paid data";
676 warn " inserting initial $payby payment of $amount\n"
678 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
680 $dbh->rollback if $oldAutoCommit;
681 return "inserting payment (transaction rolled back): $error";
685 unless ( $import || $skip_fuzzyfiles ) {
686 warn " queueing fuzzyfiles update\n"
688 $error = $self->queue_fuzzyfiles_update;
690 $dbh->rollback if $oldAutoCommit;
691 return "updating fuzzy search cache: $error";
695 # FS::geocode_Mixin::after_insert or something?
696 if ( $conf->config('tax_district_method') and !$import ) {
697 # if anything non-empty, try to look it up
698 my $queue = new FS::queue {
699 'job' => 'FS::geocode_Mixin::process_district_update',
700 'custnum' => $self->custnum,
702 my $error = $queue->insert( ref($self), $self->custnum );
704 $dbh->rollback if $oldAutoCommit;
705 return "queueing tax district update: $error";
710 warn " exporting\n" if $DEBUG > 1;
712 my $export_args = $options{'export_args'} || [];
715 map qsearch( 'part_export', {exportnum=>$_} ),
716 $conf->config('cust_main-exports'); #, $agentnum
718 foreach my $part_export ( @part_export ) {
719 my $error = $part_export->export_insert($self, @$export_args);
721 $dbh->rollback if $oldAutoCommit;
722 return "exporting to ". $part_export->exporttype.
723 " (transaction rolled back): $error";
727 #foreach my $depend_jobnum ( @$depend_jobnums ) {
728 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
730 # foreach my $jobnum ( @jobnums ) {
731 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
732 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
734 # my $error = $queue->depend_insert($depend_jobnum);
736 # $dbh->rollback if $oldAutoCommit;
737 # return "error queuing job dependancy: $error";
744 #if ( exists $options{'jobnums'} ) {
745 # push @{ $options{'jobnums'} }, @jobnums;
748 warn " insert complete; committing transaction\n"
751 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
756 use File::CounterFile;
757 sub auto_agent_custid {
760 my $format = $conf->config('cust_main-auto_agent_custid');
762 if ( $format eq '1YMMXXXXXXXX' ) {
764 my $counter = new File::CounterFile 'cust_main.agent_custid';
767 my $ym = 100000000000 + time2str('%y%m00000000', time);
768 if ( $ym > $counter->value ) {
769 $counter->{'value'} = $agent_custid = $ym;
770 $counter->{'updated'} = 1;
772 $agent_custid = $counter->inc;
778 die "Unknown cust_main-auto_agent_custid format: $format";
781 $self->agent_custid($agent_custid);
785 =item PACKAGE METHODS
787 Documentation on customer package methods has been moved to
788 L<FS::cust_main::Packages>.
790 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
792 Recharges this (existing) customer with the specified prepaid card (see
793 L<FS::prepay_credit>), specified either by I<identifier> or as an
794 FS::prepay_credit object. If there is an error, returns the error, otherwise
797 Optionally, five scalar references can be passed as well. They will have their
798 values filled in with the amount, number of seconds, and number of upload,
799 download, and total bytes applied by this prepaid card.
803 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
804 #the only place that uses these args
805 sub recharge_prepay {
806 my( $self, $prepay_credit, $amountref, $secondsref,
807 $upbytesref, $downbytesref, $totalbytesref ) = @_;
809 local $SIG{HUP} = 'IGNORE';
810 local $SIG{INT} = 'IGNORE';
811 local $SIG{QUIT} = 'IGNORE';
812 local $SIG{TERM} = 'IGNORE';
813 local $SIG{TSTP} = 'IGNORE';
814 local $SIG{PIPE} = 'IGNORE';
816 my $oldAutoCommit = $FS::UID::AutoCommit;
817 local $FS::UID::AutoCommit = 0;
820 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
822 my $error = $self->get_prepay( $prepay_credit,
823 'amount_ref' => \$amount,
824 'seconds_ref' => \$seconds,
825 'upbytes_ref' => \$upbytes,
826 'downbytes_ref' => \$downbytes,
827 'totalbytes_ref' => \$totalbytes,
829 || $self->increment_seconds($seconds)
830 || $self->increment_upbytes($upbytes)
831 || $self->increment_downbytes($downbytes)
832 || $self->increment_totalbytes($totalbytes)
833 || $self->insert_cust_pay_prepay( $amount,
835 ? $prepay_credit->identifier
840 $dbh->rollback if $oldAutoCommit;
844 if ( defined($amountref) ) { $$amountref = $amount; }
845 if ( defined($secondsref) ) { $$secondsref = $seconds; }
846 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
847 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
848 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
850 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
855 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
857 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
858 specified either by I<identifier> or as an FS::prepay_credit object.
860 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
861 incremented by the values of the prepaid card.
863 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
864 check or set this customer's I<agentnum>.
866 If there is an error, returns the error, otherwise returns false.
872 my( $self, $prepay_credit, %opt ) = @_;
874 local $SIG{HUP} = 'IGNORE';
875 local $SIG{INT} = 'IGNORE';
876 local $SIG{QUIT} = 'IGNORE';
877 local $SIG{TERM} = 'IGNORE';
878 local $SIG{TSTP} = 'IGNORE';
879 local $SIG{PIPE} = 'IGNORE';
881 my $oldAutoCommit = $FS::UID::AutoCommit;
882 local $FS::UID::AutoCommit = 0;
885 unless ( ref($prepay_credit) ) {
887 my $identifier = $prepay_credit;
889 $prepay_credit = qsearchs(
891 { 'identifier' => $identifier },
896 unless ( $prepay_credit ) {
897 $dbh->rollback if $oldAutoCommit;
898 return "Invalid prepaid card: ". $identifier;
903 if ( $prepay_credit->agentnum ) {
904 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
905 $dbh->rollback if $oldAutoCommit;
906 return "prepaid card not valid for agent ". $self->agentnum;
908 $self->agentnum($prepay_credit->agentnum);
911 my $error = $prepay_credit->delete;
913 $dbh->rollback if $oldAutoCommit;
914 return "removing prepay_credit (transaction rolled back): $error";
917 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
918 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
920 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
925 =item increment_upbytes SECONDS
927 Updates this customer's single or primary account (see L<FS::svc_acct>) by
928 the specified number of upbytes. If there is an error, returns the error,
929 otherwise returns false.
933 sub increment_upbytes {
934 _increment_column( shift, 'upbytes', @_);
937 =item increment_downbytes SECONDS
939 Updates this customer's single or primary account (see L<FS::svc_acct>) by
940 the specified number of downbytes. If there is an error, returns the error,
941 otherwise returns false.
945 sub increment_downbytes {
946 _increment_column( shift, 'downbytes', @_);
949 =item increment_totalbytes SECONDS
951 Updates this customer's single or primary account (see L<FS::svc_acct>) by
952 the specified number of totalbytes. If there is an error, returns the error,
953 otherwise returns false.
957 sub increment_totalbytes {
958 _increment_column( shift, 'totalbytes', @_);
961 =item increment_seconds SECONDS
963 Updates this customer's single or primary account (see L<FS::svc_acct>) by
964 the specified number of seconds. If there is an error, returns the error,
965 otherwise returns false.
969 sub increment_seconds {
970 _increment_column( shift, 'seconds', @_);
973 =item _increment_column AMOUNT
975 Updates this customer's single or primary account (see L<FS::svc_acct>) by
976 the specified number of seconds or bytes. If there is an error, returns
977 the error, otherwise returns false.
981 sub _increment_column {
982 my( $self, $column, $amount ) = @_;
983 warn "$me increment_column called: $column, $amount\n"
986 return '' unless $amount;
988 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
989 $self->ncancelled_pkgs;
992 return 'No packages with primary or single services found'.
993 ' to apply pre-paid time';
994 } elsif ( scalar(@cust_pkg) > 1 ) {
995 #maybe have a way to specify the package/account?
996 return 'Multiple packages found to apply pre-paid time';
999 my $cust_pkg = $cust_pkg[0];
1000 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1004 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1006 if ( ! @cust_svc ) {
1007 return 'No account found to apply pre-paid time';
1008 } elsif ( scalar(@cust_svc) > 1 ) {
1009 return 'Multiple accounts found to apply pre-paid time';
1012 my $svc_acct = $cust_svc[0]->svc_x;
1013 warn " found service svcnum ". $svc_acct->pkgnum.
1014 ' ('. $svc_acct->email. ")\n"
1017 $column = "increment_$column";
1018 $svc_acct->$column($amount);
1022 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1024 Inserts a prepayment in the specified amount for this customer. An optional
1025 second argument can specify the prepayment identifier for tracking purposes.
1026 If there is an error, returns the error, otherwise returns false.
1030 sub insert_cust_pay_prepay {
1031 shift->insert_cust_pay('PREP', @_);
1034 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1036 Inserts a cash payment in the specified amount for this customer. An optional
1037 second argument can specify the payment identifier for tracking purposes.
1038 If there is an error, returns the error, otherwise returns false.
1042 sub insert_cust_pay_cash {
1043 shift->insert_cust_pay('CASH', @_);
1046 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1048 Inserts a Western Union payment in the specified amount for this customer. An
1049 optional second argument can specify the prepayment identifier for tracking
1050 purposes. If there is an error, returns the error, otherwise returns false.
1054 sub insert_cust_pay_west {
1055 shift->insert_cust_pay('WEST', @_);
1058 sub insert_cust_pay {
1059 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1060 my $payinfo = scalar(@_) ? shift : '';
1062 my $cust_pay = new FS::cust_pay {
1063 'custnum' => $self->custnum,
1064 'paid' => sprintf('%.2f', $amount),
1065 #'_date' => #date the prepaid card was purchased???
1067 'payinfo' => $payinfo,
1073 =item delete [ OPTION => VALUE ... ]
1075 This deletes the customer. If there is an error, returns the error, otherwise
1078 This will completely remove all traces of the customer record. This is not
1079 what you want when a customer cancels service; for that, cancel all of the
1080 customer's packages (see L</cancel>).
1082 If the customer has any uncancelled packages, you need to pass a new (valid)
1083 customer number for those packages to be transferred to, as the "new_customer"
1084 option. Cancelled packages will be deleted. Did I mention that this is NOT
1085 what you want when a customer cancels service and that you really should be
1086 looking at L<FS::cust_pkg/cancel>?
1088 You can't delete a customer with invoices (see L<FS::cust_bill>),
1089 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1090 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1091 set the "delete_financials" option to a true value.
1096 my( $self, %opt ) = @_;
1098 local $SIG{HUP} = 'IGNORE';
1099 local $SIG{INT} = 'IGNORE';
1100 local $SIG{QUIT} = 'IGNORE';
1101 local $SIG{TERM} = 'IGNORE';
1102 local $SIG{TSTP} = 'IGNORE';
1103 local $SIG{PIPE} = 'IGNORE';
1105 my $oldAutoCommit = $FS::UID::AutoCommit;
1106 local $FS::UID::AutoCommit = 0;
1109 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1110 $dbh->rollback if $oldAutoCommit;
1111 return "Can't delete a master agent customer";
1114 #use FS::access_user
1115 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1116 $dbh->rollback if $oldAutoCommit;
1117 return "Can't delete a master employee customer";
1120 tie my %financial_tables, 'Tie::IxHash',
1121 'cust_bill' => 'invoices',
1122 'cust_statement' => 'statements',
1123 'cust_credit' => 'credits',
1124 'cust_pay' => 'payments',
1125 'cust_refund' => 'refunds',
1128 foreach my $table ( keys %financial_tables ) {
1130 my @records = $self->$table();
1132 if ( @records && ! $opt{'delete_financials'} ) {
1133 $dbh->rollback if $oldAutoCommit;
1134 return "Can't delete a customer with ". $financial_tables{$table};
1137 foreach my $record ( @records ) {
1138 my $error = $record->delete;
1140 $dbh->rollback if $oldAutoCommit;
1141 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1147 my @cust_pkg = $self->ncancelled_pkgs;
1149 my $new_custnum = $opt{'new_custnum'};
1150 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1151 $dbh->rollback if $oldAutoCommit;
1152 return "Invalid new customer number: $new_custnum";
1154 foreach my $cust_pkg ( @cust_pkg ) {
1155 my %hash = $cust_pkg->hash;
1156 $hash{'custnum'} = $new_custnum;
1157 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1158 my $error = $new_cust_pkg->replace($cust_pkg,
1159 options => { $cust_pkg->options },
1162 $dbh->rollback if $oldAutoCommit;
1167 my @cancelled_cust_pkg = $self->all_pkgs;
1168 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1169 my $error = $cust_pkg->delete;
1171 $dbh->rollback if $oldAutoCommit;
1176 #cust_tax_adjustment in financials?
1177 #cust_pay_pending? ouch
1178 foreach my $table (qw(
1179 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1180 cust_payby cust_location cust_main_note cust_tax_adjustment
1181 cust_pay_void cust_pay_batch queue cust_tax_exempt
1183 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1184 my $error = $record->delete;
1186 $dbh->rollback if $oldAutoCommit;
1192 my $sth = $dbh->prepare(
1193 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1195 my $errstr = $dbh->errstr;
1196 $dbh->rollback if $oldAutoCommit;
1199 $sth->execute($self->custnum) or do {
1200 my $errstr = $sth->errstr;
1201 $dbh->rollback if $oldAutoCommit;
1207 my $ticket_dbh = '';
1208 if ($conf->config('ticket_system') eq 'RT_Internal') {
1210 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1211 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1212 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1213 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1216 if ( $ticket_dbh ) {
1218 my $ticket_sth = $ticket_dbh->prepare(
1219 'DELETE FROM Links WHERE Target = ?'
1221 my $errstr = $ticket_dbh->errstr;
1222 $dbh->rollback if $oldAutoCommit;
1225 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1227 my $errstr = $ticket_sth->errstr;
1228 $dbh->rollback if $oldAutoCommit;
1232 #check and see if the customer is the only link on the ticket, and
1233 #if so, set the ticket to deleted status in RT?
1234 #maybe someday, for now this will at least fix tickets not displaying
1238 #delete the customer record
1240 my $error = $self->SUPER::delete;
1242 $dbh->rollback if $oldAutoCommit;
1246 # cust_main exports!
1248 #my $export_args = $options{'export_args'} || [];
1251 map qsearch( 'part_export', {exportnum=>$_} ),
1252 $conf->config('cust_main-exports'); #, $agentnum
1254 foreach my $part_export ( @part_export ) {
1255 my $error = $part_export->export_delete( $self ); #, @$export_args);
1257 $dbh->rollback if $oldAutoCommit;
1258 return "exporting to ". $part_export->exporttype.
1259 " (transaction rolled back): $error";
1263 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1268 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1270 Replaces the OLD_RECORD with this one in the database. If there is an error,
1271 returns the error, otherwise returns false.
1273 To change the customer's address, set the pseudo-fields C<bill_location> and
1274 C<ship_location>. The address will still only change if at least one of the
1275 address fields differs from the existing values.
1277 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1278 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1279 expected and rollback the entire transaction; it is not necessary to call
1280 check_invoicing_list first. Here's an example:
1282 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1284 Currently available options are: I<tax_exemption>.
1286 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1287 of tax names and exemption numbers. FS::cust_main_exemption records will be
1288 deleted and inserted as appropriate.
1295 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1297 : $self->replace_old;
1301 warn "$me replace called\n"
1304 my $curuser = $FS::CurrentUser::CurrentUser;
1305 return "You are not permitted to create complimentary accounts."
1306 if $self->complimentary eq 'Y'
1307 && $self->complimentary ne $old->complimentary
1308 && ! $curuser->access_right('Complimentary customer');
1310 local($ignore_expired_card) = 1
1311 if $old->payby =~ /^(CARD|DCRD)$/
1312 && $self->payby =~ /^(CARD|DCRD)$/
1313 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1315 local($ignore_banned_card) = 1
1316 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1317 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1318 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1320 return "Invoicing locale is required"
1323 && $conf->exists('cust_main-require_locale');
1325 local $SIG{HUP} = 'IGNORE';
1326 local $SIG{INT} = 'IGNORE';
1327 local $SIG{QUIT} = 'IGNORE';
1328 local $SIG{TERM} = 'IGNORE';
1329 local $SIG{TSTP} = 'IGNORE';
1330 local $SIG{PIPE} = 'IGNORE';
1332 my $oldAutoCommit = $FS::UID::AutoCommit;
1333 local $FS::UID::AutoCommit = 0;
1336 for my $l (qw(bill_location ship_location)) {
1337 #my $old_loc = $old->$l;
1338 my $new_loc = $self->$l or next;
1340 # find the existing location if there is one
1341 $new_loc->set('custnum' => $self->custnum);
1342 my $error = $new_loc->find_or_insert;
1344 $dbh->rollback if $oldAutoCommit;
1347 $self->set($l.'num', $new_loc->locationnum);
1350 # replace the customer record
1351 my $error = $self->SUPER::replace($old);
1354 $dbh->rollback if $oldAutoCommit;
1358 # now move packages to the new service location
1359 $self->set('ship_location', ''); #flush cache
1360 if ( $old->ship_locationnum and # should only be null during upgrade...
1361 $old->ship_locationnum != $self->ship_locationnum ) {
1362 $error = $old->ship_location->move_to($self->ship_location);
1364 $dbh->rollback if $oldAutoCommit;
1368 # don't move packages based on the billing location, but
1369 # disable it if it's no longer in use
1370 if ( $old->bill_locationnum and
1371 $old->bill_locationnum != $self->bill_locationnum ) {
1372 $error = $old->bill_location->disable_if_unused;
1374 $dbh->rollback if $oldAutoCommit;
1379 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1380 my $invoicing_list = shift @param;
1381 $error = $self->check_invoicing_list( $invoicing_list );
1383 $dbh->rollback if $oldAutoCommit;
1386 $self->invoicing_list( $invoicing_list );
1389 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1391 #this could be more efficient than deleting and re-inserting, if it matters
1392 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1393 my $error = $cust_tag->delete;
1395 $dbh->rollback if $oldAutoCommit;
1399 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1400 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1401 'custnum' => $self->custnum };
1402 my $error = $cust_tag->insert;
1404 $dbh->rollback if $oldAutoCommit;
1411 my %options = @param;
1413 my $tax_exemption = delete $options{'tax_exemption'};
1414 if ( $tax_exemption ) {
1416 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1417 if ref($tax_exemption) eq 'ARRAY';
1419 my %cust_main_exemption =
1420 map { $_->taxname => $_ }
1421 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1423 foreach my $taxname ( keys %$tax_exemption ) {
1425 if ( $cust_main_exemption{$taxname} &&
1426 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1429 delete $cust_main_exemption{$taxname};
1433 my $cust_main_exemption = new FS::cust_main_exemption {
1434 'custnum' => $self->custnum,
1435 'taxname' => $taxname,
1436 'exempt_number' => $tax_exemption->{$taxname},
1438 my $error = $cust_main_exemption->insert;
1440 $dbh->rollback if $oldAutoCommit;
1441 return "inserting cust_main_exemption (transaction rolled back): $error";
1445 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1446 my $error = $cust_main_exemption->delete;
1448 $dbh->rollback if $oldAutoCommit;
1449 return "deleting cust_main_exemption (transaction rolled back): $error";
1455 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1457 my $error = $self->process_o2m(
1458 'table' => 'cust_payby',
1459 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1460 'params' => $cust_payby_params,
1461 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1464 $dbh->rollback if $oldAutoCommit;
1470 unless ( $import || $skip_fuzzyfiles ) {
1471 $error = $self->queue_fuzzyfiles_update;
1473 $dbh->rollback if $oldAutoCommit;
1474 return "updating fuzzy search cache: $error";
1478 # tax district update in cust_location
1480 # cust_main exports!
1482 my $export_args = $options{'export_args'} || [];
1485 map qsearch( 'part_export', {exportnum=>$_} ),
1486 $conf->config('cust_main-exports'); #, $agentnum
1488 foreach my $part_export ( @part_export ) {
1489 my $error = $part_export->export_replace( $self, $old, @$export_args);
1491 $dbh->rollback if $oldAutoCommit;
1492 return "exporting to ". $part_export->exporttype.
1493 " (transaction rolled back): $error";
1497 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1502 =item queue_fuzzyfiles_update
1504 Used by insert & replace to update the fuzzy search cache
1508 use FS::cust_main::Search;
1509 sub queue_fuzzyfiles_update {
1512 local $SIG{HUP} = 'IGNORE';
1513 local $SIG{INT} = 'IGNORE';
1514 local $SIG{QUIT} = 'IGNORE';
1515 local $SIG{TERM} = 'IGNORE';
1516 local $SIG{TSTP} = 'IGNORE';
1517 local $SIG{PIPE} = 'IGNORE';
1519 my $oldAutoCommit = $FS::UID::AutoCommit;
1520 local $FS::UID::AutoCommit = 0;
1523 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1524 my $queue = new FS::queue {
1525 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1527 my @args = "cust_main.$field", $self->get($field);
1528 my $error = $queue->insert( @args );
1530 $dbh->rollback if $oldAutoCommit;
1531 return "queueing job (transaction rolled back): $error";
1536 push @locations, $self->bill_location if $self->bill_locationnum;
1537 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1538 foreach my $location (@locations) {
1539 my $queue = new FS::queue {
1540 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1542 my @args = 'cust_location.address1', $location->address1;
1543 my $error = $queue->insert( @args );
1545 $dbh->rollback if $oldAutoCommit;
1546 return "queueing job (transaction rolled back): $error";
1550 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1557 Checks all fields to make sure this is a valid customer record. If there is
1558 an error, returns the error, otherwise returns false. Called by the insert
1559 and replace methods.
1566 warn "$me check BEFORE: \n". $self->_dump
1570 $self->ut_numbern('custnum')
1571 || $self->ut_number('agentnum')
1572 || $self->ut_textn('agent_custid')
1573 || $self->ut_number('refnum')
1574 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1575 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1576 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1577 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1578 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1579 || $self->ut_textn('custbatch')
1580 || $self->ut_name('last')
1581 || $self->ut_name('first')
1582 || $self->ut_snumbern('signupdate')
1583 || $self->ut_snumbern('birthdate')
1584 || $self->ut_namen('spouse_last')
1585 || $self->ut_namen('spouse_first')
1586 || $self->ut_snumbern('spouse_birthdate')
1587 || $self->ut_snumbern('anniversary_date')
1588 || $self->ut_textn('company')
1589 || $self->ut_textn('ship_company')
1590 || $self->ut_anything('comments')
1591 || $self->ut_numbern('referral_custnum')
1592 || $self->ut_textn('stateid')
1593 || $self->ut_textn('stateid_state')
1594 || $self->ut_textn('invoice_terms')
1595 || $self->ut_floatn('cdr_termination_percentage')
1596 || $self->ut_floatn('credit_limit')
1597 || $self->ut_numbern('billday')
1598 || $self->ut_numbern('prorate_day')
1599 || $self->ut_flag('edit_subject')
1600 || $self->ut_flag('calling_list_exempt')
1601 || $self->ut_flag('invoice_noemail')
1602 || $self->ut_flag('message_noemail')
1603 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1604 || $self->ut_currencyn('currency')
1605 || $self->ut_alphan('po_number')
1606 || $self->ut_enum('complimentary', [ '', 'Y' ])
1607 || $self->ut_flag('invoice_ship_address')
1610 foreach (qw(company ship_company)) {
1611 my $company = $self->get($_);
1612 $company =~ s/^\s+//;
1613 $company =~ s/\s+$//;
1614 $company =~ s/\s+/ /g;
1615 $self->set($_, $company);
1618 #barf. need message catalogs. i18n. etc.
1619 $error .= "Please select an advertising source."
1620 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1621 return $error if $error;
1623 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1624 or return "Unknown agent";
1626 if ( $self->currency ) {
1627 my $agent_currency = qsearchs( 'agent_currency', {
1628 'agentnum' => $agent->agentnum,
1629 'currency' => $self->currency,
1631 or return "Agent ". $agent->agent.
1632 " not permitted to offer ". $self->currency. " invoicing";
1635 return "Unknown refnum"
1636 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1638 return "Unknown referring custnum: ". $self->referral_custnum
1639 unless ! $self->referral_custnum
1640 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1642 if ( $self->ss eq '' ) {
1647 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1648 or return "Illegal social security number: ". $self->ss;
1649 $self->ss("$1-$2-$3");
1652 #turn off invoice_ship_address if ship & bill are the same
1653 if ($self->bill_locationnum eq $self->ship_locationnum) {
1654 $self->invoice_ship_address('');
1657 # cust_main_county verification now handled by cust_location check
1660 $self->ut_phonen('daytime', $self->country)
1661 || $self->ut_phonen('night', $self->country)
1662 || $self->ut_phonen('fax', $self->country)
1663 || $self->ut_phonen('mobile', $self->country)
1665 return $error if $error;
1667 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1669 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1672 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1674 : FS::Msgcat::_gettext('daytime');
1675 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1677 : FS::Msgcat::_gettext('night');
1679 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1681 : FS::Msgcat::_gettext('mobile');
1683 return "$daytime_label, $night_label or $mobile_label is required"
1687 ### start of stuff moved to cust_payby
1688 # then mostly kept here to support upgrades (can remove in 5.x)
1689 # but modified to allow everything to be empty
1691 if ( $self->payby ) {
1692 FS::payby->can_payby($self->table, $self->payby)
1693 or return "Illegal payby: ". $self->payby;
1698 $error = $self->ut_numbern('paystart_month')
1699 || $self->ut_numbern('paystart_year')
1700 || $self->ut_numbern('payissue')
1701 || $self->ut_textn('paytype')
1703 return $error if $error;
1705 if ( $self->payip eq '' ) {
1708 $error = $self->ut_ip('payip');
1709 return $error if $error;
1712 # If it is encrypted and the private key is not availaible then we can't
1713 # check the credit card.
1714 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1716 # Need some kind of global flag to accept invalid cards, for testing
1718 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1719 $self->payby =~ /^(CARD|DCRD)$/ ) {
1721 my $payinfo = $self->payinfo;
1722 $payinfo =~ s/\D//g;
1723 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1724 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1726 $self->payinfo($payinfo);
1728 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1730 return gettext('unknown_card_type')
1731 if $self->payinfo !~ /^99\d{14}$/ #token
1732 && cardtype($self->payinfo) eq "Unknown";
1734 unless ( $ignore_banned_card ) {
1735 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1737 if ( $ban->bantype eq 'warn' ) {
1738 #or others depending on value of $ban->reason ?
1739 return '_duplicate_card'.
1740 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1741 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1742 ' (ban# '. $ban->bannum. ')'
1743 unless $self->override_ban_warn;
1745 return 'Banned credit card: banned on '.
1746 time2str('%a %h %o at %r', $ban->_date).
1747 ' by '. $ban->otaker.
1748 ' (ban# '. $ban->bannum. ')';
1753 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1754 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1755 $self->paycvv =~ /^(\d{4})$/
1756 or return "CVV2 (CID) for American Express cards is four digits.";
1759 $self->paycvv =~ /^(\d{3})$/
1760 or return "CVV2 (CVC2/CID) is three digits.";
1767 my $cardtype = cardtype($payinfo);
1768 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1770 return "Start date or issue number is required for $cardtype cards"
1771 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1773 return "Start month must be between 1 and 12"
1774 if $self->paystart_month
1775 and $self->paystart_month < 1 || $self->paystart_month > 12;
1777 return "Start year must be 1990 or later"
1778 if $self->paystart_year
1779 and $self->paystart_year < 1990;
1781 return "Issue number must be beween 1 and 99"
1783 and $self->payissue < 1 || $self->payissue > 99;
1786 $self->paystart_month('');
1787 $self->paystart_year('');
1788 $self->payissue('');
1791 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1792 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1794 my $payinfo = $self->payinfo;
1795 $payinfo =~ s/[^\d\@\.]//g;
1796 if ( $conf->config('echeck-country') eq 'CA' ) {
1797 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1798 or return 'invalid echeck account@branch.bank';
1799 $payinfo = "$1\@$2.$3";
1800 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1801 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1802 $payinfo = "$1\@$2";
1804 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1805 $payinfo = "$1\@$2";
1807 $self->payinfo($payinfo);
1810 unless ( $ignore_banned_card ) {
1811 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1813 if ( $ban->bantype eq 'warn' ) {
1814 #or others depending on value of $ban->reason ?
1815 return '_duplicate_ach' unless $self->override_ban_warn;
1817 return 'Banned ACH account: banned on '.
1818 time2str('%a %h %o at %r', $ban->_date).
1819 ' by '. $ban->otaker.
1820 ' (ban# '. $ban->bannum. ')';
1825 } elsif ( $self->payby eq 'LECB' ) {
1827 my $payinfo = $self->payinfo;
1828 $payinfo =~ s/\D//g;
1829 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1831 $self->payinfo($payinfo);
1834 } elsif ( $self->payby eq 'BILL' ) {
1836 $error = $self->ut_textn('payinfo');
1837 return "Illegal P.O. number: ". $self->payinfo if $error;
1840 } elsif ( $self->payby eq 'COMP' ) {
1842 my $curuser = $FS::CurrentUser::CurrentUser;
1843 if ( ! $self->custnum
1844 && ! $curuser->access_right('Complimentary customer')
1847 return "You are not permitted to create complimentary accounts."
1850 $error = $self->ut_textn('payinfo');
1851 return "Illegal comp account issuer: ". $self->payinfo if $error;
1854 } elsif ( $self->payby eq 'PREPAY' ) {
1856 my $payinfo = $self->payinfo;
1857 $payinfo =~ s/\W//g; #anything else would just confuse things
1858 $self->payinfo($payinfo);
1859 $error = $self->ut_alpha('payinfo');
1860 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1861 return "Unknown prepayment identifier"
1862 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1867 return "You are not permitted to create complimentary accounts."
1869 && $self->complimentary eq 'Y'
1870 && ! $FS::CurrentUser::CurrentUser->access_right('Complimentary customer');
1872 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1873 return "Expiration date required"
1874 # shouldn't payinfo_check do this?
1875 unless ! $self->payby
1876 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
1880 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1881 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1882 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1883 ( $m, $y ) = ( $2, "19$1" );
1884 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1885 ( $m, $y ) = ( $3, "20$2" );
1887 return "Illegal expiration date: ". $self->paydate;
1889 $m = sprintf('%02d',$m);
1890 $self->paydate("$y-$m-01");
1891 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1892 return gettext('expired_card')
1894 && !$ignore_expired_card
1895 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1898 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1899 ( ! $conf->exists('require_cardname')
1900 || $self->payby !~ /^(CARD|DCRD)$/ )
1902 $self->payname( $self->first. " ". $self->getfield('last') );
1905 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
1906 $self->payname =~ /^([\w \,\.\-\']*)$/
1907 or return gettext('illegal_name'). " payname: ". $self->payname;
1910 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
1911 or return gettext('illegal_name'). " payname: ". $self->payname;
1917 ### end of stuff moved to cust_payby
1919 return "Please select an invoicing locale"
1922 && $conf->exists('cust_main-require_locale');
1924 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1925 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1929 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1931 warn "$me check AFTER: \n". $self->_dump
1934 $self->SUPER::check;
1939 Additional checks for replace only.
1944 my ($new,$old) = @_;
1945 #preserve old value if global config is set
1946 if ($old && $conf->exists('invoice-ship_address')) {
1947 $new->invoice_ship_address($old->invoice_ship_address);
1954 Returns a list of fields which have ship_ duplicates.
1959 qw( last first company
1961 address1 address2 city county state zip country
1963 daytime night fax mobile
1967 =item has_ship_address
1969 Returns true if this customer record has a separate shipping address.
1973 sub has_ship_address {
1975 $self->bill_locationnum != $self->ship_locationnum;
1980 Returns a list of key/value pairs, with the following keys: address1,
1981 adddress2, city, county, state, zip, country, district, and geocode. The
1982 shipping address is used if present.
1988 $self->ship_location->location_hash;
1993 Returns all locations (see L<FS::cust_location>) for this customer.
1999 qsearch('cust_location', { 'custnum' => $self->custnum,
2000 'prospectnum' => '' } );
2005 Returns all contact associations (see L<FS::cust_contact>) for this customer.
2011 qsearch('cust_contact', { 'custnum' => $self->custnum } );
2016 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2023 'table' => 'cust_payby',
2024 'hashref' => { 'custnum' => $self->custnum },
2025 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
2029 sub has_cust_payby_auto {
2032 'table' => 'cust_payby',
2033 'hashref' => { 'custnum' => $self->custnum, },
2034 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2035 'order_by' => 'LIMIT 1',
2042 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2043 and L<FS::cust_pkg>) for this customer, except those on hold.
2045 Returns a list: an empty list on success or a list of errors.
2051 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2056 Unsuspends all suspended packages in the on-hold state (those without setup
2057 dates) for this customer.
2063 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2068 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2070 Returns a list: an empty list on success or a list of errors.
2076 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2079 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2081 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2082 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2083 of a list of pkgparts; the hashref has the following keys:
2087 =item pkgparts - listref of pkgparts
2089 =item (other options are passed to the suspend method)
2094 Returns a list: an empty list on success or a list of errors.
2098 sub suspend_if_pkgpart {
2100 my (@pkgparts, %opt);
2101 if (ref($_[0]) eq 'HASH'){
2102 @pkgparts = @{$_[0]{pkgparts}};
2107 grep { $_->suspend(%opt) }
2108 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2109 $self->unsuspended_pkgs;
2112 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2114 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2115 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2116 instead of a list of pkgparts; the hashref has the following keys:
2120 =item pkgparts - listref of pkgparts
2122 =item (other options are passed to the suspend method)
2126 Returns a list: an empty list on success or a list of errors.
2130 sub suspend_unless_pkgpart {
2132 my (@pkgparts, %opt);
2133 if (ref($_[0]) eq 'HASH'){
2134 @pkgparts = @{$_[0]{pkgparts}};
2139 grep { $_->suspend(%opt) }
2140 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2141 $self->unsuspended_pkgs;
2144 =item cancel [ OPTION => VALUE ... ]
2146 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2148 Available options are:
2152 =item quiet - can be set true to supress email cancellation notices.
2154 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
2156 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2158 =item nobill - can be set true to skip billing if it might otherwise be done.
2162 Always returns a list: an empty list on success or a list of errors.
2166 # nb that dates are not specified as valid options to this method
2169 my( $self, %opt ) = @_;
2171 warn "$me cancel called on customer ". $self->custnum. " with options ".
2172 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2175 return ( 'access denied' )
2176 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2178 if ( $opt{'ban'} ) {
2180 foreach my $cust_payby ( $self->cust_payby ) {
2182 #well, if they didn't get decrypted on search, then we don't have to
2183 # try again... queue a job for the server that does have decryption
2184 # capability if we're in a paranoid multi-server implementation?
2185 return ( "Can't (yet) ban encrypted credit cards" )
2186 if $cust_payby->is_encrypted($cust_payby->payinfo);
2188 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2189 my $error = $ban->insert;
2190 return ( $error ) if $error;
2196 my @pkgs = $self->ncancelled_pkgs;
2198 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2200 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2201 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2205 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2206 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2209 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2212 sub _banned_pay_hashref {
2223 'payby' => $payby2ban{$self->payby},
2224 'payinfo' => $self->payinfo,
2225 #don't ever *search* on reason! #'reason' =>
2231 Returns all notes (see L<FS::cust_main_note>) for this customer.
2236 my($self,$orderby_classnum) = (shift,shift);
2237 my $orderby = "sticky DESC, _date DESC";
2238 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2239 qsearch( 'cust_main_note',
2240 { 'custnum' => $self->custnum },
2242 "ORDER BY $orderby",
2248 Returns the agent (see L<FS::agent>) for this customer.
2252 Returns the agent name (see L<FS::agent>) for this customer.
2258 $self->agent->agent;
2263 Returns any tags associated with this customer, as FS::cust_tag objects,
2264 or an empty list if there are no tags.
2268 Returns any tags associated with this customer, as FS::part_tag objects,
2269 or an empty list if there are no tags.
2275 map $_->part_tag, $self->cust_tag;
2281 Returns the customer class, as an FS::cust_class object, or the empty string
2282 if there is no customer class.
2286 Returns the customer category name, or the empty string if there is no customer
2293 my $cust_class = $self->cust_class;
2295 ? $cust_class->categoryname
2301 Returns the customer class name, or the empty string if there is no customer
2308 my $cust_class = $self->cust_class;
2310 ? $cust_class->classname
2316 Returns the external tax status, as an FS::tax_status object, or the empty
2317 string if there is no tax status.
2323 if ( $self->taxstatusnum ) {
2324 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2332 Returns the tax status code if there is one.
2338 my $tax_status = $self->tax_status;
2340 ? $tax_status->taxstatus
2344 =item BILLING METHODS
2346 Documentation on billing methods has been moved to
2347 L<FS::cust_main::Billing>.
2349 =item REALTIME BILLING METHODS
2351 Documentation on realtime billing methods has been moved to
2352 L<FS::cust_main::Billing_Realtime>.
2356 Removes the I<paycvv> field from the database directly.
2358 If there is an error, returns the error, otherwise returns false.
2364 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2365 or return dbh->errstr;
2366 $sth->execute($self->custnum)
2367 or return $sth->errstr;
2374 Returns the total owed for this customer on all invoices
2375 (see L<FS::cust_bill/owed>).
2381 $self->total_owed_date(2145859200); #12/31/2037
2384 =item total_owed_date TIME
2386 Returns the total owed for this customer on all invoices with date earlier than
2387 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2388 see L<Time::Local> and L<Date::Parse> for conversion functions.
2392 sub total_owed_date {
2396 my $custnum = $self->custnum;
2398 my $owed_sql = FS::cust_bill->owed_sql;
2401 SELECT SUM($owed_sql) FROM cust_bill
2402 WHERE custnum = $custnum
2406 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2410 =item total_owed_pkgnum PKGNUM
2412 Returns the total owed on all invoices for this customer's specific package
2413 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2417 sub total_owed_pkgnum {
2418 my( $self, $pkgnum ) = @_;
2419 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2422 =item total_owed_date_pkgnum TIME PKGNUM
2424 Returns the total owed for this customer's specific package when using
2425 experimental package balances on all invoices with date earlier than
2426 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2427 see L<Time::Local> and L<Date::Parse> for conversion functions.
2431 sub total_owed_date_pkgnum {
2432 my( $self, $time, $pkgnum ) = @_;
2435 foreach my $cust_bill (
2436 grep { $_->_date <= $time }
2437 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2439 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2441 sprintf( "%.2f", $total_bill );
2447 Returns the total amount of all payments.
2454 $total += $_->paid foreach $self->cust_pay;
2455 sprintf( "%.2f", $total );
2458 =item total_unapplied_credits
2460 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2461 customer. See L<FS::cust_credit/credited>.
2463 =item total_credited
2465 Old name for total_unapplied_credits. Don't use.
2469 sub total_credited {
2470 #carp "total_credited deprecated, use total_unapplied_credits";
2471 shift->total_unapplied_credits(@_);
2474 sub total_unapplied_credits {
2477 my $custnum = $self->custnum;
2479 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2482 SELECT SUM($unapplied_sql) FROM cust_credit
2483 WHERE custnum = $custnum
2486 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2490 =item total_unapplied_credits_pkgnum PKGNUM
2492 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2493 customer. See L<FS::cust_credit/credited>.
2497 sub total_unapplied_credits_pkgnum {
2498 my( $self, $pkgnum ) = @_;
2499 my $total_credit = 0;
2500 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2501 sprintf( "%.2f", $total_credit );
2505 =item total_unapplied_payments
2507 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2508 See L<FS::cust_pay/unapplied>.
2512 sub total_unapplied_payments {
2515 my $custnum = $self->custnum;
2517 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2520 SELECT SUM($unapplied_sql) FROM cust_pay
2521 WHERE custnum = $custnum
2524 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2528 =item total_unapplied_payments_pkgnum PKGNUM
2530 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2531 specific package when using experimental package balances. See
2532 L<FS::cust_pay/unapplied>.
2536 sub total_unapplied_payments_pkgnum {
2537 my( $self, $pkgnum ) = @_;
2538 my $total_unapplied = 0;
2539 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2540 sprintf( "%.2f", $total_unapplied );
2544 =item total_unapplied_refunds
2546 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2547 customer. See L<FS::cust_refund/unapplied>.
2551 sub total_unapplied_refunds {
2553 my $custnum = $self->custnum;
2555 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2558 SELECT SUM($unapplied_sql) FROM cust_refund
2559 WHERE custnum = $custnum
2562 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2568 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2569 total_unapplied_credits minus total_unapplied_payments).
2575 $self->balance_date_range;
2578 =item balance_date TIME
2580 Returns the balance for this customer, only considering invoices with date
2581 earlier than TIME (total_owed_date minus total_credited minus
2582 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2583 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2590 $self->balance_date_range(shift);
2593 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2595 Returns the balance for this customer, optionally considering invoices with
2596 date earlier than START_TIME, and not later than END_TIME
2597 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2599 Times are specified as SQL fragments or numeric
2600 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2601 L<Date::Parse> for conversion functions. The empty string can be passed
2602 to disable that time constraint completely.
2604 Accepts the same options as L<balance_date_sql>:
2608 =item unapplied_date
2610 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)
2614 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2615 time will be ignored. Note that START_TIME and END_TIME only limit the date
2616 range for invoices and I<unapplied> payments, credits, and refunds.
2622 sub balance_date_range {
2624 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2625 ') FROM cust_main WHERE custnum='. $self->custnum;
2626 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2629 =item balance_pkgnum PKGNUM
2631 Returns the balance for this customer's specific package when using
2632 experimental package balances (total_owed plus total_unrefunded, minus
2633 total_unapplied_credits minus total_unapplied_payments)
2637 sub balance_pkgnum {
2638 my( $self, $pkgnum ) = @_;
2641 $self->total_owed_pkgnum($pkgnum)
2642 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2643 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2644 - $self->total_unapplied_credits_pkgnum($pkgnum)
2645 - $self->total_unapplied_payments_pkgnum($pkgnum)
2651 Returns a hash of useful information for making a payment.
2661 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2662 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2663 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2667 For credit card transactions:
2679 For electronic check transactions:
2694 $return{balance} = $self->balance;
2696 $return{payname} = $self->payname
2697 || ( $self->first. ' '. $self->get('last') );
2699 $return{$_} = $self->bill_location->$_
2700 for qw(address1 address2 city state zip);
2702 $return{payby} = $self->payby;
2703 $return{stateid_state} = $self->stateid_state;
2705 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2706 $return{card_type} = cardtype($self->payinfo);
2707 $return{payinfo} = $self->paymask;
2709 @return{'month', 'year'} = $self->paydate_monthyear;
2713 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2714 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2715 $return{payinfo1} = $payinfo1;
2716 $return{payinfo2} = $payinfo2;
2717 $return{paytype} = $self->paytype;
2718 $return{paystate} = $self->paystate;
2722 #doubleclick protection
2724 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2730 =item paydate_monthyear
2732 Returns a two-element list consisting of the month and year of this customer's
2733 paydate (credit card expiration date for CARD customers)
2737 sub paydate_monthyear {
2739 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2741 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2750 Returns the exact time in seconds corresponding to the payment method
2751 expiration date. For CARD/DCRD customers this is the end of the month;
2752 for others (COMP is the only other payby that uses paydate) it's the start.
2753 Returns 0 if the paydate is empty or set to the far future.
2759 my ($month, $year) = $self->paydate_monthyear;
2760 return 0 if !$year or $year >= 2037;
2761 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2763 if ( $month == 13 ) {
2767 return timelocal(0,0,0,1,$month-1,$year) - 1;
2770 return timelocal(0,0,0,1,$month-1,$year);
2774 =item paydate_epoch_sql
2776 Class method. Returns an SQL expression to obtain the payment expiration date
2777 as a number of seconds.
2781 # Special expiration date behavior for non-CARD/DCRD customers has been
2782 # carefully preserved. Do we really use that?
2783 sub paydate_epoch_sql {
2785 my $table = shift || 'cust_main';
2786 my ($case1, $case2);
2787 if ( driver_name eq 'Pg' ) {
2788 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2789 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2791 elsif ( lc(driver_name) eq 'mysql' ) {
2792 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2793 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2796 return "CASE WHEN $table.payby IN('CARD','DCRD')
2802 =item tax_exemption TAXNAME
2807 my( $self, $taxname ) = @_;
2809 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2810 'taxname' => $taxname,
2815 =item cust_main_exemption
2817 =item invoicing_list [ ARRAYREF ]
2819 If an arguement is given, sets these email addresses as invoice recipients
2820 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2821 (except as warnings), so use check_invoicing_list first.
2823 Returns a list of email addresses (with svcnum entries expanded).
2825 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2826 check it without disturbing anything by passing nothing.
2828 This interface may change in the future.
2832 sub invoicing_list {
2833 my( $self, $arrayref ) = @_;
2836 my @cust_main_invoice;
2837 if ( $self->custnum ) {
2838 @cust_main_invoice =
2839 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2841 @cust_main_invoice = ();
2843 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2844 #warn $cust_main_invoice->destnum;
2845 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2846 #warn $cust_main_invoice->destnum;
2847 my $error = $cust_main_invoice->delete;
2848 warn $error if $error;
2851 if ( $self->custnum ) {
2852 @cust_main_invoice =
2853 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2855 @cust_main_invoice = ();
2857 my %seen = map { $_->address => 1 } @cust_main_invoice;
2858 foreach my $address ( @{$arrayref} ) {
2859 next if exists $seen{$address} && $seen{$address};
2860 $seen{$address} = 1;
2861 my $cust_main_invoice = new FS::cust_main_invoice ( {
2862 'custnum' => $self->custnum,
2865 my $error = $cust_main_invoice->insert;
2866 warn $error if $error;
2870 if ( $self->custnum ) {
2872 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2879 =item check_invoicing_list ARRAYREF
2881 Checks these arguements as valid input for the invoicing_list method. If there
2882 is an error, returns the error, otherwise returns false.
2886 sub check_invoicing_list {
2887 my( $self, $arrayref ) = @_;
2889 foreach my $address ( @$arrayref ) {
2891 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2892 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2895 my $cust_main_invoice = new FS::cust_main_invoice ( {
2896 'custnum' => $self->custnum,
2899 my $error = $self->custnum
2900 ? $cust_main_invoice->check
2901 : $cust_main_invoice->checkdest
2903 return $error if $error;
2907 return "Email address required"
2908 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2909 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2914 =item set_default_invoicing_list
2916 Sets the invoicing list to all accounts associated with this customer,
2917 overwriting any previous invoicing list.
2921 sub set_default_invoicing_list {
2923 $self->invoicing_list($self->all_emails);
2928 Returns the email addresses of all accounts provisioned for this customer.
2935 foreach my $cust_pkg ( $self->all_pkgs ) {
2936 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2938 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2939 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2941 $list{$_}=1 foreach map { $_->email } @svc_acct;
2946 =item invoicing_list_addpost
2948 Adds postal invoicing to this customer. If this customer is already configured
2949 to receive postal invoices, does nothing.
2953 sub invoicing_list_addpost {
2955 return if grep { $_ eq 'POST' } $self->invoicing_list;
2956 my @invoicing_list = $self->invoicing_list;
2957 push @invoicing_list, 'POST';
2958 $self->invoicing_list(\@invoicing_list);
2961 =item invoicing_list_emailonly
2963 Returns the list of email invoice recipients (invoicing_list without non-email
2964 destinations such as POST and FAX).
2968 sub invoicing_list_emailonly {
2970 warn "$me invoicing_list_emailonly called"
2972 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
2975 =item invoicing_list_emailonly_scalar
2977 Returns the list of email invoice recipients (invoicing_list without non-email
2978 destinations such as POST and FAX) as a comma-separated scalar.
2982 sub invoicing_list_emailonly_scalar {
2984 warn "$me invoicing_list_emailonly_scalar called"
2986 join(', ', $self->invoicing_list_emailonly);
2989 =item referral_custnum_cust_main
2991 Returns the customer who referred this customer (or the empty string, if
2992 this customer was not referred).
2994 Note the difference with referral_cust_main method: This method,
2995 referral_custnum_cust_main returns the single customer (if any) who referred
2996 this customer, while referral_cust_main returns an array of customers referred
3001 sub referral_custnum_cust_main {
3003 return '' unless $self->referral_custnum;
3004 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3007 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3009 Returns an array of customers referred by this customer (referral_custnum set
3010 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3011 customers referred by customers referred by this customer and so on, inclusive.
3012 The default behavior is DEPTH 1 (no recursion).
3014 Note the difference with referral_custnum_cust_main method: This method,
3015 referral_cust_main, returns an array of customers referred BY this customer,
3016 while referral_custnum_cust_main returns the single customer (if any) who
3017 referred this customer.
3021 sub referral_cust_main {
3023 my $depth = @_ ? shift : 1;
3024 my $exclude = @_ ? shift : {};
3027 map { $exclude->{$_->custnum}++; $_; }
3028 grep { ! $exclude->{ $_->custnum } }
3029 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3033 map { $_->referral_cust_main($depth-1, $exclude) }
3040 =item referral_cust_main_ncancelled
3042 Same as referral_cust_main, except only returns customers with uncancelled
3047 sub referral_cust_main_ncancelled {
3049 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3052 =item referral_cust_pkg [ DEPTH ]
3054 Like referral_cust_main, except returns a flat list of all unsuspended (and
3055 uncancelled) packages for each customer. The number of items in this list may
3056 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3060 sub referral_cust_pkg {
3062 my $depth = @_ ? shift : 1;
3064 map { $_->unsuspended_pkgs }
3065 grep { $_->unsuspended_pkgs }
3066 $self->referral_cust_main($depth);
3069 =item referring_cust_main
3071 Returns the single cust_main record for the customer who referred this customer
3072 (referral_custnum), or false.
3076 sub referring_cust_main {
3078 return '' unless $self->referral_custnum;
3079 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3082 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3084 Applies a credit to this customer. If there is an error, returns the error,
3085 otherwise returns false.
3087 REASON can be a text string, an FS::reason object, or a scalar reference to
3088 a reasonnum. If a text string, it will be automatically inserted as a new
3089 reason, and a 'reason_type' option must be passed to indicate the
3090 FS::reason_type for the new reason.
3092 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3093 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3094 I<commission_pkgnum>.
3096 Any other options are passed to FS::cust_credit::insert.
3101 my( $self, $amount, $reason, %options ) = @_;
3103 my $cust_credit = new FS::cust_credit {
3104 'custnum' => $self->custnum,
3105 'amount' => $amount,
3108 if ( ref($reason) ) {
3110 if ( ref($reason) eq 'SCALAR' ) {
3111 $cust_credit->reasonnum( $$reason );
3113 $cust_credit->reasonnum( $reason->reasonnum );
3117 $cust_credit->set('reason', $reason)
3120 $cust_credit->$_( delete $options{$_} )
3121 foreach grep exists($options{$_}),
3122 qw( addlinfo eventnum ),
3123 map "commission_$_", qw( agentnum salesnum pkgnum );
3125 $cust_credit->insert(%options);
3129 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3131 Creates a one-time charge for this customer. If there is an error, returns
3132 the error, otherwise returns false.
3134 New-style, with a hashref of options:
3136 my $error = $cust_main->charge(
3140 'start_date' => str2time('7/4/2009'),
3141 'pkg' => 'Description',
3142 'comment' => 'Comment',
3143 'additional' => [], #extra invoice detail
3144 'classnum' => 1, #pkg_class
3146 'setuptax' => '', # or 'Y' for tax exempt
3148 'locationnum'=> 1234, # optional
3151 'taxclass' => 'Tax class',
3154 'taxproduct' => 2, #part_pkg_taxproduct
3155 'override' => {}, #XXX describe
3157 #will be filled in with the new object
3158 'cust_pkg_ref' => \$cust_pkg,
3160 #generate an invoice immediately
3162 'invoice_terms' => '', #with these terms
3168 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3172 #super false laziness w/quotation::charge
3175 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3176 my ( $pkg, $comment, $additional );
3177 my ( $setuptax, $taxclass ); #internal taxes
3178 my ( $taxproduct, $override ); #vendor (CCH) taxes
3180 my $separate_bill = '';
3181 my $cust_pkg_ref = '';
3182 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3184 if ( ref( $_[0] ) ) {
3185 $amount = $_[0]->{amount};
3186 $setup_cost = $_[0]->{setup_cost};
3187 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3188 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3189 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3190 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3191 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3192 : '$'. sprintf("%.2f",$amount);
3193 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3194 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3195 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3196 $additional = $_[0]->{additional} || [];
3197 $taxproduct = $_[0]->{taxproductnum};
3198 $override = { '' => $_[0]->{tax_override} };
3199 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3200 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3201 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3202 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3203 $separate_bill = $_[0]->{separate_bill} || '';
3209 $pkg = @_ ? shift : 'One-time charge';
3210 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3212 $taxclass = @_ ? shift : '';
3216 local $SIG{HUP} = 'IGNORE';
3217 local $SIG{INT} = 'IGNORE';
3218 local $SIG{QUIT} = 'IGNORE';
3219 local $SIG{TERM} = 'IGNORE';
3220 local $SIG{TSTP} = 'IGNORE';
3221 local $SIG{PIPE} = 'IGNORE';
3223 my $oldAutoCommit = $FS::UID::AutoCommit;
3224 local $FS::UID::AutoCommit = 0;
3227 my $part_pkg = new FS::part_pkg ( {
3229 'comment' => $comment,
3233 'classnum' => ( $classnum ? $classnum : '' ),
3234 'setuptax' => $setuptax,
3235 'taxclass' => $taxclass,
3236 'taxproductnum' => $taxproduct,
3237 'setup_cost' => $setup_cost,
3240 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3241 ( 0 .. @$additional - 1 )
3243 'additional_count' => scalar(@$additional),
3244 'setup_fee' => $amount,
3247 my $error = $part_pkg->insert( options => \%options,
3248 tax_overrides => $override,
3251 $dbh->rollback if $oldAutoCommit;
3255 my $pkgpart = $part_pkg->pkgpart;
3256 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3257 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3258 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3259 $error = $type_pkgs->insert;
3261 $dbh->rollback if $oldAutoCommit;
3266 my $cust_pkg = new FS::cust_pkg ( {
3267 'custnum' => $self->custnum,
3268 'pkgpart' => $pkgpart,
3269 'quantity' => $quantity,
3270 'start_date' => $start_date,
3271 'no_auto' => $no_auto,
3272 'separate_bill' => $separate_bill,
3273 'locationnum'=> $locationnum,
3276 $error = $cust_pkg->insert;
3278 $dbh->rollback if $oldAutoCommit;
3280 } elsif ( $cust_pkg_ref ) {
3281 ${$cust_pkg_ref} = $cust_pkg;
3285 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3286 'pkg_list' => [ $cust_pkg ],
3289 $dbh->rollback if $oldAutoCommit;
3294 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3299 #=item charge_postal_fee
3301 #Applies a one time charge this customer. If there is an error,
3302 #returns the error, returns the cust_pkg charge object or false
3303 #if there was no charge.
3307 # This should be a customer event. For that to work requires that bill
3308 # also be a customer event.
3310 sub charge_postal_fee {
3313 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3314 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3316 my $cust_pkg = new FS::cust_pkg ( {
3317 'custnum' => $self->custnum,
3318 'pkgpart' => $pkgpart,
3322 my $error = $cust_pkg->insert;
3323 $error ? $error : $cust_pkg;
3326 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3328 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3330 Optionally, a list or hashref of additional arguments to the qsearch call can
3337 my $opt = ref($_[0]) ? shift : { @_ };
3339 #return $self->num_cust_bill unless wantarray || keys %$opt;
3341 $opt->{'table'} = 'cust_bill';
3342 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3343 $opt->{'hashref'}{'custnum'} = $self->custnum;
3344 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3346 map { $_ } #behavior of sort undefined in scalar context
3347 sort { $a->_date <=> $b->_date }
3351 =item open_cust_bill
3353 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3358 sub open_cust_bill {
3362 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3368 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3370 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3374 sub legacy_cust_bill {
3377 #return $self->num_legacy_cust_bill unless wantarray;
3379 map { $_ } #behavior of sort undefined in scalar context
3380 sort { $a->_date <=> $b->_date }
3381 qsearch({ 'table' => 'legacy_cust_bill',
3382 'hashref' => { 'custnum' => $self->custnum, },
3383 'order_by' => 'ORDER BY _date ASC',
3387 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3389 Returns all the statements (see L<FS::cust_statement>) for this customer.
3391 Optionally, a list or hashref of additional arguments to the qsearch call can
3396 =item cust_bill_void
3398 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3402 sub cust_bill_void {
3405 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3406 sort { $a->_date <=> $b->_date }
3407 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3410 sub cust_statement {
3412 my $opt = ref($_[0]) ? shift : { @_ };
3414 #return $self->num_cust_statement unless wantarray || keys %$opt;
3416 $opt->{'table'} = 'cust_statement';
3417 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3418 $opt->{'hashref'}{'custnum'} = $self->custnum;
3419 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3421 map { $_ } #behavior of sort undefined in scalar context
3422 sort { $a->_date <=> $b->_date }
3426 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3428 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3430 Optionally, a list or hashref of additional arguments to the qsearch call can
3431 be passed following the SVCDB.
3438 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3439 warn "$me svc_x requires a svcdb";
3442 my $opt = ref($_[0]) ? shift : { @_ };
3444 $opt->{'table'} = $svcdb;
3445 $opt->{'addl_from'} =
3446 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3447 ($opt->{'addl_from'} || '');
3449 my $custnum = $self->custnum;
3450 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3451 my $where = "cust_pkg.custnum = $custnum";
3453 my $extra_sql = $opt->{'extra_sql'} || '';
3454 if ( keys %{ $opt->{'hashref'} } ) {
3455 $extra_sql = " AND $where $extra_sql";
3458 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3459 $extra_sql = "WHERE $where AND $1";
3462 $extra_sql = "WHERE $where $extra_sql";
3465 $opt->{'extra_sql'} = $extra_sql;
3470 # required for use as an eventtable;
3473 $self->svc_x('svc_acct', @_);
3478 Returns all the credits (see L<FS::cust_credit>) for this customer.
3484 map { $_ } #return $self->num_cust_credit unless wantarray;
3485 sort { $a->_date <=> $b->_date }
3486 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3489 =item cust_credit_pkgnum
3491 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3492 package when using experimental package balances.
3496 sub cust_credit_pkgnum {
3497 my( $self, $pkgnum ) = @_;
3498 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3499 sort { $a->_date <=> $b->_date }
3500 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3501 'pkgnum' => $pkgnum,
3506 =item cust_credit_void
3508 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3512 sub cust_credit_void {
3515 sort { $a->_date <=> $b->_date }
3516 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3521 Returns all the payments (see L<FS::cust_pay>) for this customer.
3527 my $opt = ref($_[0]) ? shift : { @_ };
3529 return $self->num_cust_pay unless wantarray || keys %$opt;
3531 $opt->{'table'} = 'cust_pay';
3532 $opt->{'hashref'}{'custnum'} = $self->custnum;
3534 map { $_ } #behavior of sort undefined in scalar context
3535 sort { $a->_date <=> $b->_date }
3542 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3543 called automatically when the cust_pay method is used in a scalar context.
3549 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3550 my $sth = dbh->prepare($sql) or die dbh->errstr;
3551 $sth->execute($self->custnum) or die $sth->errstr;
3552 $sth->fetchrow_arrayref->[0];
3555 =item unapplied_cust_pay
3557 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3561 sub unapplied_cust_pay {
3565 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3571 =item cust_pay_pkgnum
3573 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3574 package when using experimental package balances.
3578 sub cust_pay_pkgnum {
3579 my( $self, $pkgnum ) = @_;
3580 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3581 sort { $a->_date <=> $b->_date }
3582 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3583 'pkgnum' => $pkgnum,
3590 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3596 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3597 sort { $a->_date <=> $b->_date }
3598 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3601 =item cust_pay_pending
3603 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3604 (without status "done").
3608 sub cust_pay_pending {
3610 return $self->num_cust_pay_pending unless wantarray;
3611 sort { $a->_date <=> $b->_date }
3612 qsearch( 'cust_pay_pending', {
3613 'custnum' => $self->custnum,
3614 'status' => { op=>'!=', value=>'done' },
3619 =item cust_pay_pending_attempt
3621 Returns all payment attempts / declined payments for this customer, as pending
3622 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3623 a corresponding payment (see L<FS::cust_pay>).
3627 sub cust_pay_pending_attempt {
3629 return $self->num_cust_pay_pending_attempt unless wantarray;
3630 sort { $a->_date <=> $b->_date }
3631 qsearch( 'cust_pay_pending', {
3632 'custnum' => $self->custnum,
3639 =item num_cust_pay_pending
3641 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3642 customer (without status "done"). Also called automatically when the
3643 cust_pay_pending method is used in a scalar context.
3647 sub num_cust_pay_pending {
3650 " SELECT COUNT(*) FROM cust_pay_pending ".
3651 " WHERE custnum = ? AND status != 'done' ",
3656 =item num_cust_pay_pending_attempt
3658 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3659 customer, with status "done" but without a corresp. Also called automatically when the
3660 cust_pay_pending method is used in a scalar context.
3664 sub num_cust_pay_pending_attempt {
3667 " SELECT COUNT(*) FROM cust_pay_pending ".
3668 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3675 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3681 map { $_ } #return $self->num_cust_refund unless wantarray;
3682 sort { $a->_date <=> $b->_date }
3683 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3686 =item display_custnum
3688 Returns the displayed customer number for this customer: agent_custid if
3689 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3693 sub display_custnum {
3696 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3697 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3698 if ( $special eq 'CoStAg' ) {
3699 $prefix = uc( join('',
3701 ($self->state =~ /^(..)/),
3702 $prefix || ($self->agent->agent =~ /^(..)/)
3705 elsif ( $special eq 'CoStCl' ) {
3706 $prefix = uc( join('',
3708 ($self->state =~ /^(..)/),
3709 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3712 # add any others here if needed
3715 my $length = $conf->config('cust_main-custnum-display_length');
3716 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3717 return $self->agent_custid;
3718 } elsif ( $prefix ) {
3719 $length = 8 if !defined($length);
3721 sprintf('%0'.$length.'d', $self->custnum)
3722 } elsif ( $length ) {
3723 return sprintf('%0'.$length.'d', $self->custnum);
3725 return $self->custnum;
3731 Returns a name string for this customer, either "Company (Last, First)" or
3738 my $name = $self->contact;
3739 $name = $self->company. " ($name)" if $self->company;
3743 =item service_contact
3745 Returns the L<FS::contact> object for this customer that has the 'Service'
3746 contact class, or undef if there is no such contact. Deprecated; don't use
3751 sub service_contact {
3753 if ( !exists($self->{service_contact}) ) {
3754 my $classnum = $self->scalar_sql(
3755 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3756 ) || 0; #if it's zero, qsearchs will return nothing
3757 my $cust_contact = qsearchs('cust_contact', {
3758 'classnum' => $classnum,
3759 'custnum' => $self->custnum,
3761 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3763 $self->{service_contact};
3768 Returns a name string for this (service/shipping) contact, either
3769 "Company (Last, First)" or "Last, First".
3776 my $name = $self->ship_contact;
3777 $name = $self->company. " ($name)" if $self->company;
3783 Returns a name string for this customer, either "Company" or "First Last".
3789 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3792 =item ship_name_short
3794 Returns a name string for this (service/shipping) contact, either "Company"
3799 sub ship_name_short {
3801 $self->service_contact
3802 ? $self->ship_contact_firstlast
3808 Returns this customer's full (billing) contact name only, "Last, First"
3814 $self->get('last'). ', '. $self->first;
3819 Returns this customer's full (shipping) contact name only, "Last, First"
3825 my $contact = $self->service_contact || $self;
3826 $contact->get('last') . ', ' . $contact->get('first');
3829 =item contact_firstlast
3831 Returns this customers full (billing) contact name only, "First Last".
3835 sub contact_firstlast {
3837 $self->first. ' '. $self->get('last');
3840 =item ship_contact_firstlast
3842 Returns this customer's full (shipping) contact name only, "First Last".
3846 sub ship_contact_firstlast {
3848 my $contact = $self->service_contact || $self;
3849 $contact->get('first') . ' '. $contact->get('last');
3852 #XXX this doesn't work in 3.x+
3855 #Returns this customer's full country name
3861 # code2country($self->country);
3864 sub bill_country_full {
3866 code2country($self->bill_location->country);
3869 sub ship_country_full {
3871 code2country($self->ship_location->country);
3874 =item county_state_county [ PREFIX ]
3876 Returns a string consisting of just the county, state and country.
3880 sub county_state_country {
3883 if ( @_ && $_[0] && $self->has_ship_address ) {
3884 $locationnum = $self->ship_locationnum;
3886 $locationnum = $self->bill_locationnum;
3888 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3889 $cust_location->county_state_country;
3892 =item geocode DATA_VENDOR
3894 Returns a value for the customer location as encoded by DATA_VENDOR.
3895 Currently this only makes sense for "CCH" as DATA_VENDOR.
3903 Returns a status string for this customer, currently:
3909 No packages have ever been ordered. Displayed as "No packages".
3913 Recurring packages all are new (not yet billed).
3917 One or more recurring packages is active.
3921 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3925 All non-cancelled recurring packages are suspended.
3929 All recurring packages are cancelled.
3933 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3934 cust_main-status_module configuration option.
3938 sub status { shift->cust_status(@_); }
3942 for my $status ( FS::cust_main->statuses() ) {
3943 my $method = $status.'_sql';
3944 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3945 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3946 $sth->execute( ($self->custnum) x $numnum )
3947 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3948 return $status if $sth->fetchrow_arrayref->[0];
3952 =item is_status_delay_cancel
3954 Returns true if customer status is 'suspended'
3955 and all suspended cust_pkg return true for
3956 cust_pkg->is_status_delay_cancel.
3958 This is not a real status, this only meant for hacking display
3959 values, because otherwise treating the customer as suspended is
3960 really the whole point of the delay_cancel option.
3964 sub is_status_delay_cancel {
3966 return 0 unless $self->status eq 'suspended';
3967 foreach my $cust_pkg ($self->ncancelled_pkgs) {
3968 return 0 unless $cust_pkg->is_status_delay_cancel;
3973 =item ucfirst_cust_status
3975 =item ucfirst_status
3977 Deprecated, use the cust_status_label method instead.
3979 Returns the status with the first character capitalized.
3983 sub ucfirst_status {
3984 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3985 local($ucfirst_nowarn) = 1;
3986 shift->ucfirst_cust_status(@_);
3989 sub ucfirst_cust_status {
3990 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3992 ucfirst($self->cust_status);
3995 =item cust_status_label
3999 Returns the display label for this status.
4003 sub status_label { shift->cust_status_label(@_); }
4005 sub cust_status_label {
4007 __PACKAGE__->statuslabels->{$self->cust_status};
4012 Returns a hex triplet color string for this customer's status.
4016 sub statuscolor { shift->cust_statuscolor(@_); }
4018 sub cust_statuscolor {
4020 __PACKAGE__->statuscolors->{$self->cust_status};
4023 =item tickets [ STATUS ]
4025 Returns an array of hashes representing the customer's RT tickets.
4027 An optional status (or arrayref or hashref of statuses) may be specified.
4033 my $status = ( @_ && $_[0] ) ? shift : '';
4035 my $num = $conf->config('cust_main-max_tickets') || 10;
4038 if ( $conf->config('ticket_system') ) {
4039 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4041 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4050 foreach my $priority (
4051 $conf->config('ticket_system-custom_priority_field-values'), ''
4053 last if scalar(@tickets) >= $num;
4055 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4056 $num - scalar(@tickets),
4067 =item appointments [ STATUS ]
4069 Returns an array of hashes representing the customer's RT tickets which
4076 my $status = ( @_ && $_[0] ) ? shift : '';
4078 return () unless $conf->config('ticket_system');
4080 my $queueid = $conf->config('ticket_system-appointment-queueid');
4082 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4091 # Return services representing svc_accts in customer support packages
4092 sub support_services {
4094 my %packages = map { $_ => 1 } $conf->config('support_packages');
4096 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4097 grep { $_->part_svc->svcdb eq 'svc_acct' }
4098 map { $_->cust_svc }
4099 grep { exists $packages{ $_->pkgpart } }
4100 $self->ncancelled_pkgs;
4104 # Return a list of latitude/longitude for one of the services (if any)
4105 sub service_coordinates {
4109 grep { $_->latitude && $_->longitude }
4111 map { $_->cust_svc }
4112 $self->ncancelled_pkgs;
4114 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4119 Returns a masked version of the named field
4124 my ($self,$field) = @_;
4128 'x'x(length($self->getfield($field))-4).
4129 substr($self->getfield($field), (length($self->getfield($field))-4));
4133 =item payment_history
4135 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4136 cust_credit and cust_refund objects. Each hashref has the following fields:
4138 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4140 I<date> - value of _date field, unix timestamp
4142 I<date_pretty> - user-friendly date
4144 I<description> - user-friendly description of item
4146 I<amount> - impact of item on user's balance
4147 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4148 Not to be confused with the native 'amount' field in cust_credit, see below.
4150 I<amount_pretty> - includes money char
4152 I<balance> - customer balance, chronologically as of this item
4154 I<balance_pretty> - includes money char
4156 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4158 I<paid> - amount paid for cust_pay records, undef for other types
4160 I<credit> - amount credited for cust_credit records, undef for other types.
4161 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4163 I<refund> - amount refunded for cust_refund records, undef for other types
4165 The four table-specific keys always have positive values, whether they reflect charges or payments.
4167 The following options may be passed to this method:
4169 I<line_items> - if true, returns charges ('Line item') rather than invoices
4171 I<start_date> - unix timestamp, only include records on or after.
4172 If specified, an item of type 'Previous' will also be included.
4173 It does not have table-specific fields.
4175 I<end_date> - unix timestamp, only include records before
4177 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4179 I<conf> - optional already-loaded FS::Conf object.
4183 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4184 # and also for sending customer statements, which should both be kept customer-friendly.
4185 # If you add anything that shouldn't be passed on through the API or exposed
4186 # to customers, add a new option to include it, don't include it by default
4187 sub payment_history {
4189 my $opt = ref($_[0]) ? $_[0] : { @_ };
4191 my $conf = $$opt{'conf'} || new FS::Conf;
4192 my $money_char = $conf->config("money_char") || '$',
4194 #first load entire history,
4195 #need previous to calculate previous balance
4196 #loading after end_date shouldn't hurt too much?
4198 if ( $$opt{'line_items'} ) {
4200 foreach my $cust_bill ( $self->cust_bill ) {
4203 'type' => 'Line item',
4204 'description' => $_->desc( $self->locale ).
4205 ( $_->sdate && $_->edate
4206 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4207 ' To '. time2str('%d-%b-%Y', $_->edate)
4210 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4211 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4212 'date' => $cust_bill->_date,
4213 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4215 foreach $cust_bill->cust_bill_pkg;
4222 'type' => 'Invoice',
4223 'description' => 'Invoice #'. $_->display_invnum,
4224 'amount' => sprintf('%.2f', $_->charged ),
4225 'charged' => sprintf('%.2f', $_->charged ),
4226 'date' => $_->_date,
4227 'date_pretty' => $self->time2str_local('short', $_->_date ),
4229 foreach $self->cust_bill;
4234 'type' => 'Payment',
4235 'description' => 'Payment', #XXX type
4236 'amount' => sprintf('%.2f', 0 - $_->paid ),
4237 'paid' => sprintf('%.2f', $_->paid ),
4238 'date' => $_->_date,
4239 'date_pretty' => $self->time2str_local('short', $_->_date ),
4241 foreach $self->cust_pay;
4245 'description' => 'Credit', #more info?
4246 'amount' => sprintf('%.2f', 0 -$_->amount ),
4247 'credit' => sprintf('%.2f', $_->amount ),
4248 'date' => $_->_date,
4249 'date_pretty' => $self->time2str_local('short', $_->_date ),
4251 foreach $self->cust_credit;
4255 'description' => 'Refund', #more info? type, like payment?
4256 'amount' => $_->refund,
4257 'refund' => $_->refund,
4258 'date' => $_->_date,
4259 'date_pretty' => $self->time2str_local('short', $_->_date ),
4261 foreach $self->cust_refund;
4263 #put it all in chronological order
4264 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4266 #calculate balance, filter items outside date range
4270 foreach my $item (@history) {
4271 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4272 $balance += $$item{'amount'};
4273 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4274 $previous += $$item{'amount'};
4277 $$item{'balance'} = sprintf("%.2f",$balance);
4278 foreach my $key ( qw(amount balance) ) {
4279 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4284 # start with previous balance, if there was one
4287 'type' => 'Previous',
4288 'description' => 'Previous balance',
4289 'amount' => sprintf("%.2f",$previous),
4290 'balance' => sprintf("%.2f",$previous),
4291 'date' => $$opt{'start_date'},
4292 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4294 #false laziness with above
4295 foreach my $key ( qw(amount balance) ) {
4296 $$item{$key.'_pretty'} = $$item{$key};
4297 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4299 unshift(@out,$item);
4302 @out = reverse @history if $$opt{'reverse_sort'};
4309 =head1 CLASS METHODS
4315 Class method that returns the list of possible status strings for customers
4316 (see L<the status method|/status>). For example:
4318 @statuses = FS::cust_main->statuses();
4324 keys %{ $self->statuscolors };
4327 =item cust_status_sql
4329 Returns an SQL fragment to determine the status of a cust_main record, as a
4334 sub cust_status_sql {
4336 for my $status ( FS::cust_main->statuses() ) {
4337 my $method = $status.'_sql';
4338 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4347 Returns an SQL expression identifying prospective cust_main records (customers
4348 with no packages ever ordered)
4352 use vars qw($select_count_pkgs);
4353 $select_count_pkgs =
4354 "SELECT COUNT(*) FROM cust_pkg
4355 WHERE cust_pkg.custnum = cust_main.custnum";
4357 sub select_count_pkgs_sql {
4362 " 0 = ( $select_count_pkgs ) ";
4367 Returns an SQL expression identifying ordered cust_main records (customers with
4368 no active packages, but recurring packages not yet setup or one time charges
4374 FS::cust_main->none_active_sql.
4375 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4380 Returns an SQL expression identifying active cust_main records (customers with
4381 active recurring packages).
4386 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4389 =item none_active_sql
4391 Returns an SQL expression identifying cust_main records with no active
4392 recurring packages. This includes customers of status prospect, ordered,
4393 inactive, and suspended.
4397 sub none_active_sql {
4398 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4403 Returns an SQL expression identifying inactive cust_main records (customers with
4404 no active recurring packages, but otherwise unsuspended/uncancelled).
4409 FS::cust_main->none_active_sql.
4410 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4416 Returns an SQL expression identifying suspended cust_main records.
4421 sub suspended_sql { susp_sql(@_); }
4423 FS::cust_main->none_active_sql.
4424 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4430 Returns an SQL expression identifying cancelled cust_main records.
4434 sub cancel_sql { shift->cancelled_sql(@_); }
4437 =item uncancelled_sql
4439 Returns an SQL expression identifying un-cancelled cust_main records.
4443 sub uncancelled_sql { uncancel_sql(@_); }
4444 sub uncancel_sql { "
4445 ( 0 < ( $select_count_pkgs
4446 AND ( cust_pkg.cancel IS NULL
4447 OR cust_pkg.cancel = 0
4450 OR 0 = ( $select_count_pkgs )
4456 Returns an SQL fragment to retreive the balance.
4461 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4462 WHERE cust_bill.custnum = cust_main.custnum )
4463 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4464 WHERE cust_pay.custnum = cust_main.custnum )
4465 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4466 WHERE cust_credit.custnum = cust_main.custnum )
4467 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4468 WHERE cust_refund.custnum = cust_main.custnum )
4471 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4473 Returns an SQL fragment to retreive the balance for this customer, optionally
4474 considering invoices with date earlier than START_TIME, and not
4475 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4476 total_unapplied_payments).
4478 Times are specified as SQL fragments or numeric
4479 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4480 L<Date::Parse> for conversion functions. The empty string can be passed
4481 to disable that time constraint completely.
4483 Available options are:
4487 =item unapplied_date
4489 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)
4494 set to true to remove all customer comparison clauses, for totals
4499 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4504 JOIN clause (typically used with the total option)
4508 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4509 time will be ignored. Note that START_TIME and END_TIME only limit the date
4510 range for invoices and I<unapplied> payments, credits, and refunds.
4516 sub balance_date_sql {
4517 my( $class, $start, $end, %opt ) = @_;
4519 my $cutoff = $opt{'cutoff'};
4521 my $owed = FS::cust_bill->owed_sql($cutoff);
4522 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4523 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4524 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4526 my $j = $opt{'join'} || '';
4528 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4529 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4530 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4531 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4533 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4534 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4535 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4536 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4541 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4543 Returns an SQL fragment to retreive the total unapplied payments for this
4544 customer, only considering payments with date earlier than START_TIME, and
4545 optionally not later than END_TIME.
4547 Times are specified as SQL fragments or numeric
4548 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4549 L<Date::Parse> for conversion functions. The empty string can be passed
4550 to disable that time constraint completely.
4552 Available options are:
4556 sub unapplied_payments_date_sql {
4557 my( $class, $start, $end, %opt ) = @_;
4559 my $cutoff = $opt{'cutoff'};
4561 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4563 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4564 'unapplied_date'=>1 );
4566 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4569 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4571 Helper method for balance_date_sql; name (and usage) subject to change
4572 (suggestions welcome).
4574 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4575 cust_refund, cust_credit or cust_pay).
4577 If TABLE is "cust_bill" or the unapplied_date option is true, only
4578 considers records with date earlier than START_TIME, and optionally not
4579 later than END_TIME .
4583 sub _money_table_where {
4584 my( $class, $table, $start, $end, %opt ) = @_;
4587 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4588 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4589 push @where, "$table._date <= $start" if defined($start) && length($start);
4590 push @where, "$table._date > $end" if defined($end) && length($end);
4592 push @where, @{$opt{'where'}} if $opt{'where'};
4593 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4599 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4600 use FS::cust_main::Search;
4603 FS::cust_main::Search->search(@_);
4612 #=item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4614 #Deprecated. Use event notification and message templates
4615 #(L<FS::msg_template>) instead.
4617 #Sends a templated email notification to the customer (see L<Text::Template>).
4619 #OPTIONS is a hash and may include
4621 #I<from> - the email sender (default is invoice_from)
4623 #I<to> - comma-separated scalar or arrayref of recipients
4624 # (default is invoicing_list)
4626 #I<subject> - The subject line of the sent email notification
4627 # (default is "Notice from company_name")
4629 #I<extra_fields> - a hashref of name/value pairs which will be substituted
4632 #The following variables are vavailable in the template.
4634 #I<$first> - the customer first name
4635 #I<$last> - the customer last name
4636 #I<$company> - the customer company
4637 #I<$payby> - a description of the method of payment for the customer
4638 # # would be nice to use FS::payby::shortname
4639 #I<$payinfo> - the account information used to collect for this customer
4640 #I<$expdate> - the expiration of the customer payment in seconds from epoch
4645 # my ($self, $template, %options) = @_;
4647 # return unless $conf->exists($template);
4649 # my $from = $conf->invoice_from_full($self->agentnum)
4650 # if $conf->exists('invoice_from', $self->agentnum);
4651 # $from = $options{from} if exists($options{from});
4653 # my $to = join(',', $self->invoicing_list_emailonly);
4654 # $to = $options{to} if exists($options{to});
4656 # my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4657 # if $conf->exists('company_name', $self->agentnum);
4658 # $subject = $options{subject} if exists($options{subject});
4660 # my $notify_template = new Text::Template (TYPE => 'ARRAY',
4661 # SOURCE => [ map "$_\n",
4662 # $conf->config($template)]
4664 # or die "can't create new Text::Template object: Text::Template::ERROR";
4665 # $notify_template->compile()
4666 # or die "can't compile template: Text::Template::ERROR";
4668 # $FS::notify_template::_template::company_name =
4669 # $conf->config('company_name', $self->agentnum);
4670 # $FS::notify_template::_template::company_address =
4671 # join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4673 # my $paydate = $self->paydate || '2037-12-31';
4674 # $FS::notify_template::_template::first = $self->first;
4675 # $FS::notify_template::_template::last = $self->last;
4676 # $FS::notify_template::_template::company = $self->company;
4677 # $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4678 # my $payby = $self->payby;
4679 # my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4680 # my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4682 # #credit cards expire at the end of the month/year of their exp date
4683 # if ($payby eq 'CARD' || $payby eq 'DCRD') {
4684 # $FS::notify_template::_template::payby = 'credit card';
4685 # ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4686 # $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4688 # }elsif ($payby eq 'COMP') {
4689 # $FS::notify_template::_template::payby = 'complimentary account';
4691 # $FS::notify_template::_template::payby = 'current method';
4693 # $FS::notify_template::_template::expdate = $expire_time;
4695 # for (keys %{$options{extra_fields}}){
4697 # ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4700 # send_email(from => $from,
4702 # subject => $subject,
4703 # body => $notify_template->fill_in( PACKAGE =>
4704 # 'FS::notify_template::_template' ),
4709 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4711 Generates a templated notification to the customer (see L<Text::Template>).
4713 OPTIONS is a hash and may include
4715 I<extra_fields> - a hashref of name/value pairs which will be substituted
4716 into the template. These values may override values mentioned below
4717 and those from the customer record.
4719 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
4721 The following variables are available in the template instead of or in addition
4722 to the fields of the customer record.
4724 I<$payby> - a description of the method of payment for the customer
4725 # would be nice to use FS::payby::shortname
4726 I<$payinfo> - the masked account information used to collect for this customer
4727 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4728 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4732 # a lot like cust_bill::print_latex
4733 sub generate_letter {
4734 my ($self, $template, %options) = @_;
4736 warn "Template $template does not exist" && return
4737 unless $conf->exists($template) || $options{'template_text'};
4739 my $template_source = $options{'template_text'}
4740 ? [ $options{'template_text'} ]
4741 : [ map "$_\n", $conf->config($template) ];
4743 my $letter_template = new Text::Template
4745 SOURCE => $template_source,
4746 DELIMITERS => [ '[@--', '--@]' ],
4748 or die "can't create new Text::Template object: Text::Template::ERROR";
4750 $letter_template->compile()
4751 or die "can't compile template: Text::Template::ERROR";
4753 my %letter_data = map { $_ => $self->$_ } $self->fields;
4754 $letter_data{payinfo} = $self->mask_payinfo;
4756 #my $paydate = $self->paydate || '2037-12-31';
4757 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4759 my $payby = $self->payby;
4760 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4761 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4763 #credit cards expire at the end of the month/year of their exp date
4764 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4765 $letter_data{payby} = 'credit card';
4766 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4767 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4769 }elsif ($payby eq 'COMP') {
4770 $letter_data{payby} = 'complimentary account';
4772 $letter_data{payby} = 'current method';
4774 $letter_data{expdate} = $expire_time;
4776 for (keys %{$options{extra_fields}}){
4777 $letter_data{$_} = $options{extra_fields}->{$_};
4780 unless(exists($letter_data{returnaddress})){
4781 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4782 $self->agent_template)
4784 if ( length($retadd) ) {
4785 $letter_data{returnaddress} = $retadd;
4786 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4787 $letter_data{returnaddress} =
4788 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4792 ( $conf->config('company_name', $self->agentnum),
4793 $conf->config('company_address', $self->agentnum),
4797 $letter_data{returnaddress} = '~';
4801 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4803 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4805 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4807 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4811 ) or die "can't open temp file: $!\n";
4812 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4813 or die "can't write temp file: $!\n";
4815 $letter_data{'logo_file'} = $lh->filename;
4817 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4821 ) or die "can't open temp file: $!\n";
4823 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4825 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4826 return ($1, $letter_data{'logo_file'});
4830 =item print_ps TEMPLATE
4832 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4838 my($file, $lfile) = $self->generate_letter(@_);
4839 my $ps = FS::Misc::generate_ps($file);
4840 unlink($file.'.tex');
4846 =item print TEMPLATE
4848 Prints the filled in template.
4850 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4854 sub queueable_print {
4857 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4858 or die "invalid customer number: " . $opt{custnum};
4860 #do not backport this change to 3.x
4861 # my $error = $self->print( { 'template' => $opt{template} } );
4862 my $error = $self->print( $opt{'template'} );
4863 die $error if $error;
4867 my ($self, $template) = (shift, shift);
4869 [ $self->print_ps($template) ],
4870 'agentnum' => $self->agentnum,
4874 #these three subs should just go away once agent stuff is all config overrides
4876 sub agent_template {
4878 $self->_agent_plandata('agent_templatename');
4881 sub agent_invoice_from {
4883 $self->_agent_plandata('agent_invoice_from');
4886 sub _agent_plandata {
4887 my( $self, $option ) = @_;
4889 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4890 #agent-specific Conf
4892 use FS::part_event::Condition;
4894 my $agentnum = $self->agentnum;
4896 my $regexp = regexp_sql();
4898 my $part_event_option =
4900 'select' => 'part_event_option.*',
4901 'table' => 'part_event_option',
4903 LEFT JOIN part_event USING ( eventpart )
4904 LEFT JOIN part_event_option AS peo_agentnum
4905 ON ( part_event.eventpart = peo_agentnum.eventpart
4906 AND peo_agentnum.optionname = 'agentnum'
4907 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4909 LEFT JOIN part_event_condition
4910 ON ( part_event.eventpart = part_event_condition.eventpart
4911 AND part_event_condition.conditionname = 'cust_bill_age'
4913 LEFT JOIN part_event_condition_option
4914 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4915 AND part_event_condition_option.optionname = 'age'
4918 #'hashref' => { 'optionname' => $option },
4919 #'hashref' => { 'part_event_option.optionname' => $option },
4921 " WHERE part_event_option.optionname = ". dbh->quote($option).
4922 " AND action = 'cust_bill_send_agent' ".
4923 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4924 " AND peo_agentnum.optionname = 'agentnum' ".
4925 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4927 CASE WHEN part_event_condition_option.optionname IS NULL
4929 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4931 , part_event.weight".
4935 unless ( $part_event_option ) {
4936 return $self->agent->invoice_template || ''
4937 if $option eq 'agent_templatename';
4941 $part_event_option->optionvalue;
4945 sub process_o2m_qsearch {
4948 return qsearch($table, @_) unless $table eq 'contact';
4950 my $hashref = shift;
4951 my %hash = %$hashref;
4952 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4953 or die 'guru meditation #4343';
4955 qsearch({ 'table' => 'contact',
4956 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4957 'hashref' => \%hash,
4958 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4959 " cust_contact.custnum = $custnum "
4963 sub process_o2m_qsearchs {
4966 return qsearchs($table, @_) unless $table eq 'contact';
4968 my $hashref = shift;
4969 my %hash = %$hashref;
4970 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4971 or die 'guru meditation #2121';
4973 qsearchs({ 'table' => 'contact',
4974 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4975 'hashref' => \%hash,
4976 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4977 " cust_contact.custnum = $custnum "
4981 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4983 Subroutine (not a method), designed to be called from the queue.
4985 Takes a list of options and values.
4987 Pulls up the customer record via the custnum option and calls bill_and_collect.
4992 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4994 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4995 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4997 #without this errors don't get rolled back
4998 $args{'fatal'} = 1; # runs from job queue, will be caught
5000 $cust_main->bill_and_collect( %args );
5003 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5005 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5006 C<collect> part. This is used in batch tax calculation, where invoice
5007 generation and collection events have to be completely separated.
5011 sub queued_collect {
5013 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5015 $cust_main->collect(%args);
5018 sub process_bill_and_collect {
5021 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5022 or die "custnum '$param->{custnum}' not found!\n";
5023 $param->{'job'} = $job;
5024 $param->{'fatal'} = 1; # runs from job queue, will be caught
5025 $param->{'retry'} = 1;
5027 $cust_main->bill_and_collect( %$param );
5030 #starting to take quite a while for big dbs
5031 # (JRNL: journaled so it only happens once per database)
5032 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5033 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5034 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5035 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5036 # JRNL leading/trailing spaces in first, last, company
5037 # JRNL migrate to cust_payby
5038 # - otaker upgrade? journal and call it good? (double check to make sure
5039 # we're not still setting otaker here)
5041 #only going to get worse with new location stuff...
5043 sub _upgrade_data { #class method
5044 my ($class, %opts) = @_;
5047 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5050 #this seems to be the only expensive one.. why does it take so long?
5051 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5053 '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';
5054 FS::upgrade_journal->set_done('cust_main__signupdate');
5057 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5059 # fix yyyy-m-dd formatted paydates
5060 if ( driver_name =~ /^mysql/i ) {
5062 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5063 } else { # the SQL standard
5065 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5067 FS::upgrade_journal->set_done('cust_main__paydate');
5070 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5072 push @statements, #fix the weird BILL with a cc# in payinfo problem
5074 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5076 FS::upgrade_journal->set_done('cust_main__payinfo');
5081 foreach my $sql ( @statements ) {
5082 my $sth = dbh->prepare($sql) or die dbh->errstr;
5083 $sth->execute or die $sth->errstr;
5084 #warn ( (time - $t). " seconds\n" );
5088 local($ignore_expired_card) = 1;
5089 local($ignore_banned_card) = 1;
5090 local($skip_fuzzyfiles) = 1;
5091 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5093 FS::cust_main::Location->_upgrade_data(%opts);
5095 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5097 foreach my $cust_main ( qsearch({
5098 'table' => 'cust_main',
5100 'extra_sql' => 'WHERE '.
5102 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5103 qw( first last company )
5106 my $error = $cust_main->replace;
5107 die $error if $error;
5110 FS::upgrade_journal->set_done('cust_main__trimspaces');
5114 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5116 #we don't want to decrypt them, just stuff them as-is into cust_payby
5117 local(@encrypted_fields) = ();
5119 local($FS::cust_payby::ignore_expired_card) = 1;
5120 local($FS::cust_payby::ignore_banned_card) = 1;
5122 my @payfields = qw( payby payinfo paycvv paymask
5123 paydate paystart_month paystart_year payissue
5124 payname paystate paytype payip
5127 my $search = new FS::Cursor {
5128 'table' => 'cust_main',
5129 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5132 while (my $cust_main = $search->fetch) {
5134 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
5136 my $cust_payby = new FS::cust_payby {
5137 'custnum' => $cust_main->custnum,
5139 map { $_ => $cust_main->$_(); } @payfields
5142 my $error = $cust_payby->insert;
5143 die $error if $error;
5147 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
5149 $cust_main->invoice_attn( $cust_main->payname )
5150 if $cust_main->payby eq 'BILL' && $cust_main->payname;
5151 $cust_main->po_number( $cust_main->payinfo )
5152 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
5154 $cust_main->setfield($_, '') foreach @payfields;
5155 my $error = $cust_main->replace;
5156 die "Error upgradging payment information for custnum ".
5157 $cust_main->custnum. ": $error"
5162 FS::upgrade_journal->set_done('cust_main__cust_payby');
5165 $class->_upgrade_otaker(%opts);
5175 The delete method should possibly take an FS::cust_main object reference
5176 instead of a scalar customer number.
5178 Bill and collect options should probably be passed as references instead of a
5181 There should probably be a configuration file with a list of allowed credit
5184 No multiple currency support (probably a larger project than just this module).
5186 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5188 Birthdates rely on negative epoch values.
5190 The payby for card/check batches is broken. With mixed batching, bad
5193 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5197 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5198 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5199 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.