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_email send_email 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 ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
604 my $error = $self->process_o2m(
605 'table' => 'cust_payby',
606 'fields' => FS::cust_payby->cgi_cust_payby_fields,
607 'params' => $cust_payby_params,
608 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
611 $dbh->rollback if $oldAutoCommit;
617 warn " setting cust_main_exemption\n"
620 my $tax_exemption = delete $options{'tax_exemption'};
621 if ( $tax_exemption ) {
623 $tax_exemption = { map { $_ => '' } @$tax_exemption }
624 if ref($tax_exemption) eq 'ARRAY';
626 foreach my $taxname ( keys %$tax_exemption ) {
627 my $cust_main_exemption = new FS::cust_main_exemption {
628 'custnum' => $self->custnum,
629 'taxname' => $taxname,
630 'exempt_number' => $tax_exemption->{$taxname},
632 my $error = $cust_main_exemption->insert;
634 $dbh->rollback if $oldAutoCommit;
635 return "inserting cust_main_exemption (transaction rolled back): $error";
640 warn " ordering packages\n"
643 $error = $self->order_pkgs( $cust_pkgs,
645 'seconds_ref' => \$seconds,
646 'upbytes_ref' => \$upbytes,
647 'downbytes_ref' => \$downbytes,
648 'totalbytes_ref' => \$totalbytes,
651 $dbh->rollback if $oldAutoCommit;
656 $dbh->rollback if $oldAutoCommit;
657 return "No svc_acct record to apply pre-paid time";
659 if ( $upbytes || $downbytes || $totalbytes ) {
660 $dbh->rollback if $oldAutoCommit;
661 return "No svc_acct record to apply pre-paid data";
665 warn " inserting initial $payby payment of $amount\n"
667 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
669 $dbh->rollback if $oldAutoCommit;
670 return "inserting payment (transaction rolled back): $error";
674 unless ( $import || $skip_fuzzyfiles ) {
675 warn " queueing fuzzyfiles update\n"
677 $error = $self->queue_fuzzyfiles_update;
679 $dbh->rollback if $oldAutoCommit;
680 return "updating fuzzy search cache: $error";
684 # FS::geocode_Mixin::after_insert or something?
685 if ( $conf->config('tax_district_method') and !$import ) {
686 # if anything non-empty, try to look it up
687 my $queue = new FS::queue {
688 'job' => 'FS::geocode_Mixin::process_district_update',
689 'custnum' => $self->custnum,
691 my $error = $queue->insert( ref($self), $self->custnum );
693 $dbh->rollback if $oldAutoCommit;
694 return "queueing tax district update: $error";
699 warn " exporting\n" if $DEBUG > 1;
701 my $export_args = $options{'export_args'} || [];
704 map qsearch( 'part_export', {exportnum=>$_} ),
705 $conf->config('cust_main-exports'); #, $agentnum
707 foreach my $part_export ( @part_export ) {
708 my $error = $part_export->export_insert($self, @$export_args);
710 $dbh->rollback if $oldAutoCommit;
711 return "exporting to ". $part_export->exporttype.
712 " (transaction rolled back): $error";
716 #foreach my $depend_jobnum ( @$depend_jobnums ) {
717 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
719 # foreach my $jobnum ( @jobnums ) {
720 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
721 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
723 # my $error = $queue->depend_insert($depend_jobnum);
725 # $dbh->rollback if $oldAutoCommit;
726 # return "error queuing job dependancy: $error";
733 #if ( exists $options{'jobnums'} ) {
734 # push @{ $options{'jobnums'} }, @jobnums;
737 warn " insert complete; committing transaction\n"
740 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
745 use File::CounterFile;
746 sub auto_agent_custid {
749 my $format = $conf->config('cust_main-auto_agent_custid');
751 if ( $format eq '1YMMXXXXXXXX' ) {
753 my $counter = new File::CounterFile 'cust_main.agent_custid';
756 my $ym = 100000000000 + time2str('%y%m00000000', time);
757 if ( $ym > $counter->value ) {
758 $counter->{'value'} = $agent_custid = $ym;
759 $counter->{'updated'} = 1;
761 $agent_custid = $counter->inc;
767 die "Unknown cust_main-auto_agent_custid format: $format";
770 $self->agent_custid($agent_custid);
774 =item PACKAGE METHODS
776 Documentation on customer package methods has been moved to
777 L<FS::cust_main::Packages>.
779 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
781 Recharges this (existing) customer with the specified prepaid card (see
782 L<FS::prepay_credit>), specified either by I<identifier> or as an
783 FS::prepay_credit object. If there is an error, returns the error, otherwise
786 Optionally, five scalar references can be passed as well. They will have their
787 values filled in with the amount, number of seconds, and number of upload,
788 download, and total bytes applied by this prepaid card.
792 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
793 #the only place that uses these args
794 sub recharge_prepay {
795 my( $self, $prepay_credit, $amountref, $secondsref,
796 $upbytesref, $downbytesref, $totalbytesref ) = @_;
798 local $SIG{HUP} = 'IGNORE';
799 local $SIG{INT} = 'IGNORE';
800 local $SIG{QUIT} = 'IGNORE';
801 local $SIG{TERM} = 'IGNORE';
802 local $SIG{TSTP} = 'IGNORE';
803 local $SIG{PIPE} = 'IGNORE';
805 my $oldAutoCommit = $FS::UID::AutoCommit;
806 local $FS::UID::AutoCommit = 0;
809 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
811 my $error = $self->get_prepay( $prepay_credit,
812 'amount_ref' => \$amount,
813 'seconds_ref' => \$seconds,
814 'upbytes_ref' => \$upbytes,
815 'downbytes_ref' => \$downbytes,
816 'totalbytes_ref' => \$totalbytes,
818 || $self->increment_seconds($seconds)
819 || $self->increment_upbytes($upbytes)
820 || $self->increment_downbytes($downbytes)
821 || $self->increment_totalbytes($totalbytes)
822 || $self->insert_cust_pay_prepay( $amount,
824 ? $prepay_credit->identifier
829 $dbh->rollback if $oldAutoCommit;
833 if ( defined($amountref) ) { $$amountref = $amount; }
834 if ( defined($secondsref) ) { $$secondsref = $seconds; }
835 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
836 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
837 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
839 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
844 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
846 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
847 specified either by I<identifier> or as an FS::prepay_credit object.
849 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
850 incremented by the values of the prepaid card.
852 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
853 check or set this customer's I<agentnum>.
855 If there is an error, returns the error, otherwise returns false.
861 my( $self, $prepay_credit, %opt ) = @_;
863 local $SIG{HUP} = 'IGNORE';
864 local $SIG{INT} = 'IGNORE';
865 local $SIG{QUIT} = 'IGNORE';
866 local $SIG{TERM} = 'IGNORE';
867 local $SIG{TSTP} = 'IGNORE';
868 local $SIG{PIPE} = 'IGNORE';
870 my $oldAutoCommit = $FS::UID::AutoCommit;
871 local $FS::UID::AutoCommit = 0;
874 unless ( ref($prepay_credit) ) {
876 my $identifier = $prepay_credit;
878 $prepay_credit = qsearchs(
880 { 'identifier' => $identifier },
885 unless ( $prepay_credit ) {
886 $dbh->rollback if $oldAutoCommit;
887 return "Invalid prepaid card: ". $identifier;
892 if ( $prepay_credit->agentnum ) {
893 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
894 $dbh->rollback if $oldAutoCommit;
895 return "prepaid card not valid for agent ". $self->agentnum;
897 $self->agentnum($prepay_credit->agentnum);
900 my $error = $prepay_credit->delete;
902 $dbh->rollback if $oldAutoCommit;
903 return "removing prepay_credit (transaction rolled back): $error";
906 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
907 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
909 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
914 =item increment_upbytes SECONDS
916 Updates this customer's single or primary account (see L<FS::svc_acct>) by
917 the specified number of upbytes. If there is an error, returns the error,
918 otherwise returns false.
922 sub increment_upbytes {
923 _increment_column( shift, 'upbytes', @_);
926 =item increment_downbytes SECONDS
928 Updates this customer's single or primary account (see L<FS::svc_acct>) by
929 the specified number of downbytes. If there is an error, returns the error,
930 otherwise returns false.
934 sub increment_downbytes {
935 _increment_column( shift, 'downbytes', @_);
938 =item increment_totalbytes SECONDS
940 Updates this customer's single or primary account (see L<FS::svc_acct>) by
941 the specified number of totalbytes. If there is an error, returns the error,
942 otherwise returns false.
946 sub increment_totalbytes {
947 _increment_column( shift, 'totalbytes', @_);
950 =item increment_seconds SECONDS
952 Updates this customer's single or primary account (see L<FS::svc_acct>) by
953 the specified number of seconds. If there is an error, returns the error,
954 otherwise returns false.
958 sub increment_seconds {
959 _increment_column( shift, 'seconds', @_);
962 =item _increment_column AMOUNT
964 Updates this customer's single or primary account (see L<FS::svc_acct>) by
965 the specified number of seconds or bytes. If there is an error, returns
966 the error, otherwise returns false.
970 sub _increment_column {
971 my( $self, $column, $amount ) = @_;
972 warn "$me increment_column called: $column, $amount\n"
975 return '' unless $amount;
977 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
978 $self->ncancelled_pkgs;
981 return 'No packages with primary or single services found'.
982 ' to apply pre-paid time';
983 } elsif ( scalar(@cust_pkg) > 1 ) {
984 #maybe have a way to specify the package/account?
985 return 'Multiple packages found to apply pre-paid time';
988 my $cust_pkg = $cust_pkg[0];
989 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
993 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
996 return 'No account found to apply pre-paid time';
997 } elsif ( scalar(@cust_svc) > 1 ) {
998 return 'Multiple accounts found to apply pre-paid time';
1001 my $svc_acct = $cust_svc[0]->svc_x;
1002 warn " found service svcnum ". $svc_acct->pkgnum.
1003 ' ('. $svc_acct->email. ")\n"
1006 $column = "increment_$column";
1007 $svc_acct->$column($amount);
1011 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1013 Inserts a prepayment in the specified amount for this customer. An optional
1014 second argument can specify the prepayment identifier for tracking purposes.
1015 If there is an error, returns the error, otherwise returns false.
1019 sub insert_cust_pay_prepay {
1020 shift->insert_cust_pay('PREP', @_);
1023 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1025 Inserts a cash payment in the specified amount for this customer. An optional
1026 second argument can specify the payment identifier for tracking purposes.
1027 If there is an error, returns the error, otherwise returns false.
1031 sub insert_cust_pay_cash {
1032 shift->insert_cust_pay('CASH', @_);
1035 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1037 Inserts a Western Union payment in the specified amount for this customer. An
1038 optional second argument can specify the prepayment identifier for tracking
1039 purposes. If there is an error, returns the error, otherwise returns false.
1043 sub insert_cust_pay_west {
1044 shift->insert_cust_pay('WEST', @_);
1047 sub insert_cust_pay {
1048 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1049 my $payinfo = scalar(@_) ? shift : '';
1051 my $cust_pay = new FS::cust_pay {
1052 'custnum' => $self->custnum,
1053 'paid' => sprintf('%.2f', $amount),
1054 #'_date' => #date the prepaid card was purchased???
1056 'payinfo' => $payinfo,
1062 =item delete [ OPTION => VALUE ... ]
1064 This deletes the customer. If there is an error, returns the error, otherwise
1067 This will completely remove all traces of the customer record. This is not
1068 what you want when a customer cancels service; for that, cancel all of the
1069 customer's packages (see L</cancel>).
1071 If the customer has any uncancelled packages, you need to pass a new (valid)
1072 customer number for those packages to be transferred to, as the "new_customer"
1073 option. Cancelled packages will be deleted. Did I mention that this is NOT
1074 what you want when a customer cancels service and that you really should be
1075 looking at L<FS::cust_pkg/cancel>?
1077 You can't delete a customer with invoices (see L<FS::cust_bill>),
1078 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1079 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1080 set the "delete_financials" option to a true value.
1085 my( $self, %opt ) = @_;
1087 local $SIG{HUP} = 'IGNORE';
1088 local $SIG{INT} = 'IGNORE';
1089 local $SIG{QUIT} = 'IGNORE';
1090 local $SIG{TERM} = 'IGNORE';
1091 local $SIG{TSTP} = 'IGNORE';
1092 local $SIG{PIPE} = 'IGNORE';
1094 my $oldAutoCommit = $FS::UID::AutoCommit;
1095 local $FS::UID::AutoCommit = 0;
1098 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1099 $dbh->rollback if $oldAutoCommit;
1100 return "Can't delete a master agent customer";
1103 #use FS::access_user
1104 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1105 $dbh->rollback if $oldAutoCommit;
1106 return "Can't delete a master employee customer";
1109 tie my %financial_tables, 'Tie::IxHash',
1110 'cust_bill' => 'invoices',
1111 'cust_statement' => 'statements',
1112 'cust_credit' => 'credits',
1113 'cust_pay' => 'payments',
1114 'cust_refund' => 'refunds',
1117 foreach my $table ( keys %financial_tables ) {
1119 my @records = $self->$table();
1121 if ( @records && ! $opt{'delete_financials'} ) {
1122 $dbh->rollback if $oldAutoCommit;
1123 return "Can't delete a customer with ". $financial_tables{$table};
1126 foreach my $record ( @records ) {
1127 my $error = $record->delete;
1129 $dbh->rollback if $oldAutoCommit;
1130 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1136 my @cust_pkg = $self->ncancelled_pkgs;
1138 my $new_custnum = $opt{'new_custnum'};
1139 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1140 $dbh->rollback if $oldAutoCommit;
1141 return "Invalid new customer number: $new_custnum";
1143 foreach my $cust_pkg ( @cust_pkg ) {
1144 my %hash = $cust_pkg->hash;
1145 $hash{'custnum'} = $new_custnum;
1146 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1147 my $error = $new_cust_pkg->replace($cust_pkg,
1148 options => { $cust_pkg->options },
1151 $dbh->rollback if $oldAutoCommit;
1156 my @cancelled_cust_pkg = $self->all_pkgs;
1157 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1158 my $error = $cust_pkg->delete;
1160 $dbh->rollback if $oldAutoCommit;
1165 #cust_tax_adjustment in financials?
1166 #cust_pay_pending? ouch
1167 foreach my $table (qw(
1168 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1169 cust_payby cust_location cust_main_note cust_tax_adjustment
1170 cust_pay_void cust_pay_batch queue cust_tax_exempt
1172 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1173 my $error = $record->delete;
1175 $dbh->rollback if $oldAutoCommit;
1181 my $sth = $dbh->prepare(
1182 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1184 my $errstr = $dbh->errstr;
1185 $dbh->rollback if $oldAutoCommit;
1188 $sth->execute($self->custnum) or do {
1189 my $errstr = $sth->errstr;
1190 $dbh->rollback if $oldAutoCommit;
1196 my $ticket_dbh = '';
1197 if ($conf->config('ticket_system') eq 'RT_Internal') {
1199 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1200 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1201 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1202 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1205 if ( $ticket_dbh ) {
1207 my $ticket_sth = $ticket_dbh->prepare(
1208 'DELETE FROM Links WHERE Target = ?'
1210 my $errstr = $ticket_dbh->errstr;
1211 $dbh->rollback if $oldAutoCommit;
1214 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1216 my $errstr = $ticket_sth->errstr;
1217 $dbh->rollback if $oldAutoCommit;
1221 #check and see if the customer is the only link on the ticket, and
1222 #if so, set the ticket to deleted status in RT?
1223 #maybe someday, for now this will at least fix tickets not displaying
1227 #delete the customer record
1229 my $error = $self->SUPER::delete;
1231 $dbh->rollback if $oldAutoCommit;
1235 # cust_main exports!
1237 #my $export_args = $options{'export_args'} || [];
1240 map qsearch( 'part_export', {exportnum=>$_} ),
1241 $conf->config('cust_main-exports'); #, $agentnum
1243 foreach my $part_export ( @part_export ) {
1244 my $error = $part_export->export_delete( $self ); #, @$export_args);
1246 $dbh->rollback if $oldAutoCommit;
1247 return "exporting to ". $part_export->exporttype.
1248 " (transaction rolled back): $error";
1252 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1257 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1259 Replaces the OLD_RECORD with this one in the database. If there is an error,
1260 returns the error, otherwise returns false.
1262 To change the customer's address, set the pseudo-fields C<bill_location> and
1263 C<ship_location>. The address will still only change if at least one of the
1264 address fields differs from the existing values.
1266 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1267 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1268 expected and rollback the entire transaction; it is not necessary to call
1269 check_invoicing_list first. Here's an example:
1271 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1273 Currently available options are: I<tax_exemption>.
1275 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1276 of tax names and exemption numbers. FS::cust_main_exemption records will be
1277 deleted and inserted as appropriate.
1284 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1286 : $self->replace_old;
1290 warn "$me replace called\n"
1293 my $curuser = $FS::CurrentUser::CurrentUser;
1294 return "You are not permitted to create complimentary accounts."
1295 if $self->complimentary eq 'Y'
1296 && $self->complimentary ne $old->complimentary
1297 && ! $curuser->access_right('Complimentary customer');
1299 local($ignore_expired_card) = 1
1300 if $old->payby =~ /^(CARD|DCRD)$/
1301 && $self->payby =~ /^(CARD|DCRD)$/
1302 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1304 local($ignore_banned_card) = 1
1305 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1306 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1307 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1309 return "Invoicing locale is required"
1312 && $conf->exists('cust_main-require_locale');
1314 local $SIG{HUP} = 'IGNORE';
1315 local $SIG{INT} = 'IGNORE';
1316 local $SIG{QUIT} = 'IGNORE';
1317 local $SIG{TERM} = 'IGNORE';
1318 local $SIG{TSTP} = 'IGNORE';
1319 local $SIG{PIPE} = 'IGNORE';
1321 my $oldAutoCommit = $FS::UID::AutoCommit;
1322 local $FS::UID::AutoCommit = 0;
1325 for my $l (qw(bill_location ship_location)) {
1326 #my $old_loc = $old->$l;
1327 my $new_loc = $self->$l or next;
1329 # find the existing location if there is one
1330 $new_loc->set('custnum' => $self->custnum);
1331 my $error = $new_loc->find_or_insert;
1333 $dbh->rollback if $oldAutoCommit;
1336 $self->set($l.'num', $new_loc->locationnum);
1339 # replace the customer record
1340 my $error = $self->SUPER::replace($old);
1343 $dbh->rollback if $oldAutoCommit;
1347 # now move packages to the new service location
1348 $self->set('ship_location', ''); #flush cache
1349 if ( $old->ship_locationnum and # should only be null during upgrade...
1350 $old->ship_locationnum != $self->ship_locationnum ) {
1351 $error = $old->ship_location->move_to($self->ship_location);
1353 $dbh->rollback if $oldAutoCommit;
1357 # don't move packages based on the billing location, but
1358 # disable it if it's no longer in use
1359 if ( $old->bill_locationnum and
1360 $old->bill_locationnum != $self->bill_locationnum ) {
1361 $error = $old->bill_location->disable_if_unused;
1363 $dbh->rollback if $oldAutoCommit;
1368 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1369 my $invoicing_list = shift @param;
1370 $error = $self->check_invoicing_list( $invoicing_list );
1372 $dbh->rollback if $oldAutoCommit;
1375 $self->invoicing_list( $invoicing_list );
1378 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1380 #this could be more efficient than deleting and re-inserting, if it matters
1381 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1382 my $error = $cust_tag->delete;
1384 $dbh->rollback if $oldAutoCommit;
1388 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1389 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1390 'custnum' => $self->custnum };
1391 my $error = $cust_tag->insert;
1393 $dbh->rollback if $oldAutoCommit;
1400 my %options = @param;
1402 my $tax_exemption = delete $options{'tax_exemption'};
1403 if ( $tax_exemption ) {
1405 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1406 if ref($tax_exemption) eq 'ARRAY';
1408 my %cust_main_exemption =
1409 map { $_->taxname => $_ }
1410 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1412 foreach my $taxname ( keys %$tax_exemption ) {
1414 if ( $cust_main_exemption{$taxname} &&
1415 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1418 delete $cust_main_exemption{$taxname};
1422 my $cust_main_exemption = new FS::cust_main_exemption {
1423 'custnum' => $self->custnum,
1424 'taxname' => $taxname,
1425 'exempt_number' => $tax_exemption->{$taxname},
1427 my $error = $cust_main_exemption->insert;
1429 $dbh->rollback if $oldAutoCommit;
1430 return "inserting cust_main_exemption (transaction rolled back): $error";
1434 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1435 my $error = $cust_main_exemption->delete;
1437 $dbh->rollback if $oldAutoCommit;
1438 return "deleting cust_main_exemption (transaction rolled back): $error";
1444 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1446 my $error = $self->process_o2m(
1447 'table' => 'cust_payby',
1448 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1449 'params' => $cust_payby_params,
1450 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1453 $dbh->rollback if $oldAutoCommit;
1459 unless ( $import || $skip_fuzzyfiles ) {
1460 $error = $self->queue_fuzzyfiles_update;
1462 $dbh->rollback if $oldAutoCommit;
1463 return "updating fuzzy search cache: $error";
1467 # tax district update in cust_location
1469 # cust_main exports!
1471 my $export_args = $options{'export_args'} || [];
1474 map qsearch( 'part_export', {exportnum=>$_} ),
1475 $conf->config('cust_main-exports'); #, $agentnum
1477 foreach my $part_export ( @part_export ) {
1478 my $error = $part_export->export_replace( $self, $old, @$export_args);
1480 $dbh->rollback if $oldAutoCommit;
1481 return "exporting to ". $part_export->exporttype.
1482 " (transaction rolled back): $error";
1486 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1491 =item queue_fuzzyfiles_update
1493 Used by insert & replace to update the fuzzy search cache
1497 use FS::cust_main::Search;
1498 sub queue_fuzzyfiles_update {
1501 local $SIG{HUP} = 'IGNORE';
1502 local $SIG{INT} = 'IGNORE';
1503 local $SIG{QUIT} = 'IGNORE';
1504 local $SIG{TERM} = 'IGNORE';
1505 local $SIG{TSTP} = 'IGNORE';
1506 local $SIG{PIPE} = 'IGNORE';
1508 my $oldAutoCommit = $FS::UID::AutoCommit;
1509 local $FS::UID::AutoCommit = 0;
1512 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1513 my $queue = new FS::queue {
1514 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1516 my @args = "cust_main.$field", $self->get($field);
1517 my $error = $queue->insert( @args );
1519 $dbh->rollback if $oldAutoCommit;
1520 return "queueing job (transaction rolled back): $error";
1525 push @locations, $self->bill_location if $self->bill_locationnum;
1526 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1527 foreach my $location (@locations) {
1528 my $queue = new FS::queue {
1529 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1531 my @args = 'cust_location.address1', $location->address1;
1532 my $error = $queue->insert( @args );
1534 $dbh->rollback if $oldAutoCommit;
1535 return "queueing job (transaction rolled back): $error";
1539 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1546 Checks all fields to make sure this is a valid customer record. If there is
1547 an error, returns the error, otherwise returns false. Called by the insert
1548 and replace methods.
1555 warn "$me check BEFORE: \n". $self->_dump
1559 $self->ut_numbern('custnum')
1560 || $self->ut_number('agentnum')
1561 || $self->ut_textn('agent_custid')
1562 || $self->ut_number('refnum')
1563 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1564 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1565 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1566 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1567 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1568 || $self->ut_textn('custbatch')
1569 || $self->ut_name('last')
1570 || $self->ut_name('first')
1571 || $self->ut_snumbern('signupdate')
1572 || $self->ut_snumbern('birthdate')
1573 || $self->ut_namen('spouse_last')
1574 || $self->ut_namen('spouse_first')
1575 || $self->ut_snumbern('spouse_birthdate')
1576 || $self->ut_snumbern('anniversary_date')
1577 || $self->ut_textn('company')
1578 || $self->ut_textn('ship_company')
1579 || $self->ut_anything('comments')
1580 || $self->ut_numbern('referral_custnum')
1581 || $self->ut_textn('stateid')
1582 || $self->ut_textn('stateid_state')
1583 || $self->ut_textn('invoice_terms')
1584 || $self->ut_floatn('cdr_termination_percentage')
1585 || $self->ut_floatn('credit_limit')
1586 || $self->ut_numbern('billday')
1587 || $self->ut_numbern('prorate_day')
1588 || $self->ut_flag('edit_subject')
1589 || $self->ut_flag('calling_list_exempt')
1590 || $self->ut_flag('invoice_noemail')
1591 || $self->ut_flag('message_noemail')
1592 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1593 || $self->ut_currencyn('currency')
1594 || $self->ut_alphan('po_number')
1595 || $self->ut_enum('complimentary', [ '', 'Y' ])
1596 || $self->ut_flag('invoice_ship_address')
1599 foreach (qw(company ship_company)) {
1600 my $company = $self->get($_);
1601 $company =~ s/^\s+//;
1602 $company =~ s/\s+$//;
1603 $company =~ s/\s+/ /g;
1604 $self->set($_, $company);
1607 #barf. need message catalogs. i18n. etc.
1608 $error .= "Please select an advertising source."
1609 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1610 return $error if $error;
1612 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1613 or return "Unknown agent";
1615 if ( $self->currency ) {
1616 my $agent_currency = qsearchs( 'agent_currency', {
1617 'agentnum' => $agent->agentnum,
1618 'currency' => $self->currency,
1620 or return "Agent ". $agent->agent.
1621 " not permitted to offer ". $self->currency. " invoicing";
1624 return "Unknown refnum"
1625 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1627 return "Unknown referring custnum: ". $self->referral_custnum
1628 unless ! $self->referral_custnum
1629 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1631 if ( $self->ss eq '' ) {
1636 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1637 or return "Illegal social security number: ". $self->ss;
1638 $self->ss("$1-$2-$3");
1641 #turn off invoice_ship_address if ship & bill are the same
1642 if ($self->bill_locationnum eq $self->ship_locationnum) {
1643 $self->invoice_ship_address('');
1646 # cust_main_county verification now handled by cust_location check
1649 $self->ut_phonen('daytime', $self->country)
1650 || $self->ut_phonen('night', $self->country)
1651 || $self->ut_phonen('fax', $self->country)
1652 || $self->ut_phonen('mobile', $self->country)
1654 return $error if $error;
1656 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1658 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1661 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1663 : FS::Msgcat::_gettext('daytime');
1664 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1666 : FS::Msgcat::_gettext('night');
1668 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1670 : FS::Msgcat::_gettext('mobile');
1672 return "$daytime_label, $night_label or $mobile_label is required"
1676 ### start of stuff moved to cust_payby
1677 # then mostly kept here to support upgrades (can remove in 5.x)
1678 # but modified to allow everything to be empty
1680 if ( $self->payby ) {
1681 FS::payby->can_payby($self->table, $self->payby)
1682 or return "Illegal payby: ". $self->payby;
1687 $error = $self->ut_numbern('paystart_month')
1688 || $self->ut_numbern('paystart_year')
1689 || $self->ut_numbern('payissue')
1690 || $self->ut_textn('paytype')
1692 return $error if $error;
1694 if ( $self->payip eq '' ) {
1697 $error = $self->ut_ip('payip');
1698 return $error if $error;
1701 # If it is encrypted and the private key is not availaible then we can't
1702 # check the credit card.
1703 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1705 # Need some kind of global flag to accept invalid cards, for testing
1707 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1708 $self->payby =~ /^(CARD|DCRD)$/ ) {
1710 my $payinfo = $self->payinfo;
1711 $payinfo =~ s/\D//g;
1712 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1713 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1715 $self->payinfo($payinfo);
1717 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1719 return gettext('unknown_card_type')
1720 if $self->payinfo !~ /^99\d{14}$/ #token
1721 && cardtype($self->payinfo) eq "Unknown";
1723 unless ( $ignore_banned_card ) {
1724 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1726 if ( $ban->bantype eq 'warn' ) {
1727 #or others depending on value of $ban->reason ?
1728 return '_duplicate_card'.
1729 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1730 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1731 ' (ban# '. $ban->bannum. ')'
1732 unless $self->override_ban_warn;
1734 return 'Banned credit card: banned on '.
1735 time2str('%a %h %o at %r', $ban->_date).
1736 ' by '. $ban->otaker.
1737 ' (ban# '. $ban->bannum. ')';
1742 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1743 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1744 $self->paycvv =~ /^(\d{4})$/
1745 or return "CVV2 (CID) for American Express cards is four digits.";
1748 $self->paycvv =~ /^(\d{3})$/
1749 or return "CVV2 (CVC2/CID) is three digits.";
1756 my $cardtype = cardtype($payinfo);
1757 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1759 return "Start date or issue number is required for $cardtype cards"
1760 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1762 return "Start month must be between 1 and 12"
1763 if $self->paystart_month
1764 and $self->paystart_month < 1 || $self->paystart_month > 12;
1766 return "Start year must be 1990 or later"
1767 if $self->paystart_year
1768 and $self->paystart_year < 1990;
1770 return "Issue number must be beween 1 and 99"
1772 and $self->payissue < 1 || $self->payissue > 99;
1775 $self->paystart_month('');
1776 $self->paystart_year('');
1777 $self->payissue('');
1780 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1781 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1783 my $payinfo = $self->payinfo;
1784 $payinfo =~ s/[^\d\@\.]//g;
1785 if ( $conf->config('echeck-country') eq 'CA' ) {
1786 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1787 or return 'invalid echeck account@branch.bank';
1788 $payinfo = "$1\@$2.$3";
1789 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1790 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1791 $payinfo = "$1\@$2";
1793 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1794 $payinfo = "$1\@$2";
1796 $self->payinfo($payinfo);
1799 unless ( $ignore_banned_card ) {
1800 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1802 if ( $ban->bantype eq 'warn' ) {
1803 #or others depending on value of $ban->reason ?
1804 return '_duplicate_ach' unless $self->override_ban_warn;
1806 return 'Banned ACH account: banned on '.
1807 time2str('%a %h %o at %r', $ban->_date).
1808 ' by '. $ban->otaker.
1809 ' (ban# '. $ban->bannum. ')';
1814 } elsif ( $self->payby eq 'LECB' ) {
1816 my $payinfo = $self->payinfo;
1817 $payinfo =~ s/\D//g;
1818 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1820 $self->payinfo($payinfo);
1823 } elsif ( $self->payby eq 'BILL' ) {
1825 $error = $self->ut_textn('payinfo');
1826 return "Illegal P.O. number: ". $self->payinfo if $error;
1829 } elsif ( $self->payby eq 'COMP' ) {
1831 my $curuser = $FS::CurrentUser::CurrentUser;
1832 if ( ! $self->custnum
1833 && ! $curuser->access_right('Complimentary customer')
1836 return "You are not permitted to create complimentary accounts."
1839 $error = $self->ut_textn('payinfo');
1840 return "Illegal comp account issuer: ". $self->payinfo if $error;
1843 } elsif ( $self->payby eq 'PREPAY' ) {
1845 my $payinfo = $self->payinfo;
1846 $payinfo =~ s/\W//g; #anything else would just confuse things
1847 $self->payinfo($payinfo);
1848 $error = $self->ut_alpha('payinfo');
1849 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1850 return "Unknown prepayment identifier"
1851 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1856 return "You are not permitted to create complimentary accounts."
1858 && $self->complimentary eq 'Y'
1859 && ! $FS::CurrentUser::CurrentUser->access_right('Complimentary customer');
1861 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1862 return "Expiration date required"
1863 # shouldn't payinfo_check do this?
1864 unless ! $self->payby
1865 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
1869 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1870 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1871 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1872 ( $m, $y ) = ( $2, "19$1" );
1873 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1874 ( $m, $y ) = ( $3, "20$2" );
1876 return "Illegal expiration date: ". $self->paydate;
1878 $m = sprintf('%02d',$m);
1879 $self->paydate("$y-$m-01");
1880 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1881 return gettext('expired_card')
1883 && !$ignore_expired_card
1884 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1887 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1888 ( ! $conf->exists('require_cardname')
1889 || $self->payby !~ /^(CARD|DCRD)$/ )
1891 $self->payname( $self->first. " ". $self->getfield('last') );
1894 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
1895 $self->payname =~ /^([\w \,\.\-\']*)$/
1896 or return gettext('illegal_name'). " payname: ". $self->payname;
1899 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
1900 or return gettext('illegal_name'). " payname: ". $self->payname;
1906 ### end of stuff moved to cust_payby
1908 return "Please select an invoicing locale"
1911 && $conf->exists('cust_main-require_locale');
1913 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1914 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1918 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1920 warn "$me check AFTER: \n". $self->_dump
1923 $self->SUPER::check;
1928 Additional checks for replace only.
1933 my ($new,$old) = @_;
1934 #preserve old value if global config is set
1935 if ($old && $conf->exists('invoice-ship_address')) {
1936 $new->invoice_ship_address($old->invoice_ship_address);
1943 Returns a list of fields which have ship_ duplicates.
1948 qw( last first company
1950 address1 address2 city county state zip country
1952 daytime night fax mobile
1956 =item has_ship_address
1958 Returns true if this customer record has a separate shipping address.
1962 sub has_ship_address {
1964 $self->bill_locationnum != $self->ship_locationnum;
1969 Returns a list of key/value pairs, with the following keys: address1,
1970 adddress2, city, county, state, zip, country, district, and geocode. The
1971 shipping address is used if present.
1977 $self->ship_location->location_hash;
1982 Returns all locations (see L<FS::cust_location>) for this customer.
1988 qsearch('cust_location', { 'custnum' => $self->custnum,
1989 'prospectnum' => '' } );
1994 Returns all contact associations (see L<FS::cust_contact>) for this customer.
2000 qsearch('cust_contact', { 'custnum' => $self->custnum } );
2005 Returns all payment methods (see L<FS::cust_payby>) for this customer.
2012 'table' => 'cust_payby',
2013 'hashref' => { 'custnum' => $self->custnum },
2014 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
2018 sub has_cust_payby_auto {
2021 'table' => 'cust_payby',
2022 'hashref' => { 'custnum' => $self->custnum, },
2023 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2024 'order_by' => 'LIMIT 1',
2031 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2032 and L<FS::cust_pkg>) for this customer, except those on hold.
2034 Returns a list: an empty list on success or a list of errors.
2040 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2045 Unsuspends all suspended packages in the on-hold state (those without setup
2046 dates) for this customer.
2052 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2057 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2059 Returns a list: an empty list on success or a list of errors.
2065 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2068 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2070 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2071 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2072 of a list of pkgparts; the hashref has the following keys:
2076 =item pkgparts - listref of pkgparts
2078 =item (other options are passed to the suspend method)
2083 Returns a list: an empty list on success or a list of errors.
2087 sub suspend_if_pkgpart {
2089 my (@pkgparts, %opt);
2090 if (ref($_[0]) eq 'HASH'){
2091 @pkgparts = @{$_[0]{pkgparts}};
2096 grep { $_->suspend(%opt) }
2097 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2098 $self->unsuspended_pkgs;
2101 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2103 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2104 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2105 instead of a list of pkgparts; the hashref has the following keys:
2109 =item pkgparts - listref of pkgparts
2111 =item (other options are passed to the suspend method)
2115 Returns a list: an empty list on success or a list of errors.
2119 sub suspend_unless_pkgpart {
2121 my (@pkgparts, %opt);
2122 if (ref($_[0]) eq 'HASH'){
2123 @pkgparts = @{$_[0]{pkgparts}};
2128 grep { $_->suspend(%opt) }
2129 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2130 $self->unsuspended_pkgs;
2133 =item cancel [ OPTION => VALUE ... ]
2135 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2137 Available options are:
2141 =item quiet - can be set true to supress email cancellation notices.
2143 =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.
2145 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2147 =item nobill - can be set true to skip billing if it might otherwise be done.
2151 Always returns a list: an empty list on success or a list of errors.
2155 # nb that dates are not specified as valid options to this method
2158 my( $self, %opt ) = @_;
2160 warn "$me cancel called on customer ". $self->custnum. " with options ".
2161 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2164 return ( 'access denied' )
2165 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2167 if ( $opt{'ban'} ) {
2169 foreach my $cust_payby ( $self->cust_payby ) {
2171 #well, if they didn't get decrypted on search, then we don't have to
2172 # try again... queue a job for the server that does have decryption
2173 # capability if we're in a paranoid multi-server implementation?
2174 return ( "Can't (yet) ban encrypted credit cards" )
2175 if $cust_payby->is_encrypted($cust_payby->payinfo);
2177 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2178 my $error = $ban->insert;
2179 return ( $error ) if $error;
2185 my @pkgs = $self->ncancelled_pkgs;
2187 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2189 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2190 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2194 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2195 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2198 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2201 sub _banned_pay_hashref {
2212 'payby' => $payby2ban{$self->payby},
2213 'payinfo' => $self->payinfo,
2214 #don't ever *search* on reason! #'reason' =>
2220 Returns all notes (see L<FS::cust_main_note>) for this customer.
2225 my($self,$orderby_classnum) = (shift,shift);
2226 my $orderby = "sticky DESC, _date DESC";
2227 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2228 qsearch( 'cust_main_note',
2229 { 'custnum' => $self->custnum },
2231 "ORDER BY $orderby",
2237 Returns the agent (see L<FS::agent>) for this customer.
2241 Returns the agent name (see L<FS::agent>) for this customer.
2247 $self->agent->agent;
2252 Returns any tags associated with this customer, as FS::cust_tag objects,
2253 or an empty list if there are no tags.
2257 Returns any tags associated with this customer, as FS::part_tag objects,
2258 or an empty list if there are no tags.
2264 map $_->part_tag, $self->cust_tag;
2270 Returns the customer class, as an FS::cust_class object, or the empty string
2271 if there is no customer class.
2275 Returns the customer category name, or the empty string if there is no customer
2282 my $cust_class = $self->cust_class;
2284 ? $cust_class->categoryname
2290 Returns the customer class name, or the empty string if there is no customer
2297 my $cust_class = $self->cust_class;
2299 ? $cust_class->classname
2305 Returns the external tax status, as an FS::tax_status object, or the empty
2306 string if there is no tax status.
2312 if ( $self->taxstatusnum ) {
2313 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2321 Returns the tax status code if there is one.
2327 my $tax_status = $self->tax_status;
2329 ? $tax_status->taxstatus
2333 =item BILLING METHODS
2335 Documentation on billing methods has been moved to
2336 L<FS::cust_main::Billing>.
2338 =item REALTIME BILLING METHODS
2340 Documentation on realtime billing methods has been moved to
2341 L<FS::cust_main::Billing_Realtime>.
2345 Removes the I<paycvv> field from the database directly.
2347 If there is an error, returns the error, otherwise returns false.
2353 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2354 or return dbh->errstr;
2355 $sth->execute($self->custnum)
2356 or return $sth->errstr;
2363 Returns the total owed for this customer on all invoices
2364 (see L<FS::cust_bill/owed>).
2370 $self->total_owed_date(2145859200); #12/31/2037
2373 =item total_owed_date TIME
2375 Returns the total owed for this customer on all invoices with date earlier than
2376 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2377 see L<Time::Local> and L<Date::Parse> for conversion functions.
2381 sub total_owed_date {
2385 my $custnum = $self->custnum;
2387 my $owed_sql = FS::cust_bill->owed_sql;
2390 SELECT SUM($owed_sql) FROM cust_bill
2391 WHERE custnum = $custnum
2395 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2399 =item total_owed_pkgnum PKGNUM
2401 Returns the total owed on all invoices for this customer's specific package
2402 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2406 sub total_owed_pkgnum {
2407 my( $self, $pkgnum ) = @_;
2408 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2411 =item total_owed_date_pkgnum TIME PKGNUM
2413 Returns the total owed for this customer's specific package when using
2414 experimental package balances on all invoices with date earlier than
2415 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2416 see L<Time::Local> and L<Date::Parse> for conversion functions.
2420 sub total_owed_date_pkgnum {
2421 my( $self, $time, $pkgnum ) = @_;
2424 foreach my $cust_bill (
2425 grep { $_->_date <= $time }
2426 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2428 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2430 sprintf( "%.2f", $total_bill );
2436 Returns the total amount of all payments.
2443 $total += $_->paid foreach $self->cust_pay;
2444 sprintf( "%.2f", $total );
2447 =item total_unapplied_credits
2449 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2450 customer. See L<FS::cust_credit/credited>.
2452 =item total_credited
2454 Old name for total_unapplied_credits. Don't use.
2458 sub total_credited {
2459 #carp "total_credited deprecated, use total_unapplied_credits";
2460 shift->total_unapplied_credits(@_);
2463 sub total_unapplied_credits {
2466 my $custnum = $self->custnum;
2468 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2471 SELECT SUM($unapplied_sql) FROM cust_credit
2472 WHERE custnum = $custnum
2475 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2479 =item total_unapplied_credits_pkgnum PKGNUM
2481 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2482 customer. See L<FS::cust_credit/credited>.
2486 sub total_unapplied_credits_pkgnum {
2487 my( $self, $pkgnum ) = @_;
2488 my $total_credit = 0;
2489 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2490 sprintf( "%.2f", $total_credit );
2494 =item total_unapplied_payments
2496 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2497 See L<FS::cust_pay/unapplied>.
2501 sub total_unapplied_payments {
2504 my $custnum = $self->custnum;
2506 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2509 SELECT SUM($unapplied_sql) FROM cust_pay
2510 WHERE custnum = $custnum
2513 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2517 =item total_unapplied_payments_pkgnum PKGNUM
2519 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2520 specific package when using experimental package balances. See
2521 L<FS::cust_pay/unapplied>.
2525 sub total_unapplied_payments_pkgnum {
2526 my( $self, $pkgnum ) = @_;
2527 my $total_unapplied = 0;
2528 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2529 sprintf( "%.2f", $total_unapplied );
2533 =item total_unapplied_refunds
2535 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2536 customer. See L<FS::cust_refund/unapplied>.
2540 sub total_unapplied_refunds {
2542 my $custnum = $self->custnum;
2544 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2547 SELECT SUM($unapplied_sql) FROM cust_refund
2548 WHERE custnum = $custnum
2551 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2557 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2558 total_unapplied_credits minus total_unapplied_payments).
2564 $self->balance_date_range;
2567 =item balance_date TIME
2569 Returns the balance for this customer, only considering invoices with date
2570 earlier than TIME (total_owed_date minus total_credited minus
2571 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2572 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2579 $self->balance_date_range(shift);
2582 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2584 Returns the balance for this customer, optionally considering invoices with
2585 date earlier than START_TIME, and not later than END_TIME
2586 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2588 Times are specified as SQL fragments or numeric
2589 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2590 L<Date::Parse> for conversion functions. The empty string can be passed
2591 to disable that time constraint completely.
2593 Accepts the same options as L<balance_date_sql>:
2597 =item unapplied_date
2599 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)
2603 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2604 time will be ignored. Note that START_TIME and END_TIME only limit the date
2605 range for invoices and I<unapplied> payments, credits, and refunds.
2611 sub balance_date_range {
2613 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2614 ') FROM cust_main WHERE custnum='. $self->custnum;
2615 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2618 =item balance_pkgnum PKGNUM
2620 Returns the balance for this customer's specific package when using
2621 experimental package balances (total_owed plus total_unrefunded, minus
2622 total_unapplied_credits minus total_unapplied_payments)
2626 sub balance_pkgnum {
2627 my( $self, $pkgnum ) = @_;
2630 $self->total_owed_pkgnum($pkgnum)
2631 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2632 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2633 - $self->total_unapplied_credits_pkgnum($pkgnum)
2634 - $self->total_unapplied_payments_pkgnum($pkgnum)
2640 Returns a hash of useful information for making a payment.
2650 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2651 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2652 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2656 For credit card transactions:
2668 For electronic check transactions:
2683 $return{balance} = $self->balance;
2685 $return{payname} = $self->payname
2686 || ( $self->first. ' '. $self->get('last') );
2688 $return{$_} = $self->bill_location->$_
2689 for qw(address1 address2 city state zip);
2691 $return{payby} = $self->payby;
2692 $return{stateid_state} = $self->stateid_state;
2694 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2695 $return{card_type} = cardtype($self->payinfo);
2696 $return{payinfo} = $self->paymask;
2698 @return{'month', 'year'} = $self->paydate_monthyear;
2702 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2703 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2704 $return{payinfo1} = $payinfo1;
2705 $return{payinfo2} = $payinfo2;
2706 $return{paytype} = $self->paytype;
2707 $return{paystate} = $self->paystate;
2711 #doubleclick protection
2713 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2719 =item paydate_monthyear
2721 Returns a two-element list consisting of the month and year of this customer's
2722 paydate (credit card expiration date for CARD customers)
2726 sub paydate_monthyear {
2728 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2730 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2739 Returns the exact time in seconds corresponding to the payment method
2740 expiration date. For CARD/DCRD customers this is the end of the month;
2741 for others (COMP is the only other payby that uses paydate) it's the start.
2742 Returns 0 if the paydate is empty or set to the far future.
2748 my ($month, $year) = $self->paydate_monthyear;
2749 return 0 if !$year or $year >= 2037;
2750 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2752 if ( $month == 13 ) {
2756 return timelocal(0,0,0,1,$month-1,$year) - 1;
2759 return timelocal(0,0,0,1,$month-1,$year);
2763 =item paydate_epoch_sql
2765 Class method. Returns an SQL expression to obtain the payment expiration date
2766 as a number of seconds.
2770 # Special expiration date behavior for non-CARD/DCRD customers has been
2771 # carefully preserved. Do we really use that?
2772 sub paydate_epoch_sql {
2774 my $table = shift || 'cust_main';
2775 my ($case1, $case2);
2776 if ( driver_name eq 'Pg' ) {
2777 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2778 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2780 elsif ( lc(driver_name) eq 'mysql' ) {
2781 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2782 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2785 return "CASE WHEN $table.payby IN('CARD','DCRD')
2791 =item tax_exemption TAXNAME
2796 my( $self, $taxname ) = @_;
2798 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2799 'taxname' => $taxname,
2804 =item cust_main_exemption
2806 =item invoicing_list [ ARRAYREF ]
2808 If an arguement is given, sets these email addresses as invoice recipients
2809 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2810 (except as warnings), so use check_invoicing_list first.
2812 Returns a list of email addresses (with svcnum entries expanded).
2814 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2815 check it without disturbing anything by passing nothing.
2817 This interface may change in the future.
2821 sub invoicing_list {
2822 my( $self, $arrayref ) = @_;
2825 my @cust_main_invoice;
2826 if ( $self->custnum ) {
2827 @cust_main_invoice =
2828 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2830 @cust_main_invoice = ();
2832 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2833 #warn $cust_main_invoice->destnum;
2834 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2835 #warn $cust_main_invoice->destnum;
2836 my $error = $cust_main_invoice->delete;
2837 warn $error if $error;
2840 if ( $self->custnum ) {
2841 @cust_main_invoice =
2842 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2844 @cust_main_invoice = ();
2846 my %seen = map { $_->address => 1 } @cust_main_invoice;
2847 foreach my $address ( @{$arrayref} ) {
2848 next if exists $seen{$address} && $seen{$address};
2849 $seen{$address} = 1;
2850 my $cust_main_invoice = new FS::cust_main_invoice ( {
2851 'custnum' => $self->custnum,
2854 my $error = $cust_main_invoice->insert;
2855 warn $error if $error;
2859 if ( $self->custnum ) {
2861 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2868 =item check_invoicing_list ARRAYREF
2870 Checks these arguements as valid input for the invoicing_list method. If there
2871 is an error, returns the error, otherwise returns false.
2875 sub check_invoicing_list {
2876 my( $self, $arrayref ) = @_;
2878 foreach my $address ( @$arrayref ) {
2880 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2881 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2884 my $cust_main_invoice = new FS::cust_main_invoice ( {
2885 'custnum' => $self->custnum,
2888 my $error = $self->custnum
2889 ? $cust_main_invoice->check
2890 : $cust_main_invoice->checkdest
2892 return $error if $error;
2896 return "Email address required"
2897 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2898 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2903 =item set_default_invoicing_list
2905 Sets the invoicing list to all accounts associated with this customer,
2906 overwriting any previous invoicing list.
2910 sub set_default_invoicing_list {
2912 $self->invoicing_list($self->all_emails);
2917 Returns the email addresses of all accounts provisioned for this customer.
2924 foreach my $cust_pkg ( $self->all_pkgs ) {
2925 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2927 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2928 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2930 $list{$_}=1 foreach map { $_->email } @svc_acct;
2935 =item invoicing_list_addpost
2937 Adds postal invoicing to this customer. If this customer is already configured
2938 to receive postal invoices, does nothing.
2942 sub invoicing_list_addpost {
2944 return if grep { $_ eq 'POST' } $self->invoicing_list;
2945 my @invoicing_list = $self->invoicing_list;
2946 push @invoicing_list, 'POST';
2947 $self->invoicing_list(\@invoicing_list);
2950 =item invoicing_list_emailonly
2952 Returns the list of email invoice recipients (invoicing_list without non-email
2953 destinations such as POST and FAX).
2957 sub invoicing_list_emailonly {
2959 warn "$me invoicing_list_emailonly called"
2961 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
2964 =item invoicing_list_emailonly_scalar
2966 Returns the list of email invoice recipients (invoicing_list without non-email
2967 destinations such as POST and FAX) as a comma-separated scalar.
2971 sub invoicing_list_emailonly_scalar {
2973 warn "$me invoicing_list_emailonly_scalar called"
2975 join(', ', $self->invoicing_list_emailonly);
2978 =item referral_custnum_cust_main
2980 Returns the customer who referred this customer (or the empty string, if
2981 this customer was not referred).
2983 Note the difference with referral_cust_main method: This method,
2984 referral_custnum_cust_main returns the single customer (if any) who referred
2985 this customer, while referral_cust_main returns an array of customers referred
2990 sub referral_custnum_cust_main {
2992 return '' unless $self->referral_custnum;
2993 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2996 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
2998 Returns an array of customers referred by this customer (referral_custnum set
2999 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3000 customers referred by customers referred by this customer and so on, inclusive.
3001 The default behavior is DEPTH 1 (no recursion).
3003 Note the difference with referral_custnum_cust_main method: This method,
3004 referral_cust_main, returns an array of customers referred BY this customer,
3005 while referral_custnum_cust_main returns the single customer (if any) who
3006 referred this customer.
3010 sub referral_cust_main {
3012 my $depth = @_ ? shift : 1;
3013 my $exclude = @_ ? shift : {};
3016 map { $exclude->{$_->custnum}++; $_; }
3017 grep { ! $exclude->{ $_->custnum } }
3018 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3022 map { $_->referral_cust_main($depth-1, $exclude) }
3029 =item referral_cust_main_ncancelled
3031 Same as referral_cust_main, except only returns customers with uncancelled
3036 sub referral_cust_main_ncancelled {
3038 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3041 =item referral_cust_pkg [ DEPTH ]
3043 Like referral_cust_main, except returns a flat list of all unsuspended (and
3044 uncancelled) packages for each customer. The number of items in this list may
3045 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3049 sub referral_cust_pkg {
3051 my $depth = @_ ? shift : 1;
3053 map { $_->unsuspended_pkgs }
3054 grep { $_->unsuspended_pkgs }
3055 $self->referral_cust_main($depth);
3058 =item referring_cust_main
3060 Returns the single cust_main record for the customer who referred this customer
3061 (referral_custnum), or false.
3065 sub referring_cust_main {
3067 return '' unless $self->referral_custnum;
3068 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3071 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3073 Applies a credit to this customer. If there is an error, returns the error,
3074 otherwise returns false.
3076 REASON can be a text string, an FS::reason object, or a scalar reference to
3077 a reasonnum. If a text string, it will be automatically inserted as a new
3078 reason, and a 'reason_type' option must be passed to indicate the
3079 FS::reason_type for the new reason.
3081 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3082 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3083 I<commission_pkgnum>.
3085 Any other options are passed to FS::cust_credit::insert.
3090 my( $self, $amount, $reason, %options ) = @_;
3092 my $cust_credit = new FS::cust_credit {
3093 'custnum' => $self->custnum,
3094 'amount' => $amount,
3097 if ( ref($reason) ) {
3099 if ( ref($reason) eq 'SCALAR' ) {
3100 $cust_credit->reasonnum( $$reason );
3102 $cust_credit->reasonnum( $reason->reasonnum );
3106 $cust_credit->set('reason', $reason)
3109 $cust_credit->$_( delete $options{$_} )
3110 foreach grep exists($options{$_}),
3111 qw( addlinfo eventnum ),
3112 map "commission_$_", qw( agentnum salesnum pkgnum );
3114 $cust_credit->insert(%options);
3118 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3120 Creates a one-time charge for this customer. If there is an error, returns
3121 the error, otherwise returns false.
3123 New-style, with a hashref of options:
3125 my $error = $cust_main->charge(
3129 'start_date' => str2time('7/4/2009'),
3130 'pkg' => 'Description',
3131 'comment' => 'Comment',
3132 'additional' => [], #extra invoice detail
3133 'classnum' => 1, #pkg_class
3135 'setuptax' => '', # or 'Y' for tax exempt
3137 'locationnum'=> 1234, # optional
3140 'taxclass' => 'Tax class',
3143 'taxproduct' => 2, #part_pkg_taxproduct
3144 'override' => {}, #XXX describe
3146 #will be filled in with the new object
3147 'cust_pkg_ref' => \$cust_pkg,
3149 #generate an invoice immediately
3151 'invoice_terms' => '', #with these terms
3157 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3161 #super false laziness w/quotation::charge
3164 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3165 my ( $pkg, $comment, $additional );
3166 my ( $setuptax, $taxclass ); #internal taxes
3167 my ( $taxproduct, $override ); #vendor (CCH) taxes
3169 my $separate_bill = '';
3170 my $cust_pkg_ref = '';
3171 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3173 if ( ref( $_[0] ) ) {
3174 $amount = $_[0]->{amount};
3175 $setup_cost = $_[0]->{setup_cost};
3176 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3177 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3178 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3179 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3180 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3181 : '$'. sprintf("%.2f",$amount);
3182 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3183 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3184 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3185 $additional = $_[0]->{additional} || [];
3186 $taxproduct = $_[0]->{taxproductnum};
3187 $override = { '' => $_[0]->{tax_override} };
3188 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3189 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3190 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3191 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3192 $separate_bill = $_[0]->{separate_bill} || '';
3198 $pkg = @_ ? shift : 'One-time charge';
3199 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3201 $taxclass = @_ ? shift : '';
3205 local $SIG{HUP} = 'IGNORE';
3206 local $SIG{INT} = 'IGNORE';
3207 local $SIG{QUIT} = 'IGNORE';
3208 local $SIG{TERM} = 'IGNORE';
3209 local $SIG{TSTP} = 'IGNORE';
3210 local $SIG{PIPE} = 'IGNORE';
3212 my $oldAutoCommit = $FS::UID::AutoCommit;
3213 local $FS::UID::AutoCommit = 0;
3216 my $part_pkg = new FS::part_pkg ( {
3218 'comment' => $comment,
3222 'classnum' => ( $classnum ? $classnum : '' ),
3223 'setuptax' => $setuptax,
3224 'taxclass' => $taxclass,
3225 'taxproductnum' => $taxproduct,
3226 'setup_cost' => $setup_cost,
3229 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3230 ( 0 .. @$additional - 1 )
3232 'additional_count' => scalar(@$additional),
3233 'setup_fee' => $amount,
3236 my $error = $part_pkg->insert( options => \%options,
3237 tax_overrides => $override,
3240 $dbh->rollback if $oldAutoCommit;
3244 my $pkgpart = $part_pkg->pkgpart;
3245 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3246 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3247 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3248 $error = $type_pkgs->insert;
3250 $dbh->rollback if $oldAutoCommit;
3255 my $cust_pkg = new FS::cust_pkg ( {
3256 'custnum' => $self->custnum,
3257 'pkgpart' => $pkgpart,
3258 'quantity' => $quantity,
3259 'start_date' => $start_date,
3260 'no_auto' => $no_auto,
3261 'separate_bill' => $separate_bill,
3262 'locationnum'=> $locationnum,
3265 $error = $cust_pkg->insert;
3267 $dbh->rollback if $oldAutoCommit;
3269 } elsif ( $cust_pkg_ref ) {
3270 ${$cust_pkg_ref} = $cust_pkg;
3274 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3275 'pkg_list' => [ $cust_pkg ],
3278 $dbh->rollback if $oldAutoCommit;
3283 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3288 #=item charge_postal_fee
3290 #Applies a one time charge this customer. If there is an error,
3291 #returns the error, returns the cust_pkg charge object or false
3292 #if there was no charge.
3296 # This should be a customer event. For that to work requires that bill
3297 # also be a customer event.
3299 sub charge_postal_fee {
3302 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3303 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3305 my $cust_pkg = new FS::cust_pkg ( {
3306 'custnum' => $self->custnum,
3307 'pkgpart' => $pkgpart,
3311 my $error = $cust_pkg->insert;
3312 $error ? $error : $cust_pkg;
3315 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3317 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3319 Optionally, a list or hashref of additional arguments to the qsearch call can
3326 my $opt = ref($_[0]) ? shift : { @_ };
3328 #return $self->num_cust_bill unless wantarray || keys %$opt;
3330 $opt->{'table'} = 'cust_bill';
3331 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3332 $opt->{'hashref'}{'custnum'} = $self->custnum;
3333 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3335 map { $_ } #behavior of sort undefined in scalar context
3336 sort { $a->_date <=> $b->_date }
3340 =item open_cust_bill
3342 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3347 sub open_cust_bill {
3351 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3357 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3359 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3363 sub legacy_cust_bill {
3366 #return $self->num_legacy_cust_bill unless wantarray;
3368 map { $_ } #behavior of sort undefined in scalar context
3369 sort { $a->_date <=> $b->_date }
3370 qsearch({ 'table' => 'legacy_cust_bill',
3371 'hashref' => { 'custnum' => $self->custnum, },
3372 'order_by' => 'ORDER BY _date ASC',
3376 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3378 Returns all the statements (see L<FS::cust_statement>) for this customer.
3380 Optionally, a list or hashref of additional arguments to the qsearch call can
3385 =item cust_bill_void
3387 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3391 sub cust_bill_void {
3394 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3395 sort { $a->_date <=> $b->_date }
3396 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3399 sub cust_statement {
3401 my $opt = ref($_[0]) ? shift : { @_ };
3403 #return $self->num_cust_statement unless wantarray || keys %$opt;
3405 $opt->{'table'} = 'cust_statement';
3406 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3407 $opt->{'hashref'}{'custnum'} = $self->custnum;
3408 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3410 map { $_ } #behavior of sort undefined in scalar context
3411 sort { $a->_date <=> $b->_date }
3415 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3417 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3419 Optionally, a list or hashref of additional arguments to the qsearch call can
3420 be passed following the SVCDB.
3427 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3428 warn "$me svc_x requires a svcdb";
3431 my $opt = ref($_[0]) ? shift : { @_ };
3433 $opt->{'table'} = $svcdb;
3434 $opt->{'addl_from'} =
3435 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3436 ($opt->{'addl_from'} || '');
3438 my $custnum = $self->custnum;
3439 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3440 my $where = "cust_pkg.custnum = $custnum";
3442 my $extra_sql = $opt->{'extra_sql'} || '';
3443 if ( keys %{ $opt->{'hashref'} } ) {
3444 $extra_sql = " AND $where $extra_sql";
3447 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3448 $extra_sql = "WHERE $where AND $1";
3451 $extra_sql = "WHERE $where $extra_sql";
3454 $opt->{'extra_sql'} = $extra_sql;
3459 # required for use as an eventtable;
3462 $self->svc_x('svc_acct', @_);
3467 Returns all the credits (see L<FS::cust_credit>) for this customer.
3473 map { $_ } #return $self->num_cust_credit unless wantarray;
3474 sort { $a->_date <=> $b->_date }
3475 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3478 =item cust_credit_pkgnum
3480 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3481 package when using experimental package balances.
3485 sub cust_credit_pkgnum {
3486 my( $self, $pkgnum ) = @_;
3487 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3488 sort { $a->_date <=> $b->_date }
3489 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3490 'pkgnum' => $pkgnum,
3495 =item cust_credit_void
3497 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3501 sub cust_credit_void {
3504 sort { $a->_date <=> $b->_date }
3505 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3510 Returns all the payments (see L<FS::cust_pay>) for this customer.
3516 my $opt = ref($_[0]) ? shift : { @_ };
3518 return $self->num_cust_pay unless wantarray || keys %$opt;
3520 $opt->{'table'} = 'cust_pay';
3521 $opt->{'hashref'}{'custnum'} = $self->custnum;
3523 map { $_ } #behavior of sort undefined in scalar context
3524 sort { $a->_date <=> $b->_date }
3531 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3532 called automatically when the cust_pay method is used in a scalar context.
3538 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3539 my $sth = dbh->prepare($sql) or die dbh->errstr;
3540 $sth->execute($self->custnum) or die $sth->errstr;
3541 $sth->fetchrow_arrayref->[0];
3544 =item unapplied_cust_pay
3546 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3550 sub unapplied_cust_pay {
3554 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3560 =item cust_pay_pkgnum
3562 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3563 package when using experimental package balances.
3567 sub cust_pay_pkgnum {
3568 my( $self, $pkgnum ) = @_;
3569 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3570 sort { $a->_date <=> $b->_date }
3571 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3572 'pkgnum' => $pkgnum,
3579 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3585 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3586 sort { $a->_date <=> $b->_date }
3587 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3590 =item cust_pay_pending
3592 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3593 (without status "done").
3597 sub cust_pay_pending {
3599 return $self->num_cust_pay_pending unless wantarray;
3600 sort { $a->_date <=> $b->_date }
3601 qsearch( 'cust_pay_pending', {
3602 'custnum' => $self->custnum,
3603 'status' => { op=>'!=', value=>'done' },
3608 =item cust_pay_pending_attempt
3610 Returns all payment attempts / declined payments for this customer, as pending
3611 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3612 a corresponding payment (see L<FS::cust_pay>).
3616 sub cust_pay_pending_attempt {
3618 return $self->num_cust_pay_pending_attempt unless wantarray;
3619 sort { $a->_date <=> $b->_date }
3620 qsearch( 'cust_pay_pending', {
3621 'custnum' => $self->custnum,
3628 =item num_cust_pay_pending
3630 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3631 customer (without status "done"). Also called automatically when the
3632 cust_pay_pending method is used in a scalar context.
3636 sub num_cust_pay_pending {
3639 " SELECT COUNT(*) FROM cust_pay_pending ".
3640 " WHERE custnum = ? AND status != 'done' ",
3645 =item num_cust_pay_pending_attempt
3647 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3648 customer, with status "done" but without a corresp. Also called automatically when the
3649 cust_pay_pending method is used in a scalar context.
3653 sub num_cust_pay_pending_attempt {
3656 " SELECT COUNT(*) FROM cust_pay_pending ".
3657 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3664 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3670 map { $_ } #return $self->num_cust_refund unless wantarray;
3671 sort { $a->_date <=> $b->_date }
3672 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3675 =item display_custnum
3677 Returns the displayed customer number for this customer: agent_custid if
3678 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3682 sub display_custnum {
3685 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3686 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3687 if ( $special eq 'CoStAg' ) {
3688 $prefix = uc( join('',
3690 ($self->state =~ /^(..)/),
3691 $prefix || ($self->agent->agent =~ /^(..)/)
3694 elsif ( $special eq 'CoStCl' ) {
3695 $prefix = uc( join('',
3697 ($self->state =~ /^(..)/),
3698 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3701 # add any others here if needed
3704 my $length = $conf->config('cust_main-custnum-display_length');
3705 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3706 return $self->agent_custid;
3707 } elsif ( $prefix ) {
3708 $length = 8 if !defined($length);
3710 sprintf('%0'.$length.'d', $self->custnum)
3711 } elsif ( $length ) {
3712 return sprintf('%0'.$length.'d', $self->custnum);
3714 return $self->custnum;
3720 Returns a name string for this customer, either "Company (Last, First)" or
3727 my $name = $self->contact;
3728 $name = $self->company. " ($name)" if $self->company;
3732 =item service_contact
3734 Returns the L<FS::contact> object for this customer that has the 'Service'
3735 contact class, or undef if there is no such contact. Deprecated; don't use
3740 sub service_contact {
3742 if ( !exists($self->{service_contact}) ) {
3743 my $classnum = $self->scalar_sql(
3744 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3745 ) || 0; #if it's zero, qsearchs will return nothing
3746 my $cust_contact = qsearchs('cust_contact', {
3747 'classnum' => $classnum,
3748 'custnum' => $self->custnum,
3750 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3752 $self->{service_contact};
3757 Returns a name string for this (service/shipping) contact, either
3758 "Company (Last, First)" or "Last, First".
3765 my $name = $self->ship_contact;
3766 $name = $self->company. " ($name)" if $self->company;
3772 Returns a name string for this customer, either "Company" or "First Last".
3778 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3781 =item ship_name_short
3783 Returns a name string for this (service/shipping) contact, either "Company"
3788 sub ship_name_short {
3790 $self->service_contact
3791 ? $self->ship_contact_firstlast
3797 Returns this customer's full (billing) contact name only, "Last, First"
3803 $self->get('last'). ', '. $self->first;
3808 Returns this customer's full (shipping) contact name only, "Last, First"
3814 my $contact = $self->service_contact || $self;
3815 $contact->get('last') . ', ' . $contact->get('first');
3818 =item contact_firstlast
3820 Returns this customers full (billing) contact name only, "First Last".
3824 sub contact_firstlast {
3826 $self->first. ' '. $self->get('last');
3829 =item ship_contact_firstlast
3831 Returns this customer's full (shipping) contact name only, "First Last".
3835 sub ship_contact_firstlast {
3837 my $contact = $self->service_contact || $self;
3838 $contact->get('first') . ' '. $contact->get('last');
3841 #XXX this doesn't work in 3.x+
3844 #Returns this customer's full country name
3850 # code2country($self->country);
3853 sub bill_country_full {
3855 code2country($self->bill_location->country);
3858 sub ship_country_full {
3860 code2country($self->ship_location->country);
3863 =item county_state_county [ PREFIX ]
3865 Returns a string consisting of just the county, state and country.
3869 sub county_state_country {
3872 if ( @_ && $_[0] && $self->has_ship_address ) {
3873 $locationnum = $self->ship_locationnum;
3875 $locationnum = $self->bill_locationnum;
3877 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3878 $cust_location->county_state_country;
3881 =item geocode DATA_VENDOR
3883 Returns a value for the customer location as encoded by DATA_VENDOR.
3884 Currently this only makes sense for "CCH" as DATA_VENDOR.
3892 Returns a status string for this customer, currently:
3898 No packages have ever been ordered. Displayed as "No packages".
3902 Recurring packages all are new (not yet billed).
3906 One or more recurring packages is active.
3910 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3914 All non-cancelled recurring packages are suspended.
3918 All recurring packages are cancelled.
3922 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3923 cust_main-status_module configuration option.
3927 sub status { shift->cust_status(@_); }
3931 for my $status ( FS::cust_main->statuses() ) {
3932 my $method = $status.'_sql';
3933 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3934 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3935 $sth->execute( ($self->custnum) x $numnum )
3936 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3937 return $status if $sth->fetchrow_arrayref->[0];
3941 =item is_status_delay_cancel
3943 Returns true if customer status is 'suspended'
3944 and all suspended cust_pkg return true for
3945 cust_pkg->is_status_delay_cancel.
3947 This is not a real status, this only meant for hacking display
3948 values, because otherwise treating the customer as suspended is
3949 really the whole point of the delay_cancel option.
3953 sub is_status_delay_cancel {
3955 return 0 unless $self->status eq 'suspended';
3956 foreach my $cust_pkg ($self->ncancelled_pkgs) {
3957 return 0 unless $cust_pkg->is_status_delay_cancel;
3962 =item ucfirst_cust_status
3964 =item ucfirst_status
3966 Deprecated, use the cust_status_label method instead.
3968 Returns the status with the first character capitalized.
3972 sub ucfirst_status {
3973 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3974 local($ucfirst_nowarn) = 1;
3975 shift->ucfirst_cust_status(@_);
3978 sub ucfirst_cust_status {
3979 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3981 ucfirst($self->cust_status);
3984 =item cust_status_label
3988 Returns the display label for this status.
3992 sub status_label { shift->cust_status_label(@_); }
3994 sub cust_status_label {
3996 __PACKAGE__->statuslabels->{$self->cust_status};
4001 Returns a hex triplet color string for this customer's status.
4005 sub statuscolor { shift->cust_statuscolor(@_); }
4007 sub cust_statuscolor {
4009 __PACKAGE__->statuscolors->{$self->cust_status};
4012 =item tickets [ STATUS ]
4014 Returns an array of hashes representing the customer's RT tickets.
4016 An optional status (or arrayref or hashref of statuses) may be specified.
4022 my $status = ( @_ && $_[0] ) ? shift : '';
4024 my $num = $conf->config('cust_main-max_tickets') || 10;
4027 if ( $conf->config('ticket_system') ) {
4028 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4030 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4039 foreach my $priority (
4040 $conf->config('ticket_system-custom_priority_field-values'), ''
4042 last if scalar(@tickets) >= $num;
4044 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4045 $num - scalar(@tickets),
4056 # Return services representing svc_accts in customer support packages
4057 sub support_services {
4059 my %packages = map { $_ => 1 } $conf->config('support_packages');
4061 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4062 grep { $_->part_svc->svcdb eq 'svc_acct' }
4063 map { $_->cust_svc }
4064 grep { exists $packages{ $_->pkgpart } }
4065 $self->ncancelled_pkgs;
4069 # Return a list of latitude/longitude for one of the services (if any)
4070 sub service_coordinates {
4074 grep { $_->latitude && $_->longitude }
4076 map { $_->cust_svc }
4077 $self->ncancelled_pkgs;
4079 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4084 Returns a masked version of the named field
4089 my ($self,$field) = @_;
4093 'x'x(length($self->getfield($field))-4).
4094 substr($self->getfield($field), (length($self->getfield($field))-4));
4098 =item payment_history
4100 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4101 cust_credit and cust_refund objects. Each hashref has the following fields:
4103 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4105 I<date> - value of _date field, unix timestamp
4107 I<date_pretty> - user-friendly date
4109 I<description> - user-friendly description of item
4111 I<amount> - impact of item on user's balance
4112 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4113 Not to be confused with the native 'amount' field in cust_credit, see below.
4115 I<amount_pretty> - includes money char
4117 I<balance> - customer balance, chronologically as of this item
4119 I<balance_pretty> - includes money char
4121 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4123 I<paid> - amount paid for cust_pay records, undef for other types
4125 I<credit> - amount credited for cust_credit records, undef for other types.
4126 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4128 I<refund> - amount refunded for cust_refund records, undef for other types
4130 The four table-specific keys always have positive values, whether they reflect charges or payments.
4132 The following options may be passed to this method:
4134 I<line_items> - if true, returns charges ('Line item') rather than invoices
4136 I<start_date> - unix timestamp, only include records on or after.
4137 If specified, an item of type 'Previous' will also be included.
4138 It does not have table-specific fields.
4140 I<end_date> - unix timestamp, only include records before
4142 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4144 I<conf> - optional already-loaded FS::Conf object.
4148 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4149 # and also for sending customer statements, which should both be kept customer-friendly.
4150 # If you add anything that shouldn't be passed on through the API or exposed
4151 # to customers, add a new option to include it, don't include it by default
4152 sub payment_history {
4154 my $opt = ref($_[0]) ? $_[0] : { @_ };
4156 my $conf = $$opt{'conf'} || new FS::Conf;
4157 my $money_char = $conf->config("money_char") || '$',
4159 #first load entire history,
4160 #need previous to calculate previous balance
4161 #loading after end_date shouldn't hurt too much?
4163 if ( $$opt{'line_items'} ) {
4165 foreach my $cust_bill ( $self->cust_bill ) {
4168 'type' => 'Line item',
4169 'description' => $_->desc( $self->locale ).
4170 ( $_->sdate && $_->edate
4171 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4172 ' To '. time2str('%d-%b-%Y', $_->edate)
4175 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4176 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4177 'date' => $cust_bill->_date,
4178 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4180 foreach $cust_bill->cust_bill_pkg;
4187 'type' => 'Invoice',
4188 'description' => 'Invoice #'. $_->display_invnum,
4189 'amount' => sprintf('%.2f', $_->charged ),
4190 'charged' => sprintf('%.2f', $_->charged ),
4191 'date' => $_->_date,
4192 'date_pretty' => $self->time2str_local('short', $_->_date ),
4194 foreach $self->cust_bill;
4199 'type' => 'Payment',
4200 'description' => 'Payment', #XXX type
4201 'amount' => sprintf('%.2f', 0 - $_->paid ),
4202 'paid' => sprintf('%.2f', $_->paid ),
4203 'date' => $_->_date,
4204 'date_pretty' => $self->time2str_local('short', $_->_date ),
4206 foreach $self->cust_pay;
4210 'description' => 'Credit', #more info?
4211 'amount' => sprintf('%.2f', 0 -$_->amount ),
4212 'credit' => sprintf('%.2f', $_->amount ),
4213 'date' => $_->_date,
4214 'date_pretty' => $self->time2str_local('short', $_->_date ),
4216 foreach $self->cust_credit;
4220 'description' => 'Refund', #more info? type, like payment?
4221 'amount' => $_->refund,
4222 'refund' => $_->refund,
4223 'date' => $_->_date,
4224 'date_pretty' => $self->time2str_local('short', $_->_date ),
4226 foreach $self->cust_refund;
4228 #put it all in chronological order
4229 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4231 #calculate balance, filter items outside date range
4235 foreach my $item (@history) {
4236 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4237 $balance += $$item{'amount'};
4238 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4239 $previous += $$item{'amount'};
4242 $$item{'balance'} = sprintf("%.2f",$balance);
4243 foreach my $key ( qw(amount balance) ) {
4244 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4249 # start with previous balance, if there was one
4252 'type' => 'Previous',
4253 'description' => 'Previous balance',
4254 'amount' => sprintf("%.2f",$previous),
4255 'balance' => sprintf("%.2f",$previous),
4256 'date' => $$opt{'start_date'},
4257 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4259 #false laziness with above
4260 foreach my $key ( qw(amount balance) ) {
4261 $$item{$key.'_pretty'} = $$item{$key};
4262 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4264 unshift(@out,$item);
4267 @out = reverse @history if $$opt{'reverse_sort'};
4274 =head1 CLASS METHODS
4280 Class method that returns the list of possible status strings for customers
4281 (see L<the status method|/status>). For example:
4283 @statuses = FS::cust_main->statuses();
4289 keys %{ $self->statuscolors };
4292 =item cust_status_sql
4294 Returns an SQL fragment to determine the status of a cust_main record, as a
4299 sub cust_status_sql {
4301 for my $status ( FS::cust_main->statuses() ) {
4302 my $method = $status.'_sql';
4303 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4312 Returns an SQL expression identifying prospective cust_main records (customers
4313 with no packages ever ordered)
4317 use vars qw($select_count_pkgs);
4318 $select_count_pkgs =
4319 "SELECT COUNT(*) FROM cust_pkg
4320 WHERE cust_pkg.custnum = cust_main.custnum";
4322 sub select_count_pkgs_sql {
4327 " 0 = ( $select_count_pkgs ) ";
4332 Returns an SQL expression identifying ordered cust_main records (customers with
4333 no active packages, but recurring packages not yet setup or one time charges
4339 FS::cust_main->none_active_sql.
4340 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4345 Returns an SQL expression identifying active cust_main records (customers with
4346 active recurring packages).
4351 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4354 =item none_active_sql
4356 Returns an SQL expression identifying cust_main records with no active
4357 recurring packages. This includes customers of status prospect, ordered,
4358 inactive, and suspended.
4362 sub none_active_sql {
4363 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4368 Returns an SQL expression identifying inactive cust_main records (customers with
4369 no active recurring packages, but otherwise unsuspended/uncancelled).
4374 FS::cust_main->none_active_sql.
4375 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4381 Returns an SQL expression identifying suspended cust_main records.
4386 sub suspended_sql { susp_sql(@_); }
4388 FS::cust_main->none_active_sql.
4389 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4395 Returns an SQL expression identifying cancelled cust_main records.
4399 sub cancel_sql { shift->cancelled_sql(@_); }
4402 =item uncancelled_sql
4404 Returns an SQL expression identifying un-cancelled cust_main records.
4408 sub uncancelled_sql { uncancel_sql(@_); }
4409 sub uncancel_sql { "
4410 ( 0 < ( $select_count_pkgs
4411 AND ( cust_pkg.cancel IS NULL
4412 OR cust_pkg.cancel = 0
4415 OR 0 = ( $select_count_pkgs )
4421 Returns an SQL fragment to retreive the balance.
4426 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4427 WHERE cust_bill.custnum = cust_main.custnum )
4428 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4429 WHERE cust_pay.custnum = cust_main.custnum )
4430 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4431 WHERE cust_credit.custnum = cust_main.custnum )
4432 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4433 WHERE cust_refund.custnum = cust_main.custnum )
4436 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4438 Returns an SQL fragment to retreive the balance for this customer, optionally
4439 considering invoices with date earlier than START_TIME, and not
4440 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4441 total_unapplied_payments).
4443 Times are specified as SQL fragments or numeric
4444 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4445 L<Date::Parse> for conversion functions. The empty string can be passed
4446 to disable that time constraint completely.
4448 Available options are:
4452 =item unapplied_date
4454 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)
4459 set to true to remove all customer comparison clauses, for totals
4464 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4469 JOIN clause (typically used with the total option)
4473 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4474 time will be ignored. Note that START_TIME and END_TIME only limit the date
4475 range for invoices and I<unapplied> payments, credits, and refunds.
4481 sub balance_date_sql {
4482 my( $class, $start, $end, %opt ) = @_;
4484 my $cutoff = $opt{'cutoff'};
4486 my $owed = FS::cust_bill->owed_sql($cutoff);
4487 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4488 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4489 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4491 my $j = $opt{'join'} || '';
4493 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4494 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4495 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4496 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4498 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4499 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4500 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4501 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4506 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4508 Returns an SQL fragment to retreive the total unapplied payments for this
4509 customer, only considering payments with date earlier than START_TIME, and
4510 optionally not later than END_TIME.
4512 Times are specified as SQL fragments or numeric
4513 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4514 L<Date::Parse> for conversion functions. The empty string can be passed
4515 to disable that time constraint completely.
4517 Available options are:
4521 sub unapplied_payments_date_sql {
4522 my( $class, $start, $end, %opt ) = @_;
4524 my $cutoff = $opt{'cutoff'};
4526 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4528 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4529 'unapplied_date'=>1 );
4531 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4534 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4536 Helper method for balance_date_sql; name (and usage) subject to change
4537 (suggestions welcome).
4539 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4540 cust_refund, cust_credit or cust_pay).
4542 If TABLE is "cust_bill" or the unapplied_date option is true, only
4543 considers records with date earlier than START_TIME, and optionally not
4544 later than END_TIME .
4548 sub _money_table_where {
4549 my( $class, $table, $start, $end, %opt ) = @_;
4552 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4553 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4554 push @where, "$table._date <= $start" if defined($start) && length($start);
4555 push @where, "$table._date > $end" if defined($end) && length($end);
4557 push @where, @{$opt{'where'}} if $opt{'where'};
4558 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4564 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4565 use FS::cust_main::Search;
4568 FS::cust_main::Search->search(@_);
4577 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4579 Deprecated. Use event notification and message templates
4580 (L<FS::msg_template>) instead.
4582 Sends a templated email notification to the customer (see L<Text::Template>).
4584 OPTIONS is a hash and may include
4586 I<from> - the email sender (default is invoice_from)
4588 I<to> - comma-separated scalar or arrayref of recipients
4589 (default is invoicing_list)
4591 I<subject> - The subject line of the sent email notification
4592 (default is "Notice from company_name")
4594 I<extra_fields> - a hashref of name/value pairs which will be substituted
4597 The following variables are vavailable in the template.
4599 I<$first> - the customer first name
4600 I<$last> - the customer last name
4601 I<$company> - the customer company
4602 I<$payby> - a description of the method of payment for the customer
4603 # would be nice to use FS::payby::shortname
4604 I<$payinfo> - the account information used to collect for this customer
4605 I<$expdate> - the expiration of the customer payment in seconds from epoch
4610 my ($self, $template, %options) = @_;
4612 return unless $conf->exists($template);
4614 my $from = $conf->invoice_from_full($self->agentnum)
4615 if $conf->exists('invoice_from', $self->agentnum);
4616 $from = $options{from} if exists($options{from});
4618 my $to = join(',', $self->invoicing_list_emailonly);
4619 $to = $options{to} if exists($options{to});
4621 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4622 if $conf->exists('company_name', $self->agentnum);
4623 $subject = $options{subject} if exists($options{subject});
4625 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4626 SOURCE => [ map "$_\n",
4627 $conf->config($template)]
4629 or die "can't create new Text::Template object: Text::Template::ERROR";
4630 $notify_template->compile()
4631 or die "can't compile template: Text::Template::ERROR";
4633 $FS::notify_template::_template::company_name =
4634 $conf->config('company_name', $self->agentnum);
4635 $FS::notify_template::_template::company_address =
4636 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4638 my $paydate = $self->paydate || '2037-12-31';
4639 $FS::notify_template::_template::first = $self->first;
4640 $FS::notify_template::_template::last = $self->last;
4641 $FS::notify_template::_template::company = $self->company;
4642 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4643 my $payby = $self->payby;
4644 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4645 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4647 #credit cards expire at the end of the month/year of their exp date
4648 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4649 $FS::notify_template::_template::payby = 'credit card';
4650 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4651 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4653 }elsif ($payby eq 'COMP') {
4654 $FS::notify_template::_template::payby = 'complimentary account';
4656 $FS::notify_template::_template::payby = 'current method';
4658 $FS::notify_template::_template::expdate = $expire_time;
4660 for (keys %{$options{extra_fields}}){
4662 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4665 send_email(from => $from,
4667 subject => $subject,
4668 body => $notify_template->fill_in( PACKAGE =>
4669 'FS::notify_template::_template' ),
4674 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4676 Generates a templated notification to the customer (see L<Text::Template>).
4678 OPTIONS is a hash and may include
4680 I<extra_fields> - a hashref of name/value pairs which will be substituted
4681 into the template. These values may override values mentioned below
4682 and those from the customer record.
4684 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
4686 The following variables are available in the template instead of or in addition
4687 to the fields of the customer record.
4689 I<$payby> - a description of the method of payment for the customer
4690 # would be nice to use FS::payby::shortname
4691 I<$payinfo> - the masked account information used to collect for this customer
4692 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4693 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4697 # a lot like cust_bill::print_latex
4698 sub generate_letter {
4699 my ($self, $template, %options) = @_;
4701 warn "Template $template does not exist" && return
4702 unless $conf->exists($template) || $options{'template_text'};
4704 my $template_source = $options{'template_text'}
4705 ? [ $options{'template_text'} ]
4706 : [ map "$_\n", $conf->config($template) ];
4708 my $letter_template = new Text::Template
4710 SOURCE => $template_source,
4711 DELIMITERS => [ '[@--', '--@]' ],
4713 or die "can't create new Text::Template object: Text::Template::ERROR";
4715 $letter_template->compile()
4716 or die "can't compile template: Text::Template::ERROR";
4718 my %letter_data = map { $_ => $self->$_ } $self->fields;
4719 $letter_data{payinfo} = $self->mask_payinfo;
4721 #my $paydate = $self->paydate || '2037-12-31';
4722 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4724 my $payby = $self->payby;
4725 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4726 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4728 #credit cards expire at the end of the month/year of their exp date
4729 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4730 $letter_data{payby} = 'credit card';
4731 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4732 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4734 }elsif ($payby eq 'COMP') {
4735 $letter_data{payby} = 'complimentary account';
4737 $letter_data{payby} = 'current method';
4739 $letter_data{expdate} = $expire_time;
4741 for (keys %{$options{extra_fields}}){
4742 $letter_data{$_} = $options{extra_fields}->{$_};
4745 unless(exists($letter_data{returnaddress})){
4746 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4747 $self->agent_template)
4749 if ( length($retadd) ) {
4750 $letter_data{returnaddress} = $retadd;
4751 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4752 $letter_data{returnaddress} =
4753 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4757 ( $conf->config('company_name', $self->agentnum),
4758 $conf->config('company_address', $self->agentnum),
4762 $letter_data{returnaddress} = '~';
4766 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4768 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4770 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4772 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4776 ) or die "can't open temp file: $!\n";
4777 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4778 or die "can't write temp file: $!\n";
4780 $letter_data{'logo_file'} = $lh->filename;
4782 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4786 ) or die "can't open temp file: $!\n";
4788 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4790 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4791 return ($1, $letter_data{'logo_file'});
4795 =item print_ps TEMPLATE
4797 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4803 my($file, $lfile) = $self->generate_letter(@_);
4804 my $ps = FS::Misc::generate_ps($file);
4805 unlink($file.'.tex');
4811 =item print TEMPLATE
4813 Prints the filled in template.
4815 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4819 sub queueable_print {
4822 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4823 or die "invalid customer number: " . $opt{custnum};
4825 #do not backport this change to 3.x
4826 # my $error = $self->print( { 'template' => $opt{template} } );
4827 my $error = $self->print( $opt{'template'} );
4828 die $error if $error;
4832 my ($self, $template) = (shift, shift);
4834 [ $self->print_ps($template) ],
4835 'agentnum' => $self->agentnum,
4839 #these three subs should just go away once agent stuff is all config overrides
4841 sub agent_template {
4843 $self->_agent_plandata('agent_templatename');
4846 sub agent_invoice_from {
4848 $self->_agent_plandata('agent_invoice_from');
4851 sub _agent_plandata {
4852 my( $self, $option ) = @_;
4854 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4855 #agent-specific Conf
4857 use FS::part_event::Condition;
4859 my $agentnum = $self->agentnum;
4861 my $regexp = regexp_sql();
4863 my $part_event_option =
4865 'select' => 'part_event_option.*',
4866 'table' => 'part_event_option',
4868 LEFT JOIN part_event USING ( eventpart )
4869 LEFT JOIN part_event_option AS peo_agentnum
4870 ON ( part_event.eventpart = peo_agentnum.eventpart
4871 AND peo_agentnum.optionname = 'agentnum'
4872 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4874 LEFT JOIN part_event_condition
4875 ON ( part_event.eventpart = part_event_condition.eventpart
4876 AND part_event_condition.conditionname = 'cust_bill_age'
4878 LEFT JOIN part_event_condition_option
4879 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4880 AND part_event_condition_option.optionname = 'age'
4883 #'hashref' => { 'optionname' => $option },
4884 #'hashref' => { 'part_event_option.optionname' => $option },
4886 " WHERE part_event_option.optionname = ". dbh->quote($option).
4887 " AND action = 'cust_bill_send_agent' ".
4888 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4889 " AND peo_agentnum.optionname = 'agentnum' ".
4890 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4892 CASE WHEN part_event_condition_option.optionname IS NULL
4894 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4896 , part_event.weight".
4900 unless ( $part_event_option ) {
4901 return $self->agent->invoice_template || ''
4902 if $option eq 'agent_templatename';
4906 $part_event_option->optionvalue;
4910 sub process_o2m_qsearch {
4913 return qsearch($table, @_) unless $table eq 'contact';
4915 my $hashref = shift;
4916 my %hash = %$hashref;
4917 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4918 or die 'guru meditation #4343';
4920 qsearch({ 'table' => 'contact',
4921 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4922 'hashref' => \%hash,
4923 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4924 " cust_contact.custnum = $custnum "
4928 sub process_o2m_qsearchs {
4931 return qsearchs($table, @_) unless $table eq 'contact';
4933 my $hashref = shift;
4934 my %hash = %$hashref;
4935 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4936 or die 'guru meditation #2121';
4938 qsearchs({ 'table' => 'contact',
4939 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4940 'hashref' => \%hash,
4941 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4942 " cust_contact.custnum = $custnum "
4946 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4948 Subroutine (not a method), designed to be called from the queue.
4950 Takes a list of options and values.
4952 Pulls up the customer record via the custnum option and calls bill_and_collect.
4957 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4959 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4960 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4962 #without this errors don't get rolled back
4963 $args{'fatal'} = 1; # runs from job queue, will be caught
4965 $cust_main->bill_and_collect( %args );
4968 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4970 Like queued_bill, but instead of C<bill_and_collect>, just runs the
4971 C<collect> part. This is used in batch tax calculation, where invoice
4972 generation and collection events have to be completely separated.
4976 sub queued_collect {
4978 my $cust_main = FS::cust_main->by_key($args{'custnum'});
4980 $cust_main->collect(%args);
4983 sub process_bill_and_collect {
4986 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4987 or die "custnum '$param->{custnum}' not found!\n";
4988 $param->{'job'} = $job;
4989 $param->{'fatal'} = 1; # runs from job queue, will be caught
4990 $param->{'retry'} = 1;
4992 $cust_main->bill_and_collect( %$param );
4995 #starting to take quite a while for big dbs
4996 # (JRNL: journaled so it only happens once per database)
4997 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
4998 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
4999 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5000 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5001 # JRNL leading/trailing spaces in first, last, company
5002 # JRNL migrate to cust_payby
5003 # - otaker upgrade? journal and call it good? (double check to make sure
5004 # we're not still setting otaker here)
5006 #only going to get worse with new location stuff...
5008 sub _upgrade_data { #class method
5009 my ($class, %opts) = @_;
5012 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5015 #this seems to be the only expensive one.. why does it take so long?
5016 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5018 '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';
5019 FS::upgrade_journal->set_done('cust_main__signupdate');
5022 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5024 # fix yyyy-m-dd formatted paydates
5025 if ( driver_name =~ /^mysql/i ) {
5027 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5028 } else { # the SQL standard
5030 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5032 FS::upgrade_journal->set_done('cust_main__paydate');
5035 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5037 push @statements, #fix the weird BILL with a cc# in payinfo problem
5039 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5041 FS::upgrade_journal->set_done('cust_main__payinfo');
5046 foreach my $sql ( @statements ) {
5047 my $sth = dbh->prepare($sql) or die dbh->errstr;
5048 $sth->execute or die $sth->errstr;
5049 #warn ( (time - $t). " seconds\n" );
5053 local($ignore_expired_card) = 1;
5054 local($ignore_banned_card) = 1;
5055 local($skip_fuzzyfiles) = 1;
5056 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5058 FS::cust_main::Location->_upgrade_data(%opts);
5060 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5062 foreach my $cust_main ( qsearch({
5063 'table' => 'cust_main',
5065 'extra_sql' => 'WHERE '.
5067 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5068 qw( first last company )
5071 my $error = $cust_main->replace;
5072 die $error if $error;
5075 FS::upgrade_journal->set_done('cust_main__trimspaces');
5079 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5081 #we don't want to decrypt them, just stuff them as-is into cust_payby
5082 local(@encrypted_fields) = ();
5084 local($FS::cust_payby::ignore_expired_card) = 1;
5085 local($FS::cust_payby::ignore_banned_card) = 1;
5087 my @payfields = qw( payby payinfo paycvv paymask
5088 paydate paystart_month paystart_year payissue
5089 payname paystate paytype payip
5092 my $search = new FS::Cursor {
5093 'table' => 'cust_main',
5094 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5097 while (my $cust_main = $search->fetch) {
5099 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
5101 my $cust_payby = new FS::cust_payby {
5102 'custnum' => $cust_main->custnum,
5104 map { $_ => $cust_main->$_(); } @payfields
5107 my $error = $cust_payby->insert;
5108 die $error if $error;
5112 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
5114 $cust_main->invoice_attn( $cust_main->payname )
5115 if $cust_main->payby eq 'BILL' && $cust_main->payname;
5116 $cust_main->po_number( $cust_main->payinfo )
5117 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
5119 $cust_main->setfield($_, '') foreach @payfields;
5120 my $error = $cust_main->replace;
5121 die "Error upgradging payment information for custnum ".
5122 $cust_main->custnum. ": $error"
5127 FS::upgrade_journal->set_done('cust_main__cust_payby');
5130 $class->_upgrade_otaker(%opts);
5140 The delete method should possibly take an FS::cust_main object reference
5141 instead of a scalar customer number.
5143 Bill and collect options should probably be passed as references instead of a
5146 There should probably be a configuration file with a list of allowed credit
5149 No multiple currency support (probably a larger project than just this module).
5151 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5153 Birthdates rely on negative epoch values.
5155 The payby for card/check batches is broken. With mixed batching, bad
5158 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5162 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5163 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5164 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.