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 );
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",
2020 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2021 and L<FS::cust_pkg>) for this customer, except those on hold.
2023 Returns a list: an empty list on success or a list of errors.
2029 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2034 Unsuspends all suspended packages in the on-hold state (those without setup
2035 dates) for this customer.
2041 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2046 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2048 Returns a list: an empty list on success or a list of errors.
2054 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2057 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2059 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2060 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2061 of a list of pkgparts; the hashref has the following keys:
2065 =item pkgparts - listref of pkgparts
2067 =item (other options are passed to the suspend method)
2072 Returns a list: an empty list on success or a list of errors.
2076 sub suspend_if_pkgpart {
2078 my (@pkgparts, %opt);
2079 if (ref($_[0]) eq 'HASH'){
2080 @pkgparts = @{$_[0]{pkgparts}};
2085 grep { $_->suspend(%opt) }
2086 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2087 $self->unsuspended_pkgs;
2090 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2092 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2093 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2094 instead of a list of pkgparts; the hashref has the following keys:
2098 =item pkgparts - listref of pkgparts
2100 =item (other options are passed to the suspend method)
2104 Returns a list: an empty list on success or a list of errors.
2108 sub suspend_unless_pkgpart {
2110 my (@pkgparts, %opt);
2111 if (ref($_[0]) eq 'HASH'){
2112 @pkgparts = @{$_[0]{pkgparts}};
2117 grep { $_->suspend(%opt) }
2118 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2119 $self->unsuspended_pkgs;
2122 =item cancel [ OPTION => VALUE ... ]
2124 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2126 Available options are:
2130 =item quiet - can be set true to supress email cancellation notices.
2132 =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.
2134 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2136 =item nobill - can be set true to skip billing if it might otherwise be done.
2140 Always returns a list: an empty list on success or a list of errors.
2144 # nb that dates are not specified as valid options to this method
2147 my( $self, %opt ) = @_;
2149 warn "$me cancel called on customer ". $self->custnum. " with options ".
2150 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2153 return ( 'access denied' )
2154 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2156 if ( $opt{'ban'} ) {
2158 foreach my $cust_payby ( $self->cust_payby ) {
2160 #well, if they didn't get decrypted on search, then we don't have to
2161 # try again... queue a job for the server that does have decryption
2162 # capability if we're in a paranoid multi-server implementation?
2163 return ( "Can't (yet) ban encrypted credit cards" )
2164 if $cust_payby->is_encrypted($cust_payby->payinfo);
2166 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2167 my $error = $ban->insert;
2168 return ( $error ) if $error;
2174 my @pkgs = $self->ncancelled_pkgs;
2176 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2178 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2179 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2183 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2184 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2187 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2190 sub _banned_pay_hashref {
2201 'payby' => $payby2ban{$self->payby},
2202 'payinfo' => $self->payinfo,
2203 #don't ever *search* on reason! #'reason' =>
2209 Returns all notes (see L<FS::cust_main_note>) for this customer.
2214 my($self,$orderby_classnum) = (shift,shift);
2215 my $orderby = "sticky DESC, _date DESC";
2216 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2217 qsearch( 'cust_main_note',
2218 { 'custnum' => $self->custnum },
2220 "ORDER BY $orderby",
2226 Returns the agent (see L<FS::agent>) for this customer.
2230 Returns the agent name (see L<FS::agent>) for this customer.
2236 $self->agent->agent;
2241 Returns any tags associated with this customer, as FS::cust_tag objects,
2242 or an empty list if there are no tags.
2246 Returns any tags associated with this customer, as FS::part_tag objects,
2247 or an empty list if there are no tags.
2253 map $_->part_tag, $self->cust_tag;
2259 Returns the customer class, as an FS::cust_class object, or the empty string
2260 if there is no customer class.
2264 Returns the customer category name, or the empty string if there is no customer
2271 my $cust_class = $self->cust_class;
2273 ? $cust_class->categoryname
2279 Returns the customer class name, or the empty string if there is no customer
2286 my $cust_class = $self->cust_class;
2288 ? $cust_class->classname
2294 Returns the external tax status, as an FS::tax_status object, or the empty
2295 string if there is no tax status.
2301 if ( $self->taxstatusnum ) {
2302 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2310 Returns the tax status code if there is one.
2316 my $tax_status = $self->tax_status;
2318 ? $tax_status->taxstatus
2322 =item BILLING METHODS
2324 Documentation on billing methods has been moved to
2325 L<FS::cust_main::Billing>.
2327 =item REALTIME BILLING METHODS
2329 Documentation on realtime billing methods has been moved to
2330 L<FS::cust_main::Billing_Realtime>.
2334 Removes the I<paycvv> field from the database directly.
2336 If there is an error, returns the error, otherwise returns false.
2342 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2343 or return dbh->errstr;
2344 $sth->execute($self->custnum)
2345 or return $sth->errstr;
2352 Returns the total owed for this customer on all invoices
2353 (see L<FS::cust_bill/owed>).
2359 $self->total_owed_date(2145859200); #12/31/2037
2362 =item total_owed_date TIME
2364 Returns the total owed for this customer on all invoices with date earlier than
2365 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2366 see L<Time::Local> and L<Date::Parse> for conversion functions.
2370 sub total_owed_date {
2374 my $custnum = $self->custnum;
2376 my $owed_sql = FS::cust_bill->owed_sql;
2379 SELECT SUM($owed_sql) FROM cust_bill
2380 WHERE custnum = $custnum
2384 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2388 =item total_owed_pkgnum PKGNUM
2390 Returns the total owed on all invoices for this customer's specific package
2391 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2395 sub total_owed_pkgnum {
2396 my( $self, $pkgnum ) = @_;
2397 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2400 =item total_owed_date_pkgnum TIME PKGNUM
2402 Returns the total owed for this customer's specific package when using
2403 experimental package balances on all invoices with date earlier than
2404 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2405 see L<Time::Local> and L<Date::Parse> for conversion functions.
2409 sub total_owed_date_pkgnum {
2410 my( $self, $time, $pkgnum ) = @_;
2413 foreach my $cust_bill (
2414 grep { $_->_date <= $time }
2415 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2417 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2419 sprintf( "%.2f", $total_bill );
2425 Returns the total amount of all payments.
2432 $total += $_->paid foreach $self->cust_pay;
2433 sprintf( "%.2f", $total );
2436 =item total_unapplied_credits
2438 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2439 customer. See L<FS::cust_credit/credited>.
2441 =item total_credited
2443 Old name for total_unapplied_credits. Don't use.
2447 sub total_credited {
2448 #carp "total_credited deprecated, use total_unapplied_credits";
2449 shift->total_unapplied_credits(@_);
2452 sub total_unapplied_credits {
2455 my $custnum = $self->custnum;
2457 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2460 SELECT SUM($unapplied_sql) FROM cust_credit
2461 WHERE custnum = $custnum
2464 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2468 =item total_unapplied_credits_pkgnum PKGNUM
2470 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2471 customer. See L<FS::cust_credit/credited>.
2475 sub total_unapplied_credits_pkgnum {
2476 my( $self, $pkgnum ) = @_;
2477 my $total_credit = 0;
2478 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2479 sprintf( "%.2f", $total_credit );
2483 =item total_unapplied_payments
2485 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2486 See L<FS::cust_pay/unapplied>.
2490 sub total_unapplied_payments {
2493 my $custnum = $self->custnum;
2495 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2498 SELECT SUM($unapplied_sql) FROM cust_pay
2499 WHERE custnum = $custnum
2502 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2506 =item total_unapplied_payments_pkgnum PKGNUM
2508 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2509 specific package when using experimental package balances. See
2510 L<FS::cust_pay/unapplied>.
2514 sub total_unapplied_payments_pkgnum {
2515 my( $self, $pkgnum ) = @_;
2516 my $total_unapplied = 0;
2517 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2518 sprintf( "%.2f", $total_unapplied );
2522 =item total_unapplied_refunds
2524 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2525 customer. See L<FS::cust_refund/unapplied>.
2529 sub total_unapplied_refunds {
2531 my $custnum = $self->custnum;
2533 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2536 SELECT SUM($unapplied_sql) FROM cust_refund
2537 WHERE custnum = $custnum
2540 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2546 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2547 total_unapplied_credits minus total_unapplied_payments).
2553 $self->balance_date_range;
2556 =item balance_date TIME
2558 Returns the balance for this customer, only considering invoices with date
2559 earlier than TIME (total_owed_date minus total_credited minus
2560 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2561 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2568 $self->balance_date_range(shift);
2571 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2573 Returns the balance for this customer, optionally considering invoices with
2574 date earlier than START_TIME, and not later than END_TIME
2575 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2577 Times are specified as SQL fragments or numeric
2578 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2579 L<Date::Parse> for conversion functions. The empty string can be passed
2580 to disable that time constraint completely.
2582 Accepts the same options as L<balance_date_sql>:
2586 =item unapplied_date
2588 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)
2592 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2593 time will be ignored. Note that START_TIME and END_TIME only limit the date
2594 range for invoices and I<unapplied> payments, credits, and refunds.
2600 sub balance_date_range {
2602 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2603 ') FROM cust_main WHERE custnum='. $self->custnum;
2604 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2607 =item balance_pkgnum PKGNUM
2609 Returns the balance for this customer's specific package when using
2610 experimental package balances (total_owed plus total_unrefunded, minus
2611 total_unapplied_credits minus total_unapplied_payments)
2615 sub balance_pkgnum {
2616 my( $self, $pkgnum ) = @_;
2619 $self->total_owed_pkgnum($pkgnum)
2620 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2621 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2622 - $self->total_unapplied_credits_pkgnum($pkgnum)
2623 - $self->total_unapplied_payments_pkgnum($pkgnum)
2629 Returns a hash of useful information for making a payment.
2639 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2640 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2641 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2645 For credit card transactions:
2657 For electronic check transactions:
2672 $return{balance} = $self->balance;
2674 $return{payname} = $self->payname
2675 || ( $self->first. ' '. $self->get('last') );
2677 $return{$_} = $self->bill_location->$_
2678 for qw(address1 address2 city state zip);
2680 $return{payby} = $self->payby;
2681 $return{stateid_state} = $self->stateid_state;
2683 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2684 $return{card_type} = cardtype($self->payinfo);
2685 $return{payinfo} = $self->paymask;
2687 @return{'month', 'year'} = $self->paydate_monthyear;
2691 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2692 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2693 $return{payinfo1} = $payinfo1;
2694 $return{payinfo2} = $payinfo2;
2695 $return{paytype} = $self->paytype;
2696 $return{paystate} = $self->paystate;
2700 #doubleclick protection
2702 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2708 =item paydate_monthyear
2710 Returns a two-element list consisting of the month and year of this customer's
2711 paydate (credit card expiration date for CARD customers)
2715 sub paydate_monthyear {
2717 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2719 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2728 Returns the exact time in seconds corresponding to the payment method
2729 expiration date. For CARD/DCRD customers this is the end of the month;
2730 for others (COMP is the only other payby that uses paydate) it's the start.
2731 Returns 0 if the paydate is empty or set to the far future.
2737 my ($month, $year) = $self->paydate_monthyear;
2738 return 0 if !$year or $year >= 2037;
2739 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2741 if ( $month == 13 ) {
2745 return timelocal(0,0,0,1,$month-1,$year) - 1;
2748 return timelocal(0,0,0,1,$month-1,$year);
2752 =item paydate_epoch_sql
2754 Class method. Returns an SQL expression to obtain the payment expiration date
2755 as a number of seconds.
2759 # Special expiration date behavior for non-CARD/DCRD customers has been
2760 # carefully preserved. Do we really use that?
2761 sub paydate_epoch_sql {
2763 my $table = shift || 'cust_main';
2764 my ($case1, $case2);
2765 if ( driver_name eq 'Pg' ) {
2766 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2767 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2769 elsif ( lc(driver_name) eq 'mysql' ) {
2770 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2771 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2774 return "CASE WHEN $table.payby IN('CARD','DCRD')
2780 =item tax_exemption TAXNAME
2785 my( $self, $taxname ) = @_;
2787 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2788 'taxname' => $taxname,
2793 =item cust_main_exemption
2795 =item invoicing_list [ ARRAYREF ]
2797 If an arguement is given, sets these email addresses as invoice recipients
2798 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2799 (except as warnings), so use check_invoicing_list first.
2801 Returns a list of email addresses (with svcnum entries expanded).
2803 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2804 check it without disturbing anything by passing nothing.
2806 This interface may change in the future.
2810 sub invoicing_list {
2811 my( $self, $arrayref ) = @_;
2814 my @cust_main_invoice;
2815 if ( $self->custnum ) {
2816 @cust_main_invoice =
2817 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2819 @cust_main_invoice = ();
2821 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2822 #warn $cust_main_invoice->destnum;
2823 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2824 #warn $cust_main_invoice->destnum;
2825 my $error = $cust_main_invoice->delete;
2826 warn $error if $error;
2829 if ( $self->custnum ) {
2830 @cust_main_invoice =
2831 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2833 @cust_main_invoice = ();
2835 my %seen = map { $_->address => 1 } @cust_main_invoice;
2836 foreach my $address ( @{$arrayref} ) {
2837 next if exists $seen{$address} && $seen{$address};
2838 $seen{$address} = 1;
2839 my $cust_main_invoice = new FS::cust_main_invoice ( {
2840 'custnum' => $self->custnum,
2843 my $error = $cust_main_invoice->insert;
2844 warn $error if $error;
2848 if ( $self->custnum ) {
2850 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2857 =item check_invoicing_list ARRAYREF
2859 Checks these arguements as valid input for the invoicing_list method. If there
2860 is an error, returns the error, otherwise returns false.
2864 sub check_invoicing_list {
2865 my( $self, $arrayref ) = @_;
2867 foreach my $address ( @$arrayref ) {
2869 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2870 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2873 my $cust_main_invoice = new FS::cust_main_invoice ( {
2874 'custnum' => $self->custnum,
2877 my $error = $self->custnum
2878 ? $cust_main_invoice->check
2879 : $cust_main_invoice->checkdest
2881 return $error if $error;
2885 return "Email address required"
2886 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2887 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2892 =item set_default_invoicing_list
2894 Sets the invoicing list to all accounts associated with this customer,
2895 overwriting any previous invoicing list.
2899 sub set_default_invoicing_list {
2901 $self->invoicing_list($self->all_emails);
2906 Returns the email addresses of all accounts provisioned for this customer.
2913 foreach my $cust_pkg ( $self->all_pkgs ) {
2914 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2916 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2917 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2919 $list{$_}=1 foreach map { $_->email } @svc_acct;
2924 =item invoicing_list_addpost
2926 Adds postal invoicing to this customer. If this customer is already configured
2927 to receive postal invoices, does nothing.
2931 sub invoicing_list_addpost {
2933 return if grep { $_ eq 'POST' } $self->invoicing_list;
2934 my @invoicing_list = $self->invoicing_list;
2935 push @invoicing_list, 'POST';
2936 $self->invoicing_list(\@invoicing_list);
2939 =item invoicing_list_emailonly
2941 Returns the list of email invoice recipients (invoicing_list without non-email
2942 destinations such as POST and FAX).
2946 sub invoicing_list_emailonly {
2948 warn "$me invoicing_list_emailonly called"
2950 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
2953 =item invoicing_list_emailonly_scalar
2955 Returns the list of email invoice recipients (invoicing_list without non-email
2956 destinations such as POST and FAX) as a comma-separated scalar.
2960 sub invoicing_list_emailonly_scalar {
2962 warn "$me invoicing_list_emailonly_scalar called"
2964 join(', ', $self->invoicing_list_emailonly);
2967 =item referral_custnum_cust_main
2969 Returns the customer who referred this customer (or the empty string, if
2970 this customer was not referred).
2972 Note the difference with referral_cust_main method: This method,
2973 referral_custnum_cust_main returns the single customer (if any) who referred
2974 this customer, while referral_cust_main returns an array of customers referred
2979 sub referral_custnum_cust_main {
2981 return '' unless $self->referral_custnum;
2982 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2985 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
2987 Returns an array of customers referred by this customer (referral_custnum set
2988 to this custnum). If DEPTH is given, recurses up to the given depth, returning
2989 customers referred by customers referred by this customer and so on, inclusive.
2990 The default behavior is DEPTH 1 (no recursion).
2992 Note the difference with referral_custnum_cust_main method: This method,
2993 referral_cust_main, returns an array of customers referred BY this customer,
2994 while referral_custnum_cust_main returns the single customer (if any) who
2995 referred this customer.
2999 sub referral_cust_main {
3001 my $depth = @_ ? shift : 1;
3002 my $exclude = @_ ? shift : {};
3005 map { $exclude->{$_->custnum}++; $_; }
3006 grep { ! $exclude->{ $_->custnum } }
3007 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3011 map { $_->referral_cust_main($depth-1, $exclude) }
3018 =item referral_cust_main_ncancelled
3020 Same as referral_cust_main, except only returns customers with uncancelled
3025 sub referral_cust_main_ncancelled {
3027 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3030 =item referral_cust_pkg [ DEPTH ]
3032 Like referral_cust_main, except returns a flat list of all unsuspended (and
3033 uncancelled) packages for each customer. The number of items in this list may
3034 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3038 sub referral_cust_pkg {
3040 my $depth = @_ ? shift : 1;
3042 map { $_->unsuspended_pkgs }
3043 grep { $_->unsuspended_pkgs }
3044 $self->referral_cust_main($depth);
3047 =item referring_cust_main
3049 Returns the single cust_main record for the customer who referred this customer
3050 (referral_custnum), or false.
3054 sub referring_cust_main {
3056 return '' unless $self->referral_custnum;
3057 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3060 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3062 Applies a credit to this customer. If there is an error, returns the error,
3063 otherwise returns false.
3065 REASON can be a text string, an FS::reason object, or a scalar reference to
3066 a reasonnum. If a text string, it will be automatically inserted as a new
3067 reason, and a 'reason_type' option must be passed to indicate the
3068 FS::reason_type for the new reason.
3070 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3071 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3072 I<commission_pkgnum>.
3074 Any other options are passed to FS::cust_credit::insert.
3079 my( $self, $amount, $reason, %options ) = @_;
3081 my $cust_credit = new FS::cust_credit {
3082 'custnum' => $self->custnum,
3083 'amount' => $amount,
3086 if ( ref($reason) ) {
3088 if ( ref($reason) eq 'SCALAR' ) {
3089 $cust_credit->reasonnum( $$reason );
3091 $cust_credit->reasonnum( $reason->reasonnum );
3095 $cust_credit->set('reason', $reason)
3098 $cust_credit->$_( delete $options{$_} )
3099 foreach grep exists($options{$_}),
3100 qw( addlinfo eventnum ),
3101 map "commission_$_", qw( agentnum salesnum pkgnum );
3103 $cust_credit->insert(%options);
3107 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3109 Creates a one-time charge for this customer. If there is an error, returns
3110 the error, otherwise returns false.
3112 New-style, with a hashref of options:
3114 my $error = $cust_main->charge(
3118 'start_date' => str2time('7/4/2009'),
3119 'pkg' => 'Description',
3120 'comment' => 'Comment',
3121 'additional' => [], #extra invoice detail
3122 'classnum' => 1, #pkg_class
3124 'setuptax' => '', # or 'Y' for tax exempt
3126 'locationnum'=> 1234, # optional
3129 'taxclass' => 'Tax class',
3132 'taxproduct' => 2, #part_pkg_taxproduct
3133 'override' => {}, #XXX describe
3135 #will be filled in with the new object
3136 'cust_pkg_ref' => \$cust_pkg,
3138 #generate an invoice immediately
3140 'invoice_terms' => '', #with these terms
3146 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3150 #super false laziness w/quotation::charge
3153 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3154 my ( $pkg, $comment, $additional );
3155 my ( $setuptax, $taxclass ); #internal taxes
3156 my ( $taxproduct, $override ); #vendor (CCH) taxes
3158 my $separate_bill = '';
3159 my $cust_pkg_ref = '';
3160 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3162 if ( ref( $_[0] ) ) {
3163 $amount = $_[0]->{amount};
3164 $setup_cost = $_[0]->{setup_cost};
3165 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3166 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3167 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3168 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3169 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3170 : '$'. sprintf("%.2f",$amount);
3171 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3172 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3173 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3174 $additional = $_[0]->{additional} || [];
3175 $taxproduct = $_[0]->{taxproductnum};
3176 $override = { '' => $_[0]->{tax_override} };
3177 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3178 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3179 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3180 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3181 $separate_bill = $_[0]->{separate_bill} || '';
3187 $pkg = @_ ? shift : 'One-time charge';
3188 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3190 $taxclass = @_ ? shift : '';
3194 local $SIG{HUP} = 'IGNORE';
3195 local $SIG{INT} = 'IGNORE';
3196 local $SIG{QUIT} = 'IGNORE';
3197 local $SIG{TERM} = 'IGNORE';
3198 local $SIG{TSTP} = 'IGNORE';
3199 local $SIG{PIPE} = 'IGNORE';
3201 my $oldAutoCommit = $FS::UID::AutoCommit;
3202 local $FS::UID::AutoCommit = 0;
3205 my $part_pkg = new FS::part_pkg ( {
3207 'comment' => $comment,
3211 'classnum' => ( $classnum ? $classnum : '' ),
3212 'setuptax' => $setuptax,
3213 'taxclass' => $taxclass,
3214 'taxproductnum' => $taxproduct,
3215 'setup_cost' => $setup_cost,
3218 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3219 ( 0 .. @$additional - 1 )
3221 'additional_count' => scalar(@$additional),
3222 'setup_fee' => $amount,
3225 my $error = $part_pkg->insert( options => \%options,
3226 tax_overrides => $override,
3229 $dbh->rollback if $oldAutoCommit;
3233 my $pkgpart = $part_pkg->pkgpart;
3234 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3235 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3236 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3237 $error = $type_pkgs->insert;
3239 $dbh->rollback if $oldAutoCommit;
3244 my $cust_pkg = new FS::cust_pkg ( {
3245 'custnum' => $self->custnum,
3246 'pkgpart' => $pkgpart,
3247 'quantity' => $quantity,
3248 'start_date' => $start_date,
3249 'no_auto' => $no_auto,
3250 'separate_bill' => $separate_bill,
3251 'locationnum'=> $locationnum,
3254 $error = $cust_pkg->insert;
3256 $dbh->rollback if $oldAutoCommit;
3258 } elsif ( $cust_pkg_ref ) {
3259 ${$cust_pkg_ref} = $cust_pkg;
3263 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3264 'pkg_list' => [ $cust_pkg ],
3267 $dbh->rollback if $oldAutoCommit;
3272 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3277 #=item charge_postal_fee
3279 #Applies a one time charge this customer. If there is an error,
3280 #returns the error, returns the cust_pkg charge object or false
3281 #if there was no charge.
3285 # This should be a customer event. For that to work requires that bill
3286 # also be a customer event.
3288 sub charge_postal_fee {
3291 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3292 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3294 my $cust_pkg = new FS::cust_pkg ( {
3295 'custnum' => $self->custnum,
3296 'pkgpart' => $pkgpart,
3300 my $error = $cust_pkg->insert;
3301 $error ? $error : $cust_pkg;
3304 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3306 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3308 Optionally, a list or hashref of additional arguments to the qsearch call can
3315 my $opt = ref($_[0]) ? shift : { @_ };
3317 #return $self->num_cust_bill unless wantarray || keys %$opt;
3319 $opt->{'table'} = 'cust_bill';
3320 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3321 $opt->{'hashref'}{'custnum'} = $self->custnum;
3322 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3324 map { $_ } #behavior of sort undefined in scalar context
3325 sort { $a->_date <=> $b->_date }
3329 =item open_cust_bill
3331 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3336 sub open_cust_bill {
3340 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3346 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3348 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3352 sub legacy_cust_bill {
3355 #return $self->num_legacy_cust_bill unless wantarray;
3357 map { $_ } #behavior of sort undefined in scalar context
3358 sort { $a->_date <=> $b->_date }
3359 qsearch({ 'table' => 'legacy_cust_bill',
3360 'hashref' => { 'custnum' => $self->custnum, },
3361 'order_by' => 'ORDER BY _date ASC',
3365 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3367 Returns all the statements (see L<FS::cust_statement>) for this customer.
3369 Optionally, a list or hashref of additional arguments to the qsearch call can
3374 =item cust_bill_void
3376 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3380 sub cust_bill_void {
3383 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3384 sort { $a->_date <=> $b->_date }
3385 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3388 sub cust_statement {
3390 my $opt = ref($_[0]) ? shift : { @_ };
3392 #return $self->num_cust_statement unless wantarray || keys %$opt;
3394 $opt->{'table'} = 'cust_statement';
3395 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3396 $opt->{'hashref'}{'custnum'} = $self->custnum;
3397 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3399 map { $_ } #behavior of sort undefined in scalar context
3400 sort { $a->_date <=> $b->_date }
3404 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3406 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3408 Optionally, a list or hashref of additional arguments to the qsearch call can
3409 be passed following the SVCDB.
3416 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3417 warn "$me svc_x requires a svcdb";
3420 my $opt = ref($_[0]) ? shift : { @_ };
3422 $opt->{'table'} = $svcdb;
3423 $opt->{'addl_from'} =
3424 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3425 ($opt->{'addl_from'} || '');
3427 my $custnum = $self->custnum;
3428 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3429 my $where = "cust_pkg.custnum = $custnum";
3431 my $extra_sql = $opt->{'extra_sql'} || '';
3432 if ( keys %{ $opt->{'hashref'} } ) {
3433 $extra_sql = " AND $where $extra_sql";
3436 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3437 $extra_sql = "WHERE $where AND $1";
3440 $extra_sql = "WHERE $where $extra_sql";
3443 $opt->{'extra_sql'} = $extra_sql;
3448 # required for use as an eventtable;
3451 $self->svc_x('svc_acct', @_);
3456 Returns all the credits (see L<FS::cust_credit>) for this customer.
3462 map { $_ } #return $self->num_cust_credit unless wantarray;
3463 sort { $a->_date <=> $b->_date }
3464 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3467 =item cust_credit_pkgnum
3469 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3470 package when using experimental package balances.
3474 sub cust_credit_pkgnum {
3475 my( $self, $pkgnum ) = @_;
3476 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3477 sort { $a->_date <=> $b->_date }
3478 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3479 'pkgnum' => $pkgnum,
3484 =item cust_credit_void
3486 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3490 sub cust_credit_void {
3493 sort { $a->_date <=> $b->_date }
3494 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3499 Returns all the payments (see L<FS::cust_pay>) for this customer.
3505 my $opt = ref($_[0]) ? shift : { @_ };
3507 return $self->num_cust_pay unless wantarray || keys %$opt;
3509 $opt->{'table'} = 'cust_pay';
3510 $opt->{'hashref'}{'custnum'} = $self->custnum;
3512 map { $_ } #behavior of sort undefined in scalar context
3513 sort { $a->_date <=> $b->_date }
3520 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3521 called automatically when the cust_pay method is used in a scalar context.
3527 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3528 my $sth = dbh->prepare($sql) or die dbh->errstr;
3529 $sth->execute($self->custnum) or die $sth->errstr;
3530 $sth->fetchrow_arrayref->[0];
3533 =item unapplied_cust_pay
3535 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3539 sub unapplied_cust_pay {
3543 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3549 =item cust_pay_pkgnum
3551 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3552 package when using experimental package balances.
3556 sub cust_pay_pkgnum {
3557 my( $self, $pkgnum ) = @_;
3558 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3559 sort { $a->_date <=> $b->_date }
3560 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3561 'pkgnum' => $pkgnum,
3568 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3574 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3575 sort { $a->_date <=> $b->_date }
3576 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3579 =item cust_pay_pending
3581 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3582 (without status "done").
3586 sub cust_pay_pending {
3588 return $self->num_cust_pay_pending unless wantarray;
3589 sort { $a->_date <=> $b->_date }
3590 qsearch( 'cust_pay_pending', {
3591 'custnum' => $self->custnum,
3592 'status' => { op=>'!=', value=>'done' },
3597 =item cust_pay_pending_attempt
3599 Returns all payment attempts / declined payments for this customer, as pending
3600 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3601 a corresponding payment (see L<FS::cust_pay>).
3605 sub cust_pay_pending_attempt {
3607 return $self->num_cust_pay_pending_attempt unless wantarray;
3608 sort { $a->_date <=> $b->_date }
3609 qsearch( 'cust_pay_pending', {
3610 'custnum' => $self->custnum,
3617 =item num_cust_pay_pending
3619 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3620 customer (without status "done"). Also called automatically when the
3621 cust_pay_pending method is used in a scalar context.
3625 sub num_cust_pay_pending {
3628 " SELECT COUNT(*) FROM cust_pay_pending ".
3629 " WHERE custnum = ? AND status != 'done' ",
3634 =item num_cust_pay_pending_attempt
3636 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3637 customer, with status "done" but without a corresp. Also called automatically when the
3638 cust_pay_pending method is used in a scalar context.
3642 sub num_cust_pay_pending_attempt {
3645 " SELECT COUNT(*) FROM cust_pay_pending ".
3646 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3653 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3659 map { $_ } #return $self->num_cust_refund unless wantarray;
3660 sort { $a->_date <=> $b->_date }
3661 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3664 =item display_custnum
3666 Returns the displayed customer number for this customer: agent_custid if
3667 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3671 sub display_custnum {
3674 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3675 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3676 if ( $special eq 'CoStAg' ) {
3677 $prefix = uc( join('',
3679 ($self->state =~ /^(..)/),
3680 $prefix || ($self->agent->agent =~ /^(..)/)
3683 elsif ( $special eq 'CoStCl' ) {
3684 $prefix = uc( join('',
3686 ($self->state =~ /^(..)/),
3687 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3690 # add any others here if needed
3693 my $length = $conf->config('cust_main-custnum-display_length');
3694 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3695 return $self->agent_custid;
3696 } elsif ( $prefix ) {
3697 $length = 8 if !defined($length);
3699 sprintf('%0'.$length.'d', $self->custnum)
3700 } elsif ( $length ) {
3701 return sprintf('%0'.$length.'d', $self->custnum);
3703 return $self->custnum;
3709 Returns a name string for this customer, either "Company (Last, First)" or
3716 my $name = $self->contact;
3717 $name = $self->company. " ($name)" if $self->company;
3721 =item service_contact
3723 Returns the L<FS::contact> object for this customer that has the 'Service'
3724 contact class, or undef if there is no such contact. Deprecated; don't use
3729 sub service_contact {
3731 if ( !exists($self->{service_contact}) ) {
3732 my $classnum = $self->scalar_sql(
3733 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3734 ) || 0; #if it's zero, qsearchs will return nothing
3735 my $cust_contact = qsearchs('cust_contact', {
3736 'classnum' => $classnum,
3737 'custnum' => $self->custnum,
3739 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3741 $self->{service_contact};
3746 Returns a name string for this (service/shipping) contact, either
3747 "Company (Last, First)" or "Last, First".
3754 my $name = $self->ship_contact;
3755 $name = $self->company. " ($name)" if $self->company;
3761 Returns a name string for this customer, either "Company" or "First Last".
3767 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3770 =item ship_name_short
3772 Returns a name string for this (service/shipping) contact, either "Company"
3777 sub ship_name_short {
3779 $self->service_contact
3780 ? $self->ship_contact_firstlast
3786 Returns this customer's full (billing) contact name only, "Last, First"
3792 $self->get('last'). ', '. $self->first;
3797 Returns this customer's full (shipping) contact name only, "Last, First"
3803 my $contact = $self->service_contact || $self;
3804 $contact->get('last') . ', ' . $contact->get('first');
3807 =item contact_firstlast
3809 Returns this customers full (billing) contact name only, "First Last".
3813 sub contact_firstlast {
3815 $self->first. ' '. $self->get('last');
3818 =item ship_contact_firstlast
3820 Returns this customer's full (shipping) contact name only, "First Last".
3824 sub ship_contact_firstlast {
3826 my $contact = $self->service_contact || $self;
3827 $contact->get('first') . ' '. $contact->get('last');
3830 #XXX this doesn't work in 3.x+
3833 #Returns this customer's full country name
3839 # code2country($self->country);
3842 sub bill_country_full {
3844 code2country($self->bill_location->country);
3847 sub ship_country_full {
3849 code2country($self->ship_location->country);
3852 =item county_state_county [ PREFIX ]
3854 Returns a string consisting of just the county, state and country.
3858 sub county_state_country {
3861 if ( @_ && $_[0] && $self->has_ship_address ) {
3862 $locationnum = $self->ship_locationnum;
3864 $locationnum = $self->bill_locationnum;
3866 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3867 $cust_location->county_state_country;
3870 =item geocode DATA_VENDOR
3872 Returns a value for the customer location as encoded by DATA_VENDOR.
3873 Currently this only makes sense for "CCH" as DATA_VENDOR.
3881 Returns a status string for this customer, currently:
3887 No packages have ever been ordered. Displayed as "No packages".
3891 Recurring packages all are new (not yet billed).
3895 One or more recurring packages is active.
3899 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3903 All non-cancelled recurring packages are suspended.
3907 All recurring packages are cancelled.
3911 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3912 cust_main-status_module configuration option.
3916 sub status { shift->cust_status(@_); }
3920 for my $status ( FS::cust_main->statuses() ) {
3921 my $method = $status.'_sql';
3922 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3923 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3924 $sth->execute( ($self->custnum) x $numnum )
3925 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3926 return $status if $sth->fetchrow_arrayref->[0];
3930 =item is_status_delay_cancel
3932 Returns true if customer status is 'suspended'
3933 and all suspended cust_pkg return true for
3934 cust_pkg->is_status_delay_cancel.
3936 This is not a real status, this only meant for hacking display
3937 values, because otherwise treating the customer as suspended is
3938 really the whole point of the delay_cancel option.
3942 sub is_status_delay_cancel {
3944 return 0 unless $self->status eq 'suspended';
3945 foreach my $cust_pkg ($self->ncancelled_pkgs) {
3946 return 0 unless $cust_pkg->is_status_delay_cancel;
3951 =item ucfirst_cust_status
3953 =item ucfirst_status
3955 Deprecated, use the cust_status_label method instead.
3957 Returns the status with the first character capitalized.
3961 sub ucfirst_status {
3962 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3963 local($ucfirst_nowarn) = 1;
3964 shift->ucfirst_cust_status(@_);
3967 sub ucfirst_cust_status {
3968 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3970 ucfirst($self->cust_status);
3973 =item cust_status_label
3977 Returns the display label for this status.
3981 sub status_label { shift->cust_status_label(@_); }
3983 sub cust_status_label {
3985 __PACKAGE__->statuslabels->{$self->cust_status};
3990 Returns a hex triplet color string for this customer's status.
3994 sub statuscolor { shift->cust_statuscolor(@_); }
3996 sub cust_statuscolor {
3998 __PACKAGE__->statuscolors->{$self->cust_status};
4001 =item tickets [ STATUS ]
4003 Returns an array of hashes representing the customer's RT tickets.
4005 An optional status (or arrayref or hashref of statuses) may be specified.
4011 my $status = ( @_ && $_[0] ) ? shift : '';
4013 my $num = $conf->config('cust_main-max_tickets') || 10;
4016 if ( $conf->config('ticket_system') ) {
4017 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4019 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4028 foreach my $priority (
4029 $conf->config('ticket_system-custom_priority_field-values'), ''
4031 last if scalar(@tickets) >= $num;
4033 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4034 $num - scalar(@tickets),
4045 # Return services representing svc_accts in customer support packages
4046 sub support_services {
4048 my %packages = map { $_ => 1 } $conf->config('support_packages');
4050 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4051 grep { $_->part_svc->svcdb eq 'svc_acct' }
4052 map { $_->cust_svc }
4053 grep { exists $packages{ $_->pkgpart } }
4054 $self->ncancelled_pkgs;
4058 # Return a list of latitude/longitude for one of the services (if any)
4059 sub service_coordinates {
4063 grep { $_->latitude && $_->longitude }
4065 map { $_->cust_svc }
4066 $self->ncancelled_pkgs;
4068 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4073 Returns a masked version of the named field
4078 my ($self,$field) = @_;
4082 'x'x(length($self->getfield($field))-4).
4083 substr($self->getfield($field), (length($self->getfield($field))-4));
4089 =head1 CLASS METHODS
4095 Class method that returns the list of possible status strings for customers
4096 (see L<the status method|/status>). For example:
4098 @statuses = FS::cust_main->statuses();
4104 keys %{ $self->statuscolors };
4107 =item cust_status_sql
4109 Returns an SQL fragment to determine the status of a cust_main record, as a
4114 sub cust_status_sql {
4116 for my $status ( FS::cust_main->statuses() ) {
4117 my $method = $status.'_sql';
4118 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4127 Returns an SQL expression identifying prospective cust_main records (customers
4128 with no packages ever ordered)
4132 use vars qw($select_count_pkgs);
4133 $select_count_pkgs =
4134 "SELECT COUNT(*) FROM cust_pkg
4135 WHERE cust_pkg.custnum = cust_main.custnum";
4137 sub select_count_pkgs_sql {
4142 " 0 = ( $select_count_pkgs ) ";
4147 Returns an SQL expression identifying ordered cust_main records (customers with
4148 no active packages, but recurring packages not yet setup or one time charges
4154 FS::cust_main->none_active_sql.
4155 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4160 Returns an SQL expression identifying active cust_main records (customers with
4161 active recurring packages).
4166 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4169 =item none_active_sql
4171 Returns an SQL expression identifying cust_main records with no active
4172 recurring packages. This includes customers of status prospect, ordered,
4173 inactive, and suspended.
4177 sub none_active_sql {
4178 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4183 Returns an SQL expression identifying inactive cust_main records (customers with
4184 no active recurring packages, but otherwise unsuspended/uncancelled).
4189 FS::cust_main->none_active_sql.
4190 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4196 Returns an SQL expression identifying suspended cust_main records.
4201 sub suspended_sql { susp_sql(@_); }
4203 FS::cust_main->none_active_sql.
4204 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4210 Returns an SQL expression identifying cancelled cust_main records.
4214 sub cancel_sql { shift->cancelled_sql(@_); }
4217 =item uncancelled_sql
4219 Returns an SQL expression identifying un-cancelled cust_main records.
4223 sub uncancelled_sql { uncancel_sql(@_); }
4224 sub uncancel_sql { "
4225 ( 0 < ( $select_count_pkgs
4226 AND ( cust_pkg.cancel IS NULL
4227 OR cust_pkg.cancel = 0
4230 OR 0 = ( $select_count_pkgs )
4236 Returns an SQL fragment to retreive the balance.
4241 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4242 WHERE cust_bill.custnum = cust_main.custnum )
4243 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4244 WHERE cust_pay.custnum = cust_main.custnum )
4245 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4246 WHERE cust_credit.custnum = cust_main.custnum )
4247 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4248 WHERE cust_refund.custnum = cust_main.custnum )
4251 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4253 Returns an SQL fragment to retreive the balance for this customer, optionally
4254 considering invoices with date earlier than START_TIME, and not
4255 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4256 total_unapplied_payments).
4258 Times are specified as SQL fragments or numeric
4259 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4260 L<Date::Parse> for conversion functions. The empty string can be passed
4261 to disable that time constraint completely.
4263 Available options are:
4267 =item unapplied_date
4269 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)
4274 set to true to remove all customer comparison clauses, for totals
4279 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4284 JOIN clause (typically used with the total option)
4288 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4289 time will be ignored. Note that START_TIME and END_TIME only limit the date
4290 range for invoices and I<unapplied> payments, credits, and refunds.
4296 sub balance_date_sql {
4297 my( $class, $start, $end, %opt ) = @_;
4299 my $cutoff = $opt{'cutoff'};
4301 my $owed = FS::cust_bill->owed_sql($cutoff);
4302 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4303 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4304 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4306 my $j = $opt{'join'} || '';
4308 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4309 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4310 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4311 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4313 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4314 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4315 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4316 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4321 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4323 Returns an SQL fragment to retreive the total unapplied payments for this
4324 customer, only considering payments with date earlier than START_TIME, and
4325 optionally not later than END_TIME.
4327 Times are specified as SQL fragments or numeric
4328 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4329 L<Date::Parse> for conversion functions. The empty string can be passed
4330 to disable that time constraint completely.
4332 Available options are:
4336 sub unapplied_payments_date_sql {
4337 my( $class, $start, $end, %opt ) = @_;
4339 my $cutoff = $opt{'cutoff'};
4341 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4343 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4344 'unapplied_date'=>1 );
4346 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4349 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4351 Helper method for balance_date_sql; name (and usage) subject to change
4352 (suggestions welcome).
4354 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4355 cust_refund, cust_credit or cust_pay).
4357 If TABLE is "cust_bill" or the unapplied_date option is true, only
4358 considers records with date earlier than START_TIME, and optionally not
4359 later than END_TIME .
4363 sub _money_table_where {
4364 my( $class, $table, $start, $end, %opt ) = @_;
4367 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4368 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4369 push @where, "$table._date <= $start" if defined($start) && length($start);
4370 push @where, "$table._date > $end" if defined($end) && length($end);
4372 push @where, @{$opt{'where'}} if $opt{'where'};
4373 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4379 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4380 use FS::cust_main::Search;
4383 FS::cust_main::Search->search(@_);
4392 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4394 Deprecated. Use event notification and message templates
4395 (L<FS::msg_template>) instead.
4397 Sends a templated email notification to the customer (see L<Text::Template>).
4399 OPTIONS is a hash and may include
4401 I<from> - the email sender (default is invoice_from)
4403 I<to> - comma-separated scalar or arrayref of recipients
4404 (default is invoicing_list)
4406 I<subject> - The subject line of the sent email notification
4407 (default is "Notice from company_name")
4409 I<extra_fields> - a hashref of name/value pairs which will be substituted
4412 The following variables are vavailable in the template.
4414 I<$first> - the customer first name
4415 I<$last> - the customer last name
4416 I<$company> - the customer company
4417 I<$payby> - a description of the method of payment for the customer
4418 # would be nice to use FS::payby::shortname
4419 I<$payinfo> - the account information used to collect for this customer
4420 I<$expdate> - the expiration of the customer payment in seconds from epoch
4425 my ($self, $template, %options) = @_;
4427 return unless $conf->exists($template);
4429 my $from = $conf->invoice_from_full($self->agentnum)
4430 if $conf->exists('invoice_from', $self->agentnum);
4431 $from = $options{from} if exists($options{from});
4433 my $to = join(',', $self->invoicing_list_emailonly);
4434 $to = $options{to} if exists($options{to});
4436 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4437 if $conf->exists('company_name', $self->agentnum);
4438 $subject = $options{subject} if exists($options{subject});
4440 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4441 SOURCE => [ map "$_\n",
4442 $conf->config($template)]
4444 or die "can't create new Text::Template object: Text::Template::ERROR";
4445 $notify_template->compile()
4446 or die "can't compile template: Text::Template::ERROR";
4448 $FS::notify_template::_template::company_name =
4449 $conf->config('company_name', $self->agentnum);
4450 $FS::notify_template::_template::company_address =
4451 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4453 my $paydate = $self->paydate || '2037-12-31';
4454 $FS::notify_template::_template::first = $self->first;
4455 $FS::notify_template::_template::last = $self->last;
4456 $FS::notify_template::_template::company = $self->company;
4457 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4458 my $payby = $self->payby;
4459 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4460 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4462 #credit cards expire at the end of the month/year of their exp date
4463 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4464 $FS::notify_template::_template::payby = 'credit card';
4465 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4466 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4468 }elsif ($payby eq 'COMP') {
4469 $FS::notify_template::_template::payby = 'complimentary account';
4471 $FS::notify_template::_template::payby = 'current method';
4473 $FS::notify_template::_template::expdate = $expire_time;
4475 for (keys %{$options{extra_fields}}){
4477 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4480 send_email(from => $from,
4482 subject => $subject,
4483 body => $notify_template->fill_in( PACKAGE =>
4484 'FS::notify_template::_template' ),
4489 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4491 Generates a templated notification to the customer (see L<Text::Template>).
4493 OPTIONS is a hash and may include
4495 I<extra_fields> - a hashref of name/value pairs which will be substituted
4496 into the template. These values may override values mentioned below
4497 and those from the customer record.
4499 The following variables are available in the template instead of or in addition
4500 to the fields of the customer record.
4502 I<$payby> - a description of the method of payment for the customer
4503 # would be nice to use FS::payby::shortname
4504 I<$payinfo> - the masked account information used to collect for this customer
4505 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4506 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4510 # a lot like cust_bill::print_latex
4511 sub generate_letter {
4512 my ($self, $template, %options) = @_;
4514 return unless $conf->exists($template);
4516 my $letter_template = new Text::Template
4518 SOURCE => [ map "$_\n", $conf->config($template)],
4519 DELIMITERS => [ '[@--', '--@]' ],
4521 or die "can't create new Text::Template object: Text::Template::ERROR";
4523 $letter_template->compile()
4524 or die "can't compile template: Text::Template::ERROR";
4526 my %letter_data = map { $_ => $self->$_ } $self->fields;
4527 $letter_data{payinfo} = $self->mask_payinfo;
4529 #my $paydate = $self->paydate || '2037-12-31';
4530 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4532 my $payby = $self->payby;
4533 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4534 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4536 #credit cards expire at the end of the month/year of their exp date
4537 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4538 $letter_data{payby} = 'credit card';
4539 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4540 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4542 }elsif ($payby eq 'COMP') {
4543 $letter_data{payby} = 'complimentary account';
4545 $letter_data{payby} = 'current method';
4547 $letter_data{expdate} = $expire_time;
4549 for (keys %{$options{extra_fields}}){
4550 $letter_data{$_} = $options{extra_fields}->{$_};
4553 unless(exists($letter_data{returnaddress})){
4554 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4555 $self->agent_template)
4557 if ( length($retadd) ) {
4558 $letter_data{returnaddress} = $retadd;
4559 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4560 $letter_data{returnaddress} =
4561 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4565 ( $conf->config('company_name', $self->agentnum),
4566 $conf->config('company_address', $self->agentnum),
4570 $letter_data{returnaddress} = '~';
4574 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4576 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4578 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4580 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4584 ) or die "can't open temp file: $!\n";
4585 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4586 or die "can't write temp file: $!\n";
4588 $letter_data{'logo_file'} = $lh->filename;
4590 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4594 ) or die "can't open temp file: $!\n";
4596 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4598 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4599 return ($1, $letter_data{'logo_file'});
4603 =item print_ps TEMPLATE
4605 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4611 my($file, $lfile) = $self->generate_letter(@_);
4612 my $ps = FS::Misc::generate_ps($file);
4613 unlink($file.'.tex');
4619 =item print TEMPLATE
4621 Prints the filled in template.
4623 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4627 sub queueable_print {
4630 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4631 or die "invalid customer number: " . $opt{custnum};
4633 my $error = $self->print( { 'template' => $opt{template} } );
4634 die $error if $error;
4638 my ($self, $template) = (shift, shift);
4640 [ $self->print_ps($template) ],
4641 'agentnum' => $self->agentnum,
4645 #these three subs should just go away once agent stuff is all config overrides
4647 sub agent_template {
4649 $self->_agent_plandata('agent_templatename');
4652 sub agent_invoice_from {
4654 $self->_agent_plandata('agent_invoice_from');
4657 sub _agent_plandata {
4658 my( $self, $option ) = @_;
4660 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4661 #agent-specific Conf
4663 use FS::part_event::Condition;
4665 my $agentnum = $self->agentnum;
4667 my $regexp = regexp_sql();
4669 my $part_event_option =
4671 'select' => 'part_event_option.*',
4672 'table' => 'part_event_option',
4674 LEFT JOIN part_event USING ( eventpart )
4675 LEFT JOIN part_event_option AS peo_agentnum
4676 ON ( part_event.eventpart = peo_agentnum.eventpart
4677 AND peo_agentnum.optionname = 'agentnum'
4678 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4680 LEFT JOIN part_event_condition
4681 ON ( part_event.eventpart = part_event_condition.eventpart
4682 AND part_event_condition.conditionname = 'cust_bill_age'
4684 LEFT JOIN part_event_condition_option
4685 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4686 AND part_event_condition_option.optionname = 'age'
4689 #'hashref' => { 'optionname' => $option },
4690 #'hashref' => { 'part_event_option.optionname' => $option },
4692 " WHERE part_event_option.optionname = ". dbh->quote($option).
4693 " AND action = 'cust_bill_send_agent' ".
4694 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4695 " AND peo_agentnum.optionname = 'agentnum' ".
4696 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4698 CASE WHEN part_event_condition_option.optionname IS NULL
4700 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4702 , part_event.weight".
4706 unless ( $part_event_option ) {
4707 return $self->agent->invoice_template || ''
4708 if $option eq 'agent_templatename';
4712 $part_event_option->optionvalue;
4716 sub process_o2m_qsearch {
4719 return qsearch($table, @_) unless $table eq 'contact';
4721 my $hashref = shift;
4722 my %hash = %$hashref;
4723 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4724 or die 'guru meditation #4343';
4726 qsearch({ 'table' => 'contact',
4727 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4728 'hashref' => \%hash,
4729 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4730 " cust_contact.custnum = $custnum "
4734 sub process_o2m_qsearchs {
4737 return qsearchs($table, @_) unless $table eq 'contact';
4739 my $hashref = shift;
4740 my %hash = %$hashref;
4741 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4742 or die 'guru meditation #2121';
4744 qsearchs({ 'table' => 'contact',
4745 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4746 'hashref' => \%hash,
4747 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4748 " cust_contact.custnum = $custnum "
4752 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4754 Subroutine (not a method), designed to be called from the queue.
4756 Takes a list of options and values.
4758 Pulls up the customer record via the custnum option and calls bill_and_collect.
4763 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4765 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4766 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4768 #without this errors don't get rolled back
4769 $args{'fatal'} = 1; # runs from job queue, will be caught
4771 $cust_main->bill_and_collect( %args );
4774 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4776 Like queued_bill, but instead of C<bill_and_collect>, just runs the
4777 C<collect> part. This is used in batch tax calculation, where invoice
4778 generation and collection events have to be completely separated.
4782 sub queued_collect {
4784 my $cust_main = FS::cust_main->by_key($args{'custnum'});
4786 $cust_main->collect(%args);
4789 sub process_bill_and_collect {
4792 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4793 or die "custnum '$param->{custnum}' not found!\n";
4794 $param->{'job'} = $job;
4795 $param->{'fatal'} = 1; # runs from job queue, will be caught
4796 $param->{'retry'} = 1;
4798 $cust_main->bill_and_collect( %$param );
4801 #starting to take quite a while for big dbs
4802 # (JRNL: journaled so it only happens once per database)
4803 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
4804 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
4805 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
4806 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
4807 # JRNL leading/trailing spaces in first, last, company
4808 # JRNL migrate to cust_payby
4809 # - otaker upgrade? journal and call it good? (double check to make sure
4810 # we're not still setting otaker here)
4812 #only going to get worse with new location stuff...
4814 sub _upgrade_data { #class method
4815 my ($class, %opts) = @_;
4818 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4821 #this seems to be the only expensive one.. why does it take so long?
4822 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
4824 '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';
4825 FS::upgrade_journal->set_done('cust_main__signupdate');
4828 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
4830 # fix yyyy-m-dd formatted paydates
4831 if ( driver_name =~ /^mysql/i ) {
4833 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4834 } else { # the SQL standard
4836 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4838 FS::upgrade_journal->set_done('cust_main__paydate');
4841 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
4843 push @statements, #fix the weird BILL with a cc# in payinfo problem
4845 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
4847 FS::upgrade_journal->set_done('cust_main__payinfo');
4852 foreach my $sql ( @statements ) {
4853 my $sth = dbh->prepare($sql) or die dbh->errstr;
4854 $sth->execute or die $sth->errstr;
4855 #warn ( (time - $t). " seconds\n" );
4859 local($ignore_expired_card) = 1;
4860 local($ignore_banned_card) = 1;
4861 local($skip_fuzzyfiles) = 1;
4862 local($import) = 1; #prevent automatic geocoding (need its own variable?)
4864 FS::cust_main::Location->_upgrade_data(%opts);
4866 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
4868 foreach my $cust_main ( qsearch({
4869 'table' => 'cust_main',
4871 'extra_sql' => 'WHERE '.
4873 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
4874 qw( first last company )
4877 my $error = $cust_main->replace;
4878 die $error if $error;
4881 FS::upgrade_journal->set_done('cust_main__trimspaces');
4885 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
4887 #we don't want to decrypt them, just stuff them as-is into cust_payby
4888 local(@encrypted_fields) = ();
4890 local($FS::cust_payby::ignore_expired_card) = 1;
4891 local($FS::cust_payby::ignore_banned_card) = 1;
4893 my @payfields = qw( payby payinfo paycvv paymask
4894 paydate paystart_month paystart_year payissue
4895 payname paystate paytype payip
4898 my $search = new FS::Cursor {
4899 'table' => 'cust_main',
4900 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
4903 while (my $cust_main = $search->fetch) {
4905 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
4907 my $cust_payby = new FS::cust_payby {
4908 'custnum' => $cust_main->custnum,
4910 map { $_ => $cust_main->$_(); } @payfields
4913 my $error = $cust_payby->insert;
4914 die $error if $error;
4918 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
4920 $cust_main->invoice_attn( $cust_main->payname )
4921 if $cust_main->payby eq 'BILL' && $cust_main->payname;
4922 $cust_main->po_number( $cust_main->payinfo )
4923 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
4925 $cust_main->setfield($_, '') foreach @payfields;
4926 my $error = $cust_main->replace;
4927 die "Error upgradging payment information for custnum ".
4928 $cust_main->custnum. ": $error"
4933 FS::upgrade_journal->set_done('cust_main__cust_payby');
4936 $class->_upgrade_otaker(%opts);
4946 The delete method should possibly take an FS::cust_main object reference
4947 instead of a scalar customer number.
4949 Bill and collect options should probably be passed as references instead of a
4952 There should probably be a configuration file with a list of allowed credit
4955 No multiple currency support (probably a larger project than just this module).
4957 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4959 Birthdates rely on negative epoch values.
4961 The payby for card/check batches is broken. With mixed batching, bad
4964 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4968 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4969 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4970 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.