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);
27 use Digest::MD5 qw(md5_base64);
30 use File::Temp; #qw( tempfile );
31 use Business::CreditCard 0.28;
33 use FS::UID qw( dbh driver_name );
34 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
36 use FS::Misc qw( generate_email send_email generate_ps do_print );
37 use FS::Msgcat qw(gettext);
44 use FS::cust_bill_void;
45 use FS::legacy_cust_bill;
47 use FS::cust_pay_pending;
48 use FS::cust_pay_void;
49 use FS::cust_pay_batch;
52 use FS::part_referral;
53 use FS::cust_main_county;
54 use FS::cust_location;
57 use FS::cust_main_exemption;
58 use FS::cust_tax_adjustment;
59 use FS::cust_tax_location;
60 use FS::agent_currency;
61 use FS::cust_main_invoice;
63 use FS::prepay_credit;
69 use FS::payment_gateway;
70 use FS::agent_payment_gateway;
72 use FS::cust_main_note;
73 use FS::cust_attachment;
76 use FS::upgrade_journal;
81 # 1 is mostly method/subroutine entry and options
82 # 2 traces progress of some operations
83 # 3 is even more information including possibly sensitive data
85 our $me = '[FS::cust_main]';
88 our $ignore_expired_card = 0;
89 our $ignore_banned_card = 0;
90 our $ignore_invalid_card = 0;
92 our $skip_fuzzyfiles = 0;
94 our $ucfirst_nowarn = 0;
96 our @encrypted_fields = ('payinfo', 'paycvv');
97 sub nohistory_fields { ('payinfo', 'paycvv'); }
100 #ask FS::UID to run this stuff for us later
101 #$FS::UID::callback{'FS::cust_main'} = sub {
102 install_callback FS::UID sub {
103 $conf = new FS::Conf;
104 #yes, need it for stuff below (prolly should be cached)
105 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
110 my ( $hashref, $cache ) = @_;
111 if ( exists $hashref->{'pkgnum'} ) {
112 #@{ $self->{'_pkgnum'} } = ();
113 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
114 $self->{'_pkgnum'} = $subcache;
115 #push @{ $self->{'_pkgnum'} },
116 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
122 FS::cust_main - Object methods for cust_main records
128 $record = new FS::cust_main \%hash;
129 $record = new FS::cust_main { 'column' => 'value' };
131 $error = $record->insert;
133 $error = $new_record->replace($old_record);
135 $error = $record->delete;
137 $error = $record->check;
139 @cust_pkg = $record->all_pkgs;
141 @cust_pkg = $record->ncancelled_pkgs;
143 @cust_pkg = $record->suspended_pkgs;
145 $error = $record->bill;
146 $error = $record->bill %options;
147 $error = $record->bill 'time' => $time;
149 $error = $record->collect;
150 $error = $record->collect %options;
151 $error = $record->collect 'invoice_time' => $time,
156 An FS::cust_main object represents a customer. FS::cust_main inherits from
157 FS::Record. The following fields are currently supported:
163 Primary key (assigned automatically for new customers)
167 Agent (see L<FS::agent>)
171 Advertising source (see L<FS::part_referral>)
183 Cocial security number (optional)
207 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
211 Payment Information (See L<FS::payinfo_Mixin> for data format)
215 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
219 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
223 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
227 Start date month (maestro/solo cards only)
231 Start date year (maestro/solo cards only)
235 Issue number (maestro/solo cards only)
239 Name on card or billing name
243 IP address from which payment information was received
247 Tax exempt, empty or `Y'
251 Order taker (see L<FS::access_user>)
257 =item referral_custnum
259 Referring customer number
263 Enable individual CDR spooling, empty or `Y'
267 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
271 Discourage individual CDR printing, empty or `Y'
275 Allow self-service editing of ticket subjects, empty or 'Y'
277 =item calling_list_exempt
279 Do not call, empty or 'Y'
289 Creates a new customer. To add the customer to the database, see L<"insert">.
291 Note that this stores the hash reference, not a distinct copy of the hash it
292 points to. You can ask the object for a copy with the I<hash> method.
296 sub table { 'cust_main'; }
298 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
300 Adds this customer to the database. If there is an error, returns the error,
301 otherwise returns false.
303 Usually the customer's location will not yet exist in the database, and
304 the C<bill_location> and C<ship_location> pseudo-fields must be set to
305 uninserted L<FS::cust_location> objects. These will be inserted and linked
306 (in both directions) to the new customer record. If they're references
307 to the same object, they will become the same location.
309 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
310 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
311 are inserted atomicly, or the transaction is rolled back. Passing an empty
312 hash reference is equivalent to not supplying this parameter. There should be
313 a better explanation of this, but until then, here's an example:
316 tie %hash, 'Tie::RefHash'; #this part is important
318 $cust_pkg => [ $svc_acct ],
321 $cust_main->insert( \%hash );
323 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
324 be set as the invoicing list (see L<"invoicing_list">). Errors return as
325 expected and rollback the entire transaction; it is not necessary to call
326 check_invoicing_list first. The invoicing_list is set after the records in the
327 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
328 invoicing_list destination to the newly-created svc_acct. Here's an example:
330 $cust_main->insert( {}, [ $email, 'POST' ] );
332 Currently available options are: I<depend_jobnum>, I<noexport>,
333 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
335 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
336 on the supplied jobnum (they will not run until the specific job completes).
337 This can be used to defer provisioning until some action completes (such
338 as running the customer's credit card successfully).
340 The I<noexport> option is deprecated. If I<noexport> is set true, no
341 provisioning jobs (exports) are scheduled. (You can schedule them later with
342 the B<reexport> method.)
344 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
345 of tax names and exemption numbers. FS::cust_main_exemption records will be
346 created and inserted.
348 If I<prospectnum> is set, moves contacts and locations from that prospect.
350 If I<contact> is set to an arrayref of FS::contact objects, inserts those
351 new contacts with this new customer.
353 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
354 unset), inserts those new contacts with this new customer. Handles CGI
355 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
357 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
358 new stored payment records with this new customer. Handles CGI parameters
359 for an "m2" multiple entry field as passed by edit/cust_main.cgi
365 my $cust_pkgs = @_ ? shift : {};
366 my $invoicing_list = @_ ? shift : '';
368 warn "$me insert called with options ".
369 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
372 local $SIG{HUP} = 'IGNORE';
373 local $SIG{INT} = 'IGNORE';
374 local $SIG{QUIT} = 'IGNORE';
375 local $SIG{TERM} = 'IGNORE';
376 local $SIG{TSTP} = 'IGNORE';
377 local $SIG{PIPE} = 'IGNORE';
379 my $oldAutoCommit = $FS::UID::AutoCommit;
380 local $FS::UID::AutoCommit = 0;
383 my $prepay_identifier = '';
384 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
386 if ( $self->payby eq 'PREPAY' ) {
388 $self->payby(''); #'BILL');
389 $prepay_identifier = $self->payinfo;
392 warn " looking up prepaid card $prepay_identifier\n"
395 my $error = $self->get_prepay( $prepay_identifier,
396 'amount_ref' => \$amount,
397 'seconds_ref' => \$seconds,
398 'upbytes_ref' => \$upbytes,
399 'downbytes_ref' => \$downbytes,
400 'totalbytes_ref' => \$totalbytes,
403 $dbh->rollback if $oldAutoCommit;
404 #return "error applying prepaid card (transaction rolled back): $error";
408 $payby = 'PREP' if $amount;
410 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
413 $self->payby(''); #'BILL');
414 $amount = $self->paid;
419 foreach my $l (qw(bill_location ship_location)) {
421 my $loc = delete $self->hashref->{$l} or next;
423 if ( !$loc->locationnum ) {
424 # warn the location that we're going to insert it with no custnum
425 $loc->set(custnum_pending => 1);
426 warn " inserting $l\n"
428 my $error = $loc->insert;
430 $dbh->rollback if $oldAutoCommit;
431 my $label = $l eq 'ship_location' ? 'service' : 'billing';
432 return "$error (in $label location)";
435 } elsif ( $loc->prospectnum ) {
437 $loc->prospectnum('');
438 $loc->set(custnum_pending => 1);
439 my $error = $loc->replace;
441 $dbh->rollback if $oldAutoCommit;
442 my $label = $l eq 'ship_location' ? 'service' : 'billing';
443 return "$error (moving $label location)";
446 } elsif ( ($loc->custnum || 0) > 0 ) {
447 # then it somehow belongs to another customer--shouldn't happen
448 $dbh->rollback if $oldAutoCommit;
449 return "$l belongs to customer ".$loc->custnum;
451 # else it already belongs to this customer
452 # (happens when ship_location is identical to bill_location)
454 $self->set($l.'num', $loc->locationnum);
456 if ( $self->get($l.'num') eq '' ) {
457 $dbh->rollback if $oldAutoCommit;
462 warn " inserting $self\n"
465 $self->signupdate(time) unless $self->signupdate;
467 $self->auto_agent_custid()
468 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
470 my $error = $self->SUPER::insert;
472 $dbh->rollback if $oldAutoCommit;
473 #return "inserting cust_main record (transaction rolled back): $error";
477 # now set cust_location.custnum
478 foreach my $l (qw(bill_location ship_location)) {
479 warn " setting $l.custnum\n"
481 my $loc = $self->$l or next;
482 unless ( $loc->custnum ) {
483 $loc->set(custnum => $self->custnum);
484 $error ||= $loc->replace;
488 $dbh->rollback if $oldAutoCommit;
489 return "error setting $l custnum: $error";
493 warn " setting invoicing list\n"
496 if ( $invoicing_list ) {
497 $error = $self->check_invoicing_list( $invoicing_list );
499 $dbh->rollback if $oldAutoCommit;
500 #return "checking invoicing_list (transaction rolled back): $error";
503 $self->invoicing_list( $invoicing_list );
506 warn " setting customer tags\n"
509 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
510 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
511 'custnum' => $self->custnum };
512 my $error = $cust_tag->insert;
514 $dbh->rollback if $oldAutoCommit;
519 my $prospectnum = delete $options{'prospectnum'};
520 if ( $prospectnum ) {
522 warn " moving contacts and locations from prospect $prospectnum\n"
526 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
527 unless ( $prospect_main ) {
528 $dbh->rollback if $oldAutoCommit;
529 return "Unknown prospectnum $prospectnum";
531 $prospect_main->custnum($self->custnum);
532 $prospect_main->disabled('Y');
533 my $error = $prospect_main->replace;
535 $dbh->rollback if $oldAutoCommit;
539 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
540 my $cust_contact = new FS::cust_contact {
541 'custnum' => $self->custnum,
542 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
544 my $error = $cust_contact->insert
545 || $prospect_contact->delete;
547 $dbh->rollback if $oldAutoCommit;
552 my @cust_location = $prospect_main->cust_location;
553 my @qual = $prospect_main->qual;
555 foreach my $r ( @cust_location, @qual ) {
557 $r->custnum($self->custnum);
558 my $error = $r->replace;
560 $dbh->rollback if $oldAutoCommit;
567 warn " setting contacts\n"
570 if ( my $contact = delete $options{'contact'} ) {
572 foreach my $c ( @$contact ) {
573 $c->custnum($self->custnum);
574 my $error = $c->insert;
576 $dbh->rollback if $oldAutoCommit;
582 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
584 my $error = $self->process_o2m( 'table' => 'contact',
585 'fields' => FS::contact->cgi_contact_fields,
586 'params' => $contact_params,
589 $dbh->rollback if $oldAutoCommit;
594 warn " setting cust_payby\n"
597 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
599 my $error = $self->process_o2m(
600 'table' => 'cust_payby',
601 'fields' => FS::cust_payby->cgi_cust_payby_fields,
602 'params' => $cust_payby_params,
603 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
606 $dbh->rollback if $oldAutoCommit;
612 warn " setting cust_main_exemption\n"
615 my $tax_exemption = delete $options{'tax_exemption'};
616 if ( $tax_exemption ) {
618 $tax_exemption = { map { $_ => '' } @$tax_exemption }
619 if ref($tax_exemption) eq 'ARRAY';
621 foreach my $taxname ( keys %$tax_exemption ) {
622 my $cust_main_exemption = new FS::cust_main_exemption {
623 'custnum' => $self->custnum,
624 'taxname' => $taxname,
625 'exempt_number' => $tax_exemption->{$taxname},
627 my $error = $cust_main_exemption->insert;
629 $dbh->rollback if $oldAutoCommit;
630 return "inserting cust_main_exemption (transaction rolled back): $error";
635 warn " ordering packages\n"
638 $error = $self->order_pkgs( $cust_pkgs,
640 'seconds_ref' => \$seconds,
641 'upbytes_ref' => \$upbytes,
642 'downbytes_ref' => \$downbytes,
643 'totalbytes_ref' => \$totalbytes,
646 $dbh->rollback if $oldAutoCommit;
651 $dbh->rollback if $oldAutoCommit;
652 return "No svc_acct record to apply pre-paid time";
654 if ( $upbytes || $downbytes || $totalbytes ) {
655 $dbh->rollback if $oldAutoCommit;
656 return "No svc_acct record to apply pre-paid data";
660 warn " inserting initial $payby payment of $amount\n"
662 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
664 $dbh->rollback if $oldAutoCommit;
665 return "inserting payment (transaction rolled back): $error";
669 unless ( $import || $skip_fuzzyfiles ) {
670 warn " queueing fuzzyfiles update\n"
672 $error = $self->queue_fuzzyfiles_update;
674 $dbh->rollback if $oldAutoCommit;
675 return "updating fuzzy search cache: $error";
679 # FS::geocode_Mixin::after_insert or something?
680 if ( $conf->config('tax_district_method') and !$import ) {
681 # if anything non-empty, try to look it up
682 my $queue = new FS::queue {
683 'job' => 'FS::geocode_Mixin::process_district_update',
684 'custnum' => $self->custnum,
686 my $error = $queue->insert( ref($self), $self->custnum );
688 $dbh->rollback if $oldAutoCommit;
689 return "queueing tax district update: $error";
694 warn " exporting\n" if $DEBUG > 1;
696 my $export_args = $options{'export_args'} || [];
699 map qsearch( 'part_export', {exportnum=>$_} ),
700 $conf->config('cust_main-exports'); #, $agentnum
702 foreach my $part_export ( @part_export ) {
703 my $error = $part_export->export_insert($self, @$export_args);
705 $dbh->rollback if $oldAutoCommit;
706 return "exporting to ". $part_export->exporttype.
707 " (transaction rolled back): $error";
711 #foreach my $depend_jobnum ( @$depend_jobnums ) {
712 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
714 # foreach my $jobnum ( @jobnums ) {
715 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
716 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
718 # my $error = $queue->depend_insert($depend_jobnum);
720 # $dbh->rollback if $oldAutoCommit;
721 # return "error queuing job dependancy: $error";
728 #if ( exists $options{'jobnums'} ) {
729 # push @{ $options{'jobnums'} }, @jobnums;
732 warn " insert complete; committing transaction\n"
735 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
740 use File::CounterFile;
741 sub auto_agent_custid {
744 my $format = $conf->config('cust_main-auto_agent_custid');
746 if ( $format eq '1YMMXXXXXXXX' ) {
748 my $counter = new File::CounterFile 'cust_main.agent_custid';
751 my $ym = 100000000000 + time2str('%y%m00000000', time);
752 if ( $ym > $counter->value ) {
753 $counter->{'value'} = $agent_custid = $ym;
754 $counter->{'updated'} = 1;
756 $agent_custid = $counter->inc;
762 die "Unknown cust_main-auto_agent_custid format: $format";
765 $self->agent_custid($agent_custid);
769 =item PACKAGE METHODS
771 Documentation on customer package methods has been moved to
772 L<FS::cust_main::Packages>.
774 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
776 Recharges this (existing) customer with the specified prepaid card (see
777 L<FS::prepay_credit>), specified either by I<identifier> or as an
778 FS::prepay_credit object. If there is an error, returns the error, otherwise
781 Optionally, five scalar references can be passed as well. They will have their
782 values filled in with the amount, number of seconds, and number of upload,
783 download, and total bytes applied by this prepaid card.
787 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
788 #the only place that uses these args
789 sub recharge_prepay {
790 my( $self, $prepay_credit, $amountref, $secondsref,
791 $upbytesref, $downbytesref, $totalbytesref ) = @_;
793 local $SIG{HUP} = 'IGNORE';
794 local $SIG{INT} = 'IGNORE';
795 local $SIG{QUIT} = 'IGNORE';
796 local $SIG{TERM} = 'IGNORE';
797 local $SIG{TSTP} = 'IGNORE';
798 local $SIG{PIPE} = 'IGNORE';
800 my $oldAutoCommit = $FS::UID::AutoCommit;
801 local $FS::UID::AutoCommit = 0;
804 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
806 my $error = $self->get_prepay( $prepay_credit,
807 'amount_ref' => \$amount,
808 'seconds_ref' => \$seconds,
809 'upbytes_ref' => \$upbytes,
810 'downbytes_ref' => \$downbytes,
811 'totalbytes_ref' => \$totalbytes,
813 || $self->increment_seconds($seconds)
814 || $self->increment_upbytes($upbytes)
815 || $self->increment_downbytes($downbytes)
816 || $self->increment_totalbytes($totalbytes)
817 || $self->insert_cust_pay_prepay( $amount,
819 ? $prepay_credit->identifier
824 $dbh->rollback if $oldAutoCommit;
828 if ( defined($amountref) ) { $$amountref = $amount; }
829 if ( defined($secondsref) ) { $$secondsref = $seconds; }
830 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
831 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
832 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
834 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
839 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
841 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
842 specified either by I<identifier> or as an FS::prepay_credit object.
844 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
845 incremented by the values of the prepaid card.
847 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
848 check or set this customer's I<agentnum>.
850 If there is an error, returns the error, otherwise returns false.
856 my( $self, $prepay_credit, %opt ) = @_;
858 local $SIG{HUP} = 'IGNORE';
859 local $SIG{INT} = 'IGNORE';
860 local $SIG{QUIT} = 'IGNORE';
861 local $SIG{TERM} = 'IGNORE';
862 local $SIG{TSTP} = 'IGNORE';
863 local $SIG{PIPE} = 'IGNORE';
865 my $oldAutoCommit = $FS::UID::AutoCommit;
866 local $FS::UID::AutoCommit = 0;
869 unless ( ref($prepay_credit) ) {
871 my $identifier = $prepay_credit;
873 $prepay_credit = qsearchs(
875 { 'identifier' => $identifier },
880 unless ( $prepay_credit ) {
881 $dbh->rollback if $oldAutoCommit;
882 return "Invalid prepaid card: ". $identifier;
887 if ( $prepay_credit->agentnum ) {
888 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
889 $dbh->rollback if $oldAutoCommit;
890 return "prepaid card not valid for agent ". $self->agentnum;
892 $self->agentnum($prepay_credit->agentnum);
895 my $error = $prepay_credit->delete;
897 $dbh->rollback if $oldAutoCommit;
898 return "removing prepay_credit (transaction rolled back): $error";
901 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
902 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
904 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
909 =item increment_upbytes SECONDS
911 Updates this customer's single or primary account (see L<FS::svc_acct>) by
912 the specified number of upbytes. If there is an error, returns the error,
913 otherwise returns false.
917 sub increment_upbytes {
918 _increment_column( shift, 'upbytes', @_);
921 =item increment_downbytes SECONDS
923 Updates this customer's single or primary account (see L<FS::svc_acct>) by
924 the specified number of downbytes. If there is an error, returns the error,
925 otherwise returns false.
929 sub increment_downbytes {
930 _increment_column( shift, 'downbytes', @_);
933 =item increment_totalbytes SECONDS
935 Updates this customer's single or primary account (see L<FS::svc_acct>) by
936 the specified number of totalbytes. If there is an error, returns the error,
937 otherwise returns false.
941 sub increment_totalbytes {
942 _increment_column( shift, 'totalbytes', @_);
945 =item increment_seconds SECONDS
947 Updates this customer's single or primary account (see L<FS::svc_acct>) by
948 the specified number of seconds. If there is an error, returns the error,
949 otherwise returns false.
953 sub increment_seconds {
954 _increment_column( shift, 'seconds', @_);
957 =item _increment_column AMOUNT
959 Updates this customer's single or primary account (see L<FS::svc_acct>) by
960 the specified number of seconds or bytes. If there is an error, returns
961 the error, otherwise returns false.
965 sub _increment_column {
966 my( $self, $column, $amount ) = @_;
967 warn "$me increment_column called: $column, $amount\n"
970 return '' unless $amount;
972 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
973 $self->ncancelled_pkgs;
976 return 'No packages with primary or single services found'.
977 ' to apply pre-paid time';
978 } elsif ( scalar(@cust_pkg) > 1 ) {
979 #maybe have a way to specify the package/account?
980 return 'Multiple packages found to apply pre-paid time';
983 my $cust_pkg = $cust_pkg[0];
984 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
988 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
991 return 'No account found to apply pre-paid time';
992 } elsif ( scalar(@cust_svc) > 1 ) {
993 return 'Multiple accounts found to apply pre-paid time';
996 my $svc_acct = $cust_svc[0]->svc_x;
997 warn " found service svcnum ". $svc_acct->pkgnum.
998 ' ('. $svc_acct->email. ")\n"
1001 $column = "increment_$column";
1002 $svc_acct->$column($amount);
1006 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1008 Inserts a prepayment in the specified amount for this customer. An optional
1009 second argument can specify the prepayment identifier for tracking purposes.
1010 If there is an error, returns the error, otherwise returns false.
1014 sub insert_cust_pay_prepay {
1015 shift->insert_cust_pay('PREP', @_);
1018 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1020 Inserts a cash payment in the specified amount for this customer. An optional
1021 second argument can specify the payment identifier for tracking purposes.
1022 If there is an error, returns the error, otherwise returns false.
1026 sub insert_cust_pay_cash {
1027 shift->insert_cust_pay('CASH', @_);
1030 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1032 Inserts a Western Union payment in the specified amount for this customer. An
1033 optional second argument can specify the prepayment identifier for tracking
1034 purposes. If there is an error, returns the error, otherwise returns false.
1038 sub insert_cust_pay_west {
1039 shift->insert_cust_pay('WEST', @_);
1042 sub insert_cust_pay {
1043 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1044 my $payinfo = scalar(@_) ? shift : '';
1046 my $cust_pay = new FS::cust_pay {
1047 'custnum' => $self->custnum,
1048 'paid' => sprintf('%.2f', $amount),
1049 #'_date' => #date the prepaid card was purchased???
1051 'payinfo' => $payinfo,
1057 =item delete [ OPTION => VALUE ... ]
1059 This deletes the customer. If there is an error, returns the error, otherwise
1062 This will completely remove all traces of the customer record. This is not
1063 what you want when a customer cancels service; for that, cancel all of the
1064 customer's packages (see L</cancel>).
1066 If the customer has any uncancelled packages, you need to pass a new (valid)
1067 customer number for those packages to be transferred to, as the "new_customer"
1068 option. Cancelled packages will be deleted. Did I mention that this is NOT
1069 what you want when a customer cancels service and that you really should be
1070 looking at L<FS::cust_pkg/cancel>?
1072 You can't delete a customer with invoices (see L<FS::cust_bill>),
1073 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1074 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1075 set the "delete_financials" option to a true value.
1080 my( $self, %opt ) = @_;
1082 local $SIG{HUP} = 'IGNORE';
1083 local $SIG{INT} = 'IGNORE';
1084 local $SIG{QUIT} = 'IGNORE';
1085 local $SIG{TERM} = 'IGNORE';
1086 local $SIG{TSTP} = 'IGNORE';
1087 local $SIG{PIPE} = 'IGNORE';
1089 my $oldAutoCommit = $FS::UID::AutoCommit;
1090 local $FS::UID::AutoCommit = 0;
1093 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1094 $dbh->rollback if $oldAutoCommit;
1095 return "Can't delete a master agent customer";
1098 #use FS::access_user
1099 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1100 $dbh->rollback if $oldAutoCommit;
1101 return "Can't delete a master employee customer";
1104 tie my %financial_tables, 'Tie::IxHash',
1105 'cust_bill' => 'invoices',
1106 'cust_statement' => 'statements',
1107 'cust_credit' => 'credits',
1108 'cust_pay' => 'payments',
1109 'cust_refund' => 'refunds',
1112 foreach my $table ( keys %financial_tables ) {
1114 my @records = $self->$table();
1116 if ( @records && ! $opt{'delete_financials'} ) {
1117 $dbh->rollback if $oldAutoCommit;
1118 return "Can't delete a customer with ". $financial_tables{$table};
1121 foreach my $record ( @records ) {
1122 my $error = $record->delete;
1124 $dbh->rollback if $oldAutoCommit;
1125 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1131 my @cust_pkg = $self->ncancelled_pkgs;
1133 my $new_custnum = $opt{'new_custnum'};
1134 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1135 $dbh->rollback if $oldAutoCommit;
1136 return "Invalid new customer number: $new_custnum";
1138 foreach my $cust_pkg ( @cust_pkg ) {
1139 my %hash = $cust_pkg->hash;
1140 $hash{'custnum'} = $new_custnum;
1141 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1142 my $error = $new_cust_pkg->replace($cust_pkg,
1143 options => { $cust_pkg->options },
1146 $dbh->rollback if $oldAutoCommit;
1151 my @cancelled_cust_pkg = $self->all_pkgs;
1152 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1153 my $error = $cust_pkg->delete;
1155 $dbh->rollback if $oldAutoCommit;
1160 #cust_tax_adjustment in financials?
1161 #cust_pay_pending? ouch
1162 foreach my $table (qw(
1163 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1164 cust_payby cust_location cust_main_note cust_tax_adjustment
1165 cust_pay_void cust_pay_batch queue cust_tax_exempt
1167 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1168 my $error = $record->delete;
1170 $dbh->rollback if $oldAutoCommit;
1176 my $sth = $dbh->prepare(
1177 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1179 my $errstr = $dbh->errstr;
1180 $dbh->rollback if $oldAutoCommit;
1183 $sth->execute($self->custnum) or do {
1184 my $errstr = $sth->errstr;
1185 $dbh->rollback if $oldAutoCommit;
1191 my $ticket_dbh = '';
1192 if ($conf->config('ticket_system') eq 'RT_Internal') {
1194 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1195 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1196 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1197 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1200 if ( $ticket_dbh ) {
1202 my $ticket_sth = $ticket_dbh->prepare(
1203 'DELETE FROM Links WHERE Target = ?'
1205 my $errstr = $ticket_dbh->errstr;
1206 $dbh->rollback if $oldAutoCommit;
1209 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1211 my $errstr = $ticket_sth->errstr;
1212 $dbh->rollback if $oldAutoCommit;
1216 #check and see if the customer is the only link on the ticket, and
1217 #if so, set the ticket to deleted status in RT?
1218 #maybe someday, for now this will at least fix tickets not displaying
1222 #delete the customer record
1224 my $error = $self->SUPER::delete;
1226 $dbh->rollback if $oldAutoCommit;
1230 # cust_main exports!
1232 #my $export_args = $options{'export_args'} || [];
1235 map qsearch( 'part_export', {exportnum=>$_} ),
1236 $conf->config('cust_main-exports'); #, $agentnum
1238 foreach my $part_export ( @part_export ) {
1239 my $error = $part_export->export_delete( $self ); #, @$export_args);
1241 $dbh->rollback if $oldAutoCommit;
1242 return "exporting to ". $part_export->exporttype.
1243 " (transaction rolled back): $error";
1247 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1252 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1254 Replaces the OLD_RECORD with this one in the database. If there is an error,
1255 returns the error, otherwise returns false.
1257 To change the customer's address, set the pseudo-fields C<bill_location> and
1258 C<ship_location>. The address will still only change if at least one of the
1259 address fields differs from the existing values.
1261 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1262 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1263 expected and rollback the entire transaction; it is not necessary to call
1264 check_invoicing_list first. Here's an example:
1266 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1268 Currently available options are: I<tax_exemption>.
1270 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1271 of tax names and exemption numbers. FS::cust_main_exemption records will be
1272 deleted and inserted as appropriate.
1279 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1281 : $self->replace_old;
1285 warn "$me replace called\n"
1288 my $curuser = $FS::CurrentUser::CurrentUser;
1289 return "You are not permitted to create complimentary accounts."
1290 if $self->complimentary eq 'Y'
1291 && $self->complimentary ne $old->complimentary
1292 && ! $curuser->access_right('Complimentary customer');
1294 local($ignore_expired_card) = 1
1295 if $old->payby =~ /^(CARD|DCRD)$/
1296 && $self->payby =~ /^(CARD|DCRD)$/
1297 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1299 local($ignore_banned_card) = 1
1300 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1301 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1302 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1304 return "Invoicing locale is required"
1307 && $conf->exists('cust_main-require_locale');
1309 local $SIG{HUP} = 'IGNORE';
1310 local $SIG{INT} = 'IGNORE';
1311 local $SIG{QUIT} = 'IGNORE';
1312 local $SIG{TERM} = 'IGNORE';
1313 local $SIG{TSTP} = 'IGNORE';
1314 local $SIG{PIPE} = 'IGNORE';
1316 my $oldAutoCommit = $FS::UID::AutoCommit;
1317 local $FS::UID::AutoCommit = 0;
1320 for my $l (qw(bill_location ship_location)) {
1321 #my $old_loc = $old->$l;
1322 my $new_loc = $self->$l or next;
1324 # find the existing location if there is one
1325 $new_loc->set('custnum' => $self->custnum);
1326 my $error = $new_loc->find_or_insert;
1328 $dbh->rollback if $oldAutoCommit;
1331 $self->set($l.'num', $new_loc->locationnum);
1334 # replace the customer record
1335 my $error = $self->SUPER::replace($old);
1338 $dbh->rollback if $oldAutoCommit;
1342 # now move packages to the new service location
1343 $self->set('ship_location', ''); #flush cache
1344 if ( $old->ship_locationnum and # should only be null during upgrade...
1345 $old->ship_locationnum != $self->ship_locationnum ) {
1346 $error = $old->ship_location->move_to($self->ship_location);
1348 $dbh->rollback if $oldAutoCommit;
1352 # don't move packages based on the billing location, but
1353 # disable it if it's no longer in use
1354 if ( $old->bill_locationnum and
1355 $old->bill_locationnum != $self->bill_locationnum ) {
1356 $error = $old->bill_location->disable_if_unused;
1358 $dbh->rollback if $oldAutoCommit;
1363 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1364 my $invoicing_list = shift @param;
1365 $error = $self->check_invoicing_list( $invoicing_list );
1367 $dbh->rollback if $oldAutoCommit;
1370 $self->invoicing_list( $invoicing_list );
1373 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1375 #this could be more efficient than deleting and re-inserting, if it matters
1376 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1377 my $error = $cust_tag->delete;
1379 $dbh->rollback if $oldAutoCommit;
1383 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1384 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1385 'custnum' => $self->custnum };
1386 my $error = $cust_tag->insert;
1388 $dbh->rollback if $oldAutoCommit;
1395 my %options = @param;
1397 my $tax_exemption = delete $options{'tax_exemption'};
1398 if ( $tax_exemption ) {
1400 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1401 if ref($tax_exemption) eq 'ARRAY';
1403 my %cust_main_exemption =
1404 map { $_->taxname => $_ }
1405 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1407 foreach my $taxname ( keys %$tax_exemption ) {
1409 if ( $cust_main_exemption{$taxname} &&
1410 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1413 delete $cust_main_exemption{$taxname};
1417 my $cust_main_exemption = new FS::cust_main_exemption {
1418 'custnum' => $self->custnum,
1419 'taxname' => $taxname,
1420 'exempt_number' => $tax_exemption->{$taxname},
1422 my $error = $cust_main_exemption->insert;
1424 $dbh->rollback if $oldAutoCommit;
1425 return "inserting cust_main_exemption (transaction rolled back): $error";
1429 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1430 my $error = $cust_main_exemption->delete;
1432 $dbh->rollback if $oldAutoCommit;
1433 return "deleting cust_main_exemption (transaction rolled back): $error";
1439 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1441 my $error = $self->process_o2m(
1442 'table' => 'cust_payby',
1443 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1444 'params' => $cust_payby_params,
1445 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1448 $dbh->rollback if $oldAutoCommit;
1454 unless ( $import || $skip_fuzzyfiles ) {
1455 $error = $self->queue_fuzzyfiles_update;
1457 $dbh->rollback if $oldAutoCommit;
1458 return "updating fuzzy search cache: $error";
1462 # tax district update in cust_location
1464 # cust_main exports!
1466 my $export_args = $options{'export_args'} || [];
1469 map qsearch( 'part_export', {exportnum=>$_} ),
1470 $conf->config('cust_main-exports'); #, $agentnum
1472 foreach my $part_export ( @part_export ) {
1473 my $error = $part_export->export_replace( $self, $old, @$export_args);
1475 $dbh->rollback if $oldAutoCommit;
1476 return "exporting to ". $part_export->exporttype.
1477 " (transaction rolled back): $error";
1481 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1486 =item queue_fuzzyfiles_update
1488 Used by insert & replace to update the fuzzy search cache
1492 use FS::cust_main::Search;
1493 sub queue_fuzzyfiles_update {
1496 local $SIG{HUP} = 'IGNORE';
1497 local $SIG{INT} = 'IGNORE';
1498 local $SIG{QUIT} = 'IGNORE';
1499 local $SIG{TERM} = 'IGNORE';
1500 local $SIG{TSTP} = 'IGNORE';
1501 local $SIG{PIPE} = 'IGNORE';
1503 my $oldAutoCommit = $FS::UID::AutoCommit;
1504 local $FS::UID::AutoCommit = 0;
1507 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1508 my $queue = new FS::queue {
1509 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1511 my @args = "cust_main.$field", $self->get($field);
1512 my $error = $queue->insert( @args );
1514 $dbh->rollback if $oldAutoCommit;
1515 return "queueing job (transaction rolled back): $error";
1520 push @locations, $self->bill_location if $self->bill_locationnum;
1521 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1522 foreach my $location (@locations) {
1523 my $queue = new FS::queue {
1524 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1526 my @args = 'cust_location.address1', $location->address1;
1527 my $error = $queue->insert( @args );
1529 $dbh->rollback if $oldAutoCommit;
1530 return "queueing job (transaction rolled back): $error";
1534 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1541 Checks all fields to make sure this is a valid customer record. If there is
1542 an error, returns the error, otherwise returns false. Called by the insert
1543 and replace methods.
1550 warn "$me check BEFORE: \n". $self->_dump
1554 $self->ut_numbern('custnum')
1555 || $self->ut_number('agentnum')
1556 || $self->ut_textn('agent_custid')
1557 || $self->ut_number('refnum')
1558 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1559 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1560 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1561 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1562 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1563 || $self->ut_textn('custbatch')
1564 || $self->ut_name('last')
1565 || $self->ut_name('first')
1566 || $self->ut_snumbern('signupdate')
1567 || $self->ut_snumbern('birthdate')
1568 || $self->ut_namen('spouse_last')
1569 || $self->ut_namen('spouse_first')
1570 || $self->ut_snumbern('spouse_birthdate')
1571 || $self->ut_snumbern('anniversary_date')
1572 || $self->ut_textn('company')
1573 || $self->ut_textn('ship_company')
1574 || $self->ut_anything('comments')
1575 || $self->ut_numbern('referral_custnum')
1576 || $self->ut_textn('stateid')
1577 || $self->ut_textn('stateid_state')
1578 || $self->ut_textn('invoice_terms')
1579 || $self->ut_floatn('cdr_termination_percentage')
1580 || $self->ut_floatn('credit_limit')
1581 || $self->ut_numbern('billday')
1582 || $self->ut_numbern('prorate_day')
1583 || $self->ut_flag('edit_subject')
1584 || $self->ut_flag('calling_list_exempt')
1585 || $self->ut_flag('invoice_noemail')
1586 || $self->ut_flag('message_noemail')
1587 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1588 || $self->ut_currencyn('currency')
1589 || $self->ut_alphan('po_number')
1590 || $self->ut_enum('complimentary', [ '', 'Y' ])
1593 foreach (qw(company ship_company)) {
1594 my $company = $self->get($_);
1595 $company =~ s/^\s+//;
1596 $company =~ s/\s+$//;
1597 $company =~ s/\s+/ /g;
1598 $self->set($_, $company);
1601 #barf. need message catalogs. i18n. etc.
1602 $error .= "Please select an advertising source."
1603 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1604 return $error if $error;
1606 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1607 or return "Unknown agent";
1609 if ( $self->currency ) {
1610 my $agent_currency = qsearchs( 'agent_currency', {
1611 'agentnum' => $agent->agentnum,
1612 'currency' => $self->currency,
1614 or return "Agent ". $agent->agent.
1615 " not permitted to offer ". $self->currency. " invoicing";
1618 return "Unknown refnum"
1619 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1621 return "Unknown referring custnum: ". $self->referral_custnum
1622 unless ! $self->referral_custnum
1623 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1625 if ( $self->ss eq '' ) {
1630 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1631 or return "Illegal social security number: ". $self->ss;
1632 $self->ss("$1-$2-$3");
1635 # cust_main_county verification now handled by cust_location check
1638 $self->ut_phonen('daytime', $self->country)
1639 || $self->ut_phonen('night', $self->country)
1640 || $self->ut_phonen('fax', $self->country)
1641 || $self->ut_phonen('mobile', $self->country)
1643 return $error if $error;
1645 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1647 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1650 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1652 : FS::Msgcat::_gettext('daytime');
1653 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1655 : FS::Msgcat::_gettext('night');
1657 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1659 : FS::Msgcat::_gettext('mobile');
1661 return "$daytime_label, $night_label or $mobile_label is required"
1665 ### start of stuff moved to cust_payby
1666 # then mostly kept here to support upgrades (can remove in 5.x)
1667 # but modified to allow everything to be empty
1669 if ( $self->payby ) {
1670 FS::payby->can_payby($self->table, $self->payby)
1671 or return "Illegal payby: ". $self->payby;
1676 $error = $self->ut_numbern('paystart_month')
1677 || $self->ut_numbern('paystart_year')
1678 || $self->ut_numbern('payissue')
1679 || $self->ut_textn('paytype')
1681 return $error if $error;
1683 if ( $self->payip eq '' ) {
1686 $error = $self->ut_ip('payip');
1687 return $error if $error;
1690 # If it is encrypted and the private key is not availaible then we can't
1691 # check the credit card.
1692 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1694 # Need some kind of global flag to accept invalid cards, for testing
1696 if ( !$import && !$ignore_invalid_card && $check_payinfo &&
1697 $self->payby =~ /^(CARD|DCRD)$/ ) {
1699 my $payinfo = $self->payinfo;
1700 $payinfo =~ s/\D//g;
1701 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1702 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1704 $self->payinfo($payinfo);
1706 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1708 return gettext('unknown_card_type')
1709 if $self->payinfo !~ /^99\d{14}$/ #token
1710 && cardtype($self->payinfo) eq "Unknown";
1712 unless ( $ignore_banned_card ) {
1713 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1715 if ( $ban->bantype eq 'warn' ) {
1716 #or others depending on value of $ban->reason ?
1717 return '_duplicate_card'.
1718 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1719 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1720 ' (ban# '. $ban->bannum. ')'
1721 unless $self->override_ban_warn;
1723 return 'Banned credit card: banned on '.
1724 time2str('%a %h %o at %r', $ban->_date).
1725 ' by '. $ban->otaker.
1726 ' (ban# '. $ban->bannum. ')';
1731 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1732 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1733 $self->paycvv =~ /^(\d{4})$/
1734 or return "CVV2 (CID) for American Express cards is four digits.";
1737 $self->paycvv =~ /^(\d{3})$/
1738 or return "CVV2 (CVC2/CID) is three digits.";
1745 my $cardtype = cardtype($payinfo);
1746 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1748 return "Start date or issue number is required for $cardtype cards"
1749 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1751 return "Start month must be between 1 and 12"
1752 if $self->paystart_month
1753 and $self->paystart_month < 1 || $self->paystart_month > 12;
1755 return "Start year must be 1990 or later"
1756 if $self->paystart_year
1757 and $self->paystart_year < 1990;
1759 return "Issue number must be beween 1 and 99"
1761 and $self->payissue < 1 || $self->payissue > 99;
1764 $self->paystart_month('');
1765 $self->paystart_year('');
1766 $self->payissue('');
1769 } elsif ( !$ignore_invalid_card && $check_payinfo &&
1770 $self->payby =~ /^(CHEK|DCHK)$/ ) {
1772 my $payinfo = $self->payinfo;
1773 $payinfo =~ s/[^\d\@\.]//g;
1774 if ( $conf->config('echeck-country') eq 'CA' ) {
1775 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1776 or return 'invalid echeck account@branch.bank';
1777 $payinfo = "$1\@$2.$3";
1778 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1779 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1780 $payinfo = "$1\@$2";
1782 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1783 $payinfo = "$1\@$2";
1785 $self->payinfo($payinfo);
1788 unless ( $ignore_banned_card ) {
1789 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1791 if ( $ban->bantype eq 'warn' ) {
1792 #or others depending on value of $ban->reason ?
1793 return '_duplicate_ach' unless $self->override_ban_warn;
1795 return 'Banned ACH account: banned on '.
1796 time2str('%a %h %o at %r', $ban->_date).
1797 ' by '. $ban->otaker.
1798 ' (ban# '. $ban->bannum. ')';
1803 } elsif ( $self->payby eq 'LECB' ) {
1805 my $payinfo = $self->payinfo;
1806 $payinfo =~ s/\D//g;
1807 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1809 $self->payinfo($payinfo);
1812 } elsif ( $self->payby eq 'BILL' ) {
1814 $error = $self->ut_textn('payinfo');
1815 return "Illegal P.O. number: ". $self->payinfo if $error;
1818 } elsif ( $self->payby eq 'COMP' ) {
1820 my $curuser = $FS::CurrentUser::CurrentUser;
1821 if ( ! $self->custnum
1822 && ! $curuser->access_right('Complimentary customer')
1825 return "You are not permitted to create complimentary accounts."
1828 $error = $self->ut_textn('payinfo');
1829 return "Illegal comp account issuer: ". $self->payinfo if $error;
1832 } elsif ( $self->payby eq 'PREPAY' ) {
1834 my $payinfo = $self->payinfo;
1835 $payinfo =~ s/\W//g; #anything else would just confuse things
1836 $self->payinfo($payinfo);
1837 $error = $self->ut_alpha('payinfo');
1838 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1839 return "Unknown prepayment identifier"
1840 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1845 return "You are not permitted to create complimentary accounts."
1847 && $self->complimentary eq 'Y'
1848 && ! $FS::CurrentUser->CurrentUser->access_right('Complimentary customer');
1850 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1851 return "Expiration date required"
1852 # shouldn't payinfo_check do this?
1853 unless ! $self->payby
1854 || $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
1858 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1859 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1860 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1861 ( $m, $y ) = ( $2, "19$1" );
1862 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1863 ( $m, $y ) = ( $3, "20$2" );
1865 return "Illegal expiration date: ". $self->paydate;
1867 $m = sprintf('%02d',$m);
1868 $self->paydate("$y-$m-01");
1869 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1870 return gettext('expired_card')
1872 && !$ignore_expired_card
1873 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1876 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1877 ( ! $conf->exists('require_cardname')
1878 || $self->payby !~ /^(CARD|DCRD)$/ )
1880 $self->payname( $self->first. " ". $self->getfield('last') );
1883 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
1884 $self->payname =~ /^([\w \,\.\-\']*)$/
1885 or return gettext('illegal_name'). " payname: ". $self->payname;
1888 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
1889 or return gettext('illegal_name'). " payname: ". $self->payname;
1895 ### end of stuff moved to cust_payby
1897 return "Please select an invoicing locale"
1900 && $conf->exists('cust_main-require_locale');
1902 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1903 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1907 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1909 warn "$me check AFTER: \n". $self->_dump
1912 $self->SUPER::check;
1917 Returns a list of fields which have ship_ duplicates.
1922 qw( last first company
1924 address1 address2 city county state zip country
1926 daytime night fax mobile
1930 =item has_ship_address
1932 Returns true if this customer record has a separate shipping address.
1936 sub has_ship_address {
1938 $self->bill_locationnum != $self->ship_locationnum;
1943 Returns a list of key/value pairs, with the following keys: address1,
1944 adddress2, city, county, state, zip, country, district, and geocode. The
1945 shipping address is used if present.
1951 $self->ship_location->location_hash;
1956 Returns all locations (see L<FS::cust_location>) for this customer.
1962 qsearch('cust_location', { 'custnum' => $self->custnum,
1963 'prospectnum' => '' } );
1968 Returns all contact associations (see L<FS::cust_contact>) for this customer.
1974 qsearch('cust_contact', { 'custnum' => $self->custnum } );
1979 Returns all payment methods (see L<FS::cust_payby>) for this customer.
1986 'table' => 'cust_payby',
1987 'hashref' => { 'custnum' => $self->custnum },
1988 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
1994 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1995 and L<FS::cust_pkg>) for this customer, except those on hold.
1997 Returns a list: an empty list on success or a list of errors.
2003 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2008 Unsuspends all suspended packages in the on-hold state (those without setup
2009 dates) for this customer.
2015 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2020 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2022 Returns a list: an empty list on success or a list of errors.
2028 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2031 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2033 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2034 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2035 of a list of pkgparts; the hashref has the following keys:
2039 =item pkgparts - listref of pkgparts
2041 =item (other options are passed to the suspend method)
2046 Returns a list: an empty list on success or a list of errors.
2050 sub suspend_if_pkgpart {
2052 my (@pkgparts, %opt);
2053 if (ref($_[0]) eq 'HASH'){
2054 @pkgparts = @{$_[0]{pkgparts}};
2059 grep { $_->suspend(%opt) }
2060 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2061 $self->unsuspended_pkgs;
2064 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2066 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2067 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2068 instead of a list of pkgparts; the hashref has the following keys:
2072 =item pkgparts - listref of pkgparts
2074 =item (other options are passed to the suspend method)
2078 Returns a list: an empty list on success or a list of errors.
2082 sub suspend_unless_pkgpart {
2084 my (@pkgparts, %opt);
2085 if (ref($_[0]) eq 'HASH'){
2086 @pkgparts = @{$_[0]{pkgparts}};
2091 grep { $_->suspend(%opt) }
2092 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2093 $self->unsuspended_pkgs;
2096 =item cancel [ OPTION => VALUE ... ]
2098 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2100 Available options are:
2104 =item quiet - can be set true to supress email cancellation notices.
2106 =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.
2108 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2110 =item nobill - can be set true to skip billing if it might otherwise be done.
2114 Always returns a list: an empty list on success or a list of errors.
2118 # nb that dates are not specified as valid options to this method
2121 my( $self, %opt ) = @_;
2123 warn "$me cancel called on customer ". $self->custnum. " with options ".
2124 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2127 return ( 'access denied' )
2128 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2130 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2132 #should try decryption (we might have the private key)
2133 # and if not maybe queue a job for the server that does?
2134 return ( "Can't (yet) ban encrypted credit cards" )
2135 if $self->is_encrypted($self->payinfo);
2137 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2138 my $error = $ban->insert;
2139 return ( $error ) if $error;
2143 my @pkgs = $self->ncancelled_pkgs;
2145 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2147 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2148 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2152 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2153 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2156 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2159 sub _banned_pay_hashref {
2170 'payby' => $payby2ban{$self->payby},
2171 'payinfo' => $self->payinfo,
2172 #don't ever *search* on reason! #'reason' =>
2176 sub _new_banned_pay_hashref {
2178 my $hr = $self->_banned_pay_hashref;
2179 $hr->{payinfo} = md5_base64($hr->{payinfo});
2185 Returns all notes (see L<FS::cust_main_note>) for this customer.
2190 my($self,$orderby_classnum) = (shift,shift);
2191 my $orderby = "sticky DESC, _date DESC";
2192 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2193 qsearch( 'cust_main_note',
2194 { 'custnum' => $self->custnum },
2196 "ORDER BY $orderby",
2202 Returns the agent (see L<FS::agent>) for this customer.
2206 Returns the agent name (see L<FS::agent>) for this customer.
2212 $self->agent->agent;
2217 Returns any tags associated with this customer, as FS::cust_tag objects,
2218 or an empty list if there are no tags.
2222 Returns any tags associated with this customer, as FS::part_tag objects,
2223 or an empty list if there are no tags.
2229 map $_->part_tag, $self->cust_tag;
2235 Returns the customer class, as an FS::cust_class object, or the empty string
2236 if there is no customer class.
2240 Returns the customer category name, or the empty string if there is no customer
2247 my $cust_class = $self->cust_class;
2249 ? $cust_class->categoryname
2255 Returns the customer class name, or the empty string if there is no customer
2262 my $cust_class = $self->cust_class;
2264 ? $cust_class->classname
2270 Returns the external tax status, as an FS::tax_status object, or the empty
2271 string if there is no tax status.
2277 if ( $self->taxstatusnum ) {
2278 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2286 Returns the tax status code if there is one.
2292 my $tax_status = $self->tax_status;
2294 ? $tax_status->taxstatus
2298 =item BILLING METHODS
2300 Documentation on billing methods has been moved to
2301 L<FS::cust_main::Billing>.
2303 =item REALTIME BILLING METHODS
2305 Documentation on realtime billing methods has been moved to
2306 L<FS::cust_main::Billing_Realtime>.
2310 Removes the I<paycvv> field from the database directly.
2312 If there is an error, returns the error, otherwise returns false.
2318 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2319 or return dbh->errstr;
2320 $sth->execute($self->custnum)
2321 or return $sth->errstr;
2328 Returns the total owed for this customer on all invoices
2329 (see L<FS::cust_bill/owed>).
2335 $self->total_owed_date(2145859200); #12/31/2037
2338 =item total_owed_date TIME
2340 Returns the total owed for this customer on all invoices with date earlier than
2341 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2342 see L<Time::Local> and L<Date::Parse> for conversion functions.
2346 sub total_owed_date {
2350 my $custnum = $self->custnum;
2352 my $owed_sql = FS::cust_bill->owed_sql;
2355 SELECT SUM($owed_sql) FROM cust_bill
2356 WHERE custnum = $custnum
2360 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2364 =item total_owed_pkgnum PKGNUM
2366 Returns the total owed on all invoices for this customer's specific package
2367 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2371 sub total_owed_pkgnum {
2372 my( $self, $pkgnum ) = @_;
2373 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2376 =item total_owed_date_pkgnum TIME PKGNUM
2378 Returns the total owed for this customer's specific package when using
2379 experimental package balances on all invoices with date earlier than
2380 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2381 see L<Time::Local> and L<Date::Parse> for conversion functions.
2385 sub total_owed_date_pkgnum {
2386 my( $self, $time, $pkgnum ) = @_;
2389 foreach my $cust_bill (
2390 grep { $_->_date <= $time }
2391 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2393 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2395 sprintf( "%.2f", $total_bill );
2401 Returns the total amount of all payments.
2408 $total += $_->paid foreach $self->cust_pay;
2409 sprintf( "%.2f", $total );
2412 =item total_unapplied_credits
2414 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2415 customer. See L<FS::cust_credit/credited>.
2417 =item total_credited
2419 Old name for total_unapplied_credits. Don't use.
2423 sub total_credited {
2424 #carp "total_credited deprecated, use total_unapplied_credits";
2425 shift->total_unapplied_credits(@_);
2428 sub total_unapplied_credits {
2431 my $custnum = $self->custnum;
2433 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2436 SELECT SUM($unapplied_sql) FROM cust_credit
2437 WHERE custnum = $custnum
2440 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2444 =item total_unapplied_credits_pkgnum PKGNUM
2446 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2447 customer. See L<FS::cust_credit/credited>.
2451 sub total_unapplied_credits_pkgnum {
2452 my( $self, $pkgnum ) = @_;
2453 my $total_credit = 0;
2454 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2455 sprintf( "%.2f", $total_credit );
2459 =item total_unapplied_payments
2461 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2462 See L<FS::cust_pay/unapplied>.
2466 sub total_unapplied_payments {
2469 my $custnum = $self->custnum;
2471 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2474 SELECT SUM($unapplied_sql) FROM cust_pay
2475 WHERE custnum = $custnum
2478 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2482 =item total_unapplied_payments_pkgnum PKGNUM
2484 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2485 specific package when using experimental package balances. See
2486 L<FS::cust_pay/unapplied>.
2490 sub total_unapplied_payments_pkgnum {
2491 my( $self, $pkgnum ) = @_;
2492 my $total_unapplied = 0;
2493 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2494 sprintf( "%.2f", $total_unapplied );
2498 =item total_unapplied_refunds
2500 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2501 customer. See L<FS::cust_refund/unapplied>.
2505 sub total_unapplied_refunds {
2507 my $custnum = $self->custnum;
2509 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2512 SELECT SUM($unapplied_sql) FROM cust_refund
2513 WHERE custnum = $custnum
2516 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2522 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2523 total_unapplied_credits minus total_unapplied_payments).
2529 $self->balance_date_range;
2532 =item balance_date TIME
2534 Returns the balance for this customer, only considering invoices with date
2535 earlier than TIME (total_owed_date minus total_credited minus
2536 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2537 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2544 $self->balance_date_range(shift);
2547 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2549 Returns the balance for this customer, optionally considering invoices with
2550 date earlier than START_TIME, and not later than END_TIME
2551 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2553 Times are specified as SQL fragments or numeric
2554 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2555 L<Date::Parse> for conversion functions. The empty string can be passed
2556 to disable that time constraint completely.
2558 Accepts the same options as L<balance_date_sql>:
2562 =item unapplied_date
2564 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)
2568 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2569 time will be ignored. Note that START_TIME and END_TIME only limit the date
2570 range for invoices and I<unapplied> payments, credits, and refunds.
2576 sub balance_date_range {
2578 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2579 ') FROM cust_main WHERE custnum='. $self->custnum;
2580 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2583 =item balance_pkgnum PKGNUM
2585 Returns the balance for this customer's specific package when using
2586 experimental package balances (total_owed plus total_unrefunded, minus
2587 total_unapplied_credits minus total_unapplied_payments)
2591 sub balance_pkgnum {
2592 my( $self, $pkgnum ) = @_;
2595 $self->total_owed_pkgnum($pkgnum)
2596 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2597 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2598 - $self->total_unapplied_credits_pkgnum($pkgnum)
2599 - $self->total_unapplied_payments_pkgnum($pkgnum)
2605 Returns a hash of useful information for making a payment.
2615 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2616 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2617 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2621 For credit card transactions:
2633 For electronic check transactions:
2648 $return{balance} = $self->balance;
2650 $return{payname} = $self->payname
2651 || ( $self->first. ' '. $self->get('last') );
2653 $return{$_} = $self->bill_location->$_
2654 for qw(address1 address2 city state zip);
2656 $return{payby} = $self->payby;
2657 $return{stateid_state} = $self->stateid_state;
2659 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2660 $return{card_type} = cardtype($self->payinfo);
2661 $return{payinfo} = $self->paymask;
2663 @return{'month', 'year'} = $self->paydate_monthyear;
2667 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2668 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2669 $return{payinfo1} = $payinfo1;
2670 $return{payinfo2} = $payinfo2;
2671 $return{paytype} = $self->paytype;
2672 $return{paystate} = $self->paystate;
2676 #doubleclick protection
2678 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2684 =item paydate_monthyear
2686 Returns a two-element list consisting of the month and year of this customer's
2687 paydate (credit card expiration date for CARD customers)
2691 sub paydate_monthyear {
2693 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2695 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2704 Returns the exact time in seconds corresponding to the payment method
2705 expiration date. For CARD/DCRD customers this is the end of the month;
2706 for others (COMP is the only other payby that uses paydate) it's the start.
2707 Returns 0 if the paydate is empty or set to the far future.
2713 my ($month, $year) = $self->paydate_monthyear;
2714 return 0 if !$year or $year >= 2037;
2715 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2717 if ( $month == 13 ) {
2721 return timelocal(0,0,0,1,$month-1,$year) - 1;
2724 return timelocal(0,0,0,1,$month-1,$year);
2728 =item paydate_epoch_sql
2730 Class method. Returns an SQL expression to obtain the payment expiration date
2731 as a number of seconds.
2735 # Special expiration date behavior for non-CARD/DCRD customers has been
2736 # carefully preserved. Do we really use that?
2737 sub paydate_epoch_sql {
2739 my $table = shift || 'cust_main';
2740 my ($case1, $case2);
2741 if ( driver_name eq 'Pg' ) {
2742 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2743 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2745 elsif ( lc(driver_name) eq 'mysql' ) {
2746 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2747 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2750 return "CASE WHEN $table.payby IN('CARD','DCRD')
2756 =item tax_exemption TAXNAME
2761 my( $self, $taxname ) = @_;
2763 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2764 'taxname' => $taxname,
2769 =item cust_main_exemption
2771 =item invoicing_list [ ARRAYREF ]
2773 If an arguement is given, sets these email addresses as invoice recipients
2774 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2775 (except as warnings), so use check_invoicing_list first.
2777 Returns a list of email addresses (with svcnum entries expanded).
2779 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2780 check it without disturbing anything by passing nothing.
2782 This interface may change in the future.
2786 sub invoicing_list {
2787 my( $self, $arrayref ) = @_;
2790 my @cust_main_invoice;
2791 if ( $self->custnum ) {
2792 @cust_main_invoice =
2793 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2795 @cust_main_invoice = ();
2797 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2798 #warn $cust_main_invoice->destnum;
2799 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2800 #warn $cust_main_invoice->destnum;
2801 my $error = $cust_main_invoice->delete;
2802 warn $error if $error;
2805 if ( $self->custnum ) {
2806 @cust_main_invoice =
2807 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2809 @cust_main_invoice = ();
2811 my %seen = map { $_->address => 1 } @cust_main_invoice;
2812 foreach my $address ( @{$arrayref} ) {
2813 next if exists $seen{$address} && $seen{$address};
2814 $seen{$address} = 1;
2815 my $cust_main_invoice = new FS::cust_main_invoice ( {
2816 'custnum' => $self->custnum,
2819 my $error = $cust_main_invoice->insert;
2820 warn $error if $error;
2824 if ( $self->custnum ) {
2826 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2833 =item check_invoicing_list ARRAYREF
2835 Checks these arguements as valid input for the invoicing_list method. If there
2836 is an error, returns the error, otherwise returns false.
2840 sub check_invoicing_list {
2841 my( $self, $arrayref ) = @_;
2843 foreach my $address ( @$arrayref ) {
2845 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2846 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2849 my $cust_main_invoice = new FS::cust_main_invoice ( {
2850 'custnum' => $self->custnum,
2853 my $error = $self->custnum
2854 ? $cust_main_invoice->check
2855 : $cust_main_invoice->checkdest
2857 return $error if $error;
2861 return "Email address required"
2862 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2863 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2868 =item set_default_invoicing_list
2870 Sets the invoicing list to all accounts associated with this customer,
2871 overwriting any previous invoicing list.
2875 sub set_default_invoicing_list {
2877 $self->invoicing_list($self->all_emails);
2882 Returns the email addresses of all accounts provisioned for this customer.
2889 foreach my $cust_pkg ( $self->all_pkgs ) {
2890 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2892 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2893 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2895 $list{$_}=1 foreach map { $_->email } @svc_acct;
2900 =item invoicing_list_addpost
2902 Adds postal invoicing to this customer. If this customer is already configured
2903 to receive postal invoices, does nothing.
2907 sub invoicing_list_addpost {
2909 return if grep { $_ eq 'POST' } $self->invoicing_list;
2910 my @invoicing_list = $self->invoicing_list;
2911 push @invoicing_list, 'POST';
2912 $self->invoicing_list(\@invoicing_list);
2915 =item invoicing_list_emailonly
2917 Returns the list of email invoice recipients (invoicing_list without non-email
2918 destinations such as POST and FAX).
2922 sub invoicing_list_emailonly {
2924 warn "$me invoicing_list_emailonly called"
2926 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
2929 =item invoicing_list_emailonly_scalar
2931 Returns the list of email invoice recipients (invoicing_list without non-email
2932 destinations such as POST and FAX) as a comma-separated scalar.
2936 sub invoicing_list_emailonly_scalar {
2938 warn "$me invoicing_list_emailonly_scalar called"
2940 join(', ', $self->invoicing_list_emailonly);
2943 =item referral_custnum_cust_main
2945 Returns the customer who referred this customer (or the empty string, if
2946 this customer was not referred).
2948 Note the difference with referral_cust_main method: This method,
2949 referral_custnum_cust_main returns the single customer (if any) who referred
2950 this customer, while referral_cust_main returns an array of customers referred
2955 sub referral_custnum_cust_main {
2957 return '' unless $self->referral_custnum;
2958 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2961 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
2963 Returns an array of customers referred by this customer (referral_custnum set
2964 to this custnum). If DEPTH is given, recurses up to the given depth, returning
2965 customers referred by customers referred by this customer and so on, inclusive.
2966 The default behavior is DEPTH 1 (no recursion).
2968 Note the difference with referral_custnum_cust_main method: This method,
2969 referral_cust_main, returns an array of customers referred BY this customer,
2970 while referral_custnum_cust_main returns the single customer (if any) who
2971 referred this customer.
2975 sub referral_cust_main {
2977 my $depth = @_ ? shift : 1;
2978 my $exclude = @_ ? shift : {};
2981 map { $exclude->{$_->custnum}++; $_; }
2982 grep { ! $exclude->{ $_->custnum } }
2983 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
2987 map { $_->referral_cust_main($depth-1, $exclude) }
2994 =item referral_cust_main_ncancelled
2996 Same as referral_cust_main, except only returns customers with uncancelled
3001 sub referral_cust_main_ncancelled {
3003 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3006 =item referral_cust_pkg [ DEPTH ]
3008 Like referral_cust_main, except returns a flat list of all unsuspended (and
3009 uncancelled) packages for each customer. The number of items in this list may
3010 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3014 sub referral_cust_pkg {
3016 my $depth = @_ ? shift : 1;
3018 map { $_->unsuspended_pkgs }
3019 grep { $_->unsuspended_pkgs }
3020 $self->referral_cust_main($depth);
3023 =item referring_cust_main
3025 Returns the single cust_main record for the customer who referred this customer
3026 (referral_custnum), or false.
3030 sub referring_cust_main {
3032 return '' unless $self->referral_custnum;
3033 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3036 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3038 Applies a credit to this customer. If there is an error, returns the error,
3039 otherwise returns false.
3041 REASON can be a text string, an FS::reason object, or a scalar reference to
3042 a reasonnum. If a text string, it will be automatically inserted as a new
3043 reason, and a 'reason_type' option must be passed to indicate the
3044 FS::reason_type for the new reason.
3046 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3047 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3048 I<commission_pkgnum>.
3050 Any other options are passed to FS::cust_credit::insert.
3055 my( $self, $amount, $reason, %options ) = @_;
3057 my $cust_credit = new FS::cust_credit {
3058 'custnum' => $self->custnum,
3059 'amount' => $amount,
3062 if ( ref($reason) ) {
3064 if ( ref($reason) eq 'SCALAR' ) {
3065 $cust_credit->reasonnum( $$reason );
3067 $cust_credit->reasonnum( $reason->reasonnum );
3071 $cust_credit->set('reason', $reason)
3074 $cust_credit->$_( delete $options{$_} )
3075 foreach grep exists($options{$_}),
3076 qw( addlinfo eventnum ),
3077 map "commission_$_", qw( agentnum salesnum pkgnum );
3079 $cust_credit->insert(%options);
3083 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3085 Creates a one-time charge for this customer. If there is an error, returns
3086 the error, otherwise returns false.
3088 New-style, with a hashref of options:
3090 my $error = $cust_main->charge(
3094 'start_date' => str2time('7/4/2009'),
3095 'pkg' => 'Description',
3096 'comment' => 'Comment',
3097 'additional' => [], #extra invoice detail
3098 'classnum' => 1, #pkg_class
3100 'setuptax' => '', # or 'Y' for tax exempt
3102 'locationnum'=> 1234, # optional
3105 'taxclass' => 'Tax class',
3108 'taxproduct' => 2, #part_pkg_taxproduct
3109 'override' => {}, #XXX describe
3111 #will be filled in with the new object
3112 'cust_pkg_ref' => \$cust_pkg,
3114 #generate an invoice immediately
3116 'invoice_terms' => '', #with these terms
3122 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3126 #super false laziness w/quotation::charge
3129 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3130 my ( $pkg, $comment, $additional );
3131 my ( $setuptax, $taxclass ); #internal taxes
3132 my ( $taxproduct, $override ); #vendor (CCH) taxes
3134 my $separate_bill = '';
3135 my $cust_pkg_ref = '';
3136 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3138 if ( ref( $_[0] ) ) {
3139 $amount = $_[0]->{amount};
3140 $setup_cost = $_[0]->{setup_cost};
3141 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3142 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3143 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3144 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3145 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3146 : '$'. sprintf("%.2f",$amount);
3147 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3148 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3149 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3150 $additional = $_[0]->{additional} || [];
3151 $taxproduct = $_[0]->{taxproductnum};
3152 $override = { '' => $_[0]->{tax_override} };
3153 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3154 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3155 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3156 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3157 $separate_bill = $_[0]->{separate_bill} || '';
3163 $pkg = @_ ? shift : 'One-time charge';
3164 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3166 $taxclass = @_ ? shift : '';
3170 local $SIG{HUP} = 'IGNORE';
3171 local $SIG{INT} = 'IGNORE';
3172 local $SIG{QUIT} = 'IGNORE';
3173 local $SIG{TERM} = 'IGNORE';
3174 local $SIG{TSTP} = 'IGNORE';
3175 local $SIG{PIPE} = 'IGNORE';
3177 my $oldAutoCommit = $FS::UID::AutoCommit;
3178 local $FS::UID::AutoCommit = 0;
3181 my $part_pkg = new FS::part_pkg ( {
3183 'comment' => $comment,
3187 'classnum' => ( $classnum ? $classnum : '' ),
3188 'setuptax' => $setuptax,
3189 'taxclass' => $taxclass,
3190 'taxproductnum' => $taxproduct,
3191 'setup_cost' => $setup_cost,
3194 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3195 ( 0 .. @$additional - 1 )
3197 'additional_count' => scalar(@$additional),
3198 'setup_fee' => $amount,
3201 my $error = $part_pkg->insert( options => \%options,
3202 tax_overrides => $override,
3205 $dbh->rollback if $oldAutoCommit;
3209 my $pkgpart = $part_pkg->pkgpart;
3210 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3211 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3212 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3213 $error = $type_pkgs->insert;
3215 $dbh->rollback if $oldAutoCommit;
3220 my $cust_pkg = new FS::cust_pkg ( {
3221 'custnum' => $self->custnum,
3222 'pkgpart' => $pkgpart,
3223 'quantity' => $quantity,
3224 'start_date' => $start_date,
3225 'no_auto' => $no_auto,
3226 'separate_bill' => $separate_bill,
3227 'locationnum'=> $locationnum,
3230 $error = $cust_pkg->insert;
3232 $dbh->rollback if $oldAutoCommit;
3234 } elsif ( $cust_pkg_ref ) {
3235 ${$cust_pkg_ref} = $cust_pkg;
3239 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3240 'pkg_list' => [ $cust_pkg ],
3243 $dbh->rollback if $oldAutoCommit;
3248 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3253 #=item charge_postal_fee
3255 #Applies a one time charge this customer. If there is an error,
3256 #returns the error, returns the cust_pkg charge object or false
3257 #if there was no charge.
3261 # This should be a customer event. For that to work requires that bill
3262 # also be a customer event.
3264 sub charge_postal_fee {
3267 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3268 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3270 my $cust_pkg = new FS::cust_pkg ( {
3271 'custnum' => $self->custnum,
3272 'pkgpart' => $pkgpart,
3276 my $error = $cust_pkg->insert;
3277 $error ? $error : $cust_pkg;
3280 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3282 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3284 Optionally, a list or hashref of additional arguments to the qsearch call can
3291 my $opt = ref($_[0]) ? shift : { @_ };
3293 #return $self->num_cust_bill unless wantarray || keys %$opt;
3295 $opt->{'table'} = 'cust_bill';
3296 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3297 $opt->{'hashref'}{'custnum'} = $self->custnum;
3298 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3300 map { $_ } #behavior of sort undefined in scalar context
3301 sort { $a->_date <=> $b->_date }
3305 =item open_cust_bill
3307 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3312 sub open_cust_bill {
3316 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3322 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3324 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3328 sub legacy_cust_bill {
3331 #return $self->num_legacy_cust_bill unless wantarray;
3333 map { $_ } #behavior of sort undefined in scalar context
3334 sort { $a->_date <=> $b->_date }
3335 qsearch({ 'table' => 'legacy_cust_bill',
3336 'hashref' => { 'custnum' => $self->custnum, },
3337 'order_by' => 'ORDER BY _date ASC',
3341 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3343 Returns all the statements (see L<FS::cust_statement>) for this customer.
3345 Optionally, a list or hashref of additional arguments to the qsearch call can
3350 =item cust_bill_void
3352 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3356 sub cust_bill_void {
3359 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3360 sort { $a->_date <=> $b->_date }
3361 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3364 sub cust_statement {
3366 my $opt = ref($_[0]) ? shift : { @_ };
3368 #return $self->num_cust_statement unless wantarray || keys %$opt;
3370 $opt->{'table'} = 'cust_statement';
3371 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3372 $opt->{'hashref'}{'custnum'} = $self->custnum;
3373 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3375 map { $_ } #behavior of sort undefined in scalar context
3376 sort { $a->_date <=> $b->_date }
3380 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3382 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3384 Optionally, a list or hashref of additional arguments to the qsearch call can
3385 be passed following the SVCDB.
3392 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3393 warn "$me svc_x requires a svcdb";
3396 my $opt = ref($_[0]) ? shift : { @_ };
3398 $opt->{'table'} = $svcdb;
3399 $opt->{'addl_from'} =
3400 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3401 ($opt->{'addl_from'} || '');
3403 my $custnum = $self->custnum;
3404 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3405 my $where = "cust_pkg.custnum = $custnum";
3407 my $extra_sql = $opt->{'extra_sql'} || '';
3408 if ( keys %{ $opt->{'hashref'} } ) {
3409 $extra_sql = " AND $where $extra_sql";
3412 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3413 $extra_sql = "WHERE $where AND $1";
3416 $extra_sql = "WHERE $where $extra_sql";
3419 $opt->{'extra_sql'} = $extra_sql;
3424 # required for use as an eventtable;
3427 $self->svc_x('svc_acct', @_);
3432 Returns all the credits (see L<FS::cust_credit>) for this customer.
3438 map { $_ } #return $self->num_cust_credit unless wantarray;
3439 sort { $a->_date <=> $b->_date }
3440 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3443 =item cust_credit_pkgnum
3445 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3446 package when using experimental package balances.
3450 sub cust_credit_pkgnum {
3451 my( $self, $pkgnum ) = @_;
3452 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3453 sort { $a->_date <=> $b->_date }
3454 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3455 'pkgnum' => $pkgnum,
3460 =item cust_credit_void
3462 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3466 sub cust_credit_void {
3469 sort { $a->_date <=> $b->_date }
3470 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3475 Returns all the payments (see L<FS::cust_pay>) for this customer.
3481 my $opt = ref($_[0]) ? shift : { @_ };
3483 return $self->num_cust_pay unless wantarray || keys %$opt;
3485 $opt->{'table'} = 'cust_pay';
3486 $opt->{'hashref'}{'custnum'} = $self->custnum;
3488 map { $_ } #behavior of sort undefined in scalar context
3489 sort { $a->_date <=> $b->_date }
3496 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3497 called automatically when the cust_pay method is used in a scalar context.
3503 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3504 my $sth = dbh->prepare($sql) or die dbh->errstr;
3505 $sth->execute($self->custnum) or die $sth->errstr;
3506 $sth->fetchrow_arrayref->[0];
3509 =item unapplied_cust_pay
3511 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3515 sub unapplied_cust_pay {
3519 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3525 =item cust_pay_pkgnum
3527 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3528 package when using experimental package balances.
3532 sub cust_pay_pkgnum {
3533 my( $self, $pkgnum ) = @_;
3534 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3535 sort { $a->_date <=> $b->_date }
3536 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3537 'pkgnum' => $pkgnum,
3544 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3550 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3551 sort { $a->_date <=> $b->_date }
3552 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3555 =item cust_pay_pending
3557 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3558 (without status "done").
3562 sub cust_pay_pending {
3564 return $self->num_cust_pay_pending unless wantarray;
3565 sort { $a->_date <=> $b->_date }
3566 qsearch( 'cust_pay_pending', {
3567 'custnum' => $self->custnum,
3568 'status' => { op=>'!=', value=>'done' },
3573 =item cust_pay_pending_attempt
3575 Returns all payment attempts / declined payments for this customer, as pending
3576 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3577 a corresponding payment (see L<FS::cust_pay>).
3581 sub cust_pay_pending_attempt {
3583 return $self->num_cust_pay_pending_attempt unless wantarray;
3584 sort { $a->_date <=> $b->_date }
3585 qsearch( 'cust_pay_pending', {
3586 'custnum' => $self->custnum,
3593 =item num_cust_pay_pending
3595 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3596 customer (without status "done"). Also called automatically when the
3597 cust_pay_pending method is used in a scalar context.
3601 sub num_cust_pay_pending {
3604 " SELECT COUNT(*) FROM cust_pay_pending ".
3605 " WHERE custnum = ? AND status != 'done' ",
3610 =item num_cust_pay_pending_attempt
3612 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3613 customer, with status "done" but without a corresp. Also called automatically when the
3614 cust_pay_pending method is used in a scalar context.
3618 sub num_cust_pay_pending_attempt {
3621 " SELECT COUNT(*) FROM cust_pay_pending ".
3622 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3629 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3635 map { $_ } #return $self->num_cust_refund unless wantarray;
3636 sort { $a->_date <=> $b->_date }
3637 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3640 =item display_custnum
3642 Returns the displayed customer number for this customer: agent_custid if
3643 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3647 sub display_custnum {
3650 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3651 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3652 if ( $special eq 'CoStAg' ) {
3653 $prefix = uc( join('',
3655 ($self->state =~ /^(..)/),
3656 $prefix || ($self->agent->agent =~ /^(..)/)
3659 elsif ( $special eq 'CoStCl' ) {
3660 $prefix = uc( join('',
3662 ($self->state =~ /^(..)/),
3663 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3666 # add any others here if needed
3669 my $length = $conf->config('cust_main-custnum-display_length');
3670 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3671 return $self->agent_custid;
3672 } elsif ( $prefix ) {
3673 $length = 8 if !defined($length);
3675 sprintf('%0'.$length.'d', $self->custnum)
3676 } elsif ( $length ) {
3677 return sprintf('%0'.$length.'d', $self->custnum);
3679 return $self->custnum;
3685 Returns a name string for this customer, either "Company (Last, First)" or
3692 my $name = $self->contact;
3693 $name = $self->company. " ($name)" if $self->company;
3697 =item service_contact
3699 Returns the L<FS::contact> object for this customer that has the 'Service'
3700 contact class, or undef if there is no such contact. Deprecated; don't use
3705 sub service_contact {
3707 if ( !exists($self->{service_contact}) ) {
3708 my $classnum = $self->scalar_sql(
3709 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3710 ) || 0; #if it's zero, qsearchs will return nothing
3711 my $cust_contact = qsearchs('cust_contact', {
3712 'classnum' => $classnum,
3713 'custnum' => $self->custnum,
3715 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3717 $self->{service_contact};
3722 Returns a name string for this (service/shipping) contact, either
3723 "Company (Last, First)" or "Last, First".
3730 my $name = $self->ship_contact;
3731 $name = $self->company. " ($name)" if $self->company;
3737 Returns a name string for this customer, either "Company" or "First Last".
3743 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3746 =item ship_name_short
3748 Returns a name string for this (service/shipping) contact, either "Company"
3753 sub ship_name_short {
3755 $self->service_contact
3756 ? $self->ship_contact_firstlast
3762 Returns this customer's full (billing) contact name only, "Last, First"
3768 $self->get('last'). ', '. $self->first;
3773 Returns this customer's full (shipping) contact name only, "Last, First"
3779 my $contact = $self->service_contact || $self;
3780 $contact->get('last') . ', ' . $contact->get('first');
3783 =item contact_firstlast
3785 Returns this customers full (billing) contact name only, "First Last".
3789 sub contact_firstlast {
3791 $self->first. ' '. $self->get('last');
3794 =item ship_contact_firstlast
3796 Returns this customer's full (shipping) contact name only, "First Last".
3800 sub ship_contact_firstlast {
3802 my $contact = $self->service_contact || $self;
3803 $contact->get('first') . ' '. $contact->get('last');
3806 #XXX this doesn't work in 3.x+
3809 #Returns this customer's full country name
3815 # code2country($self->country);
3818 sub bill_country_full {
3820 code2country($self->bill_location->country);
3823 sub ship_country_full {
3825 code2country($self->ship_location->country);
3828 =item county_state_county [ PREFIX ]
3830 Returns a string consisting of just the county, state and country.
3834 sub county_state_country {
3837 if ( @_ && $_[0] && $self->has_ship_address ) {
3838 $locationnum = $self->ship_locationnum;
3840 $locationnum = $self->bill_locationnum;
3842 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3843 $cust_location->county_state_country;
3846 =item geocode DATA_VENDOR
3848 Returns a value for the customer location as encoded by DATA_VENDOR.
3849 Currently this only makes sense for "CCH" as DATA_VENDOR.
3857 Returns a status string for this customer, currently:
3863 No packages have ever been ordered. Displayed as "No packages".
3867 Recurring packages all are new (not yet billed).
3871 One or more recurring packages is active.
3875 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3879 All non-cancelled recurring packages are suspended.
3883 All recurring packages are cancelled.
3887 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3888 cust_main-status_module configuration option.
3892 sub status { shift->cust_status(@_); }
3896 for my $status ( FS::cust_main->statuses() ) {
3897 my $method = $status.'_sql';
3898 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3899 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3900 $sth->execute( ($self->custnum) x $numnum )
3901 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3902 return $status if $sth->fetchrow_arrayref->[0];
3906 =item is_status_delay_cancel
3908 Returns true if customer status is 'suspended'
3909 and all suspended cust_pkg return true for
3910 cust_pkg->is_status_delay_cancel.
3912 This is not a real status, this only meant for hacking display
3913 values, because otherwise treating the customer as suspended is
3914 really the whole point of the delay_cancel option.
3918 sub is_status_delay_cancel {
3920 return 0 unless $self->status eq 'suspended';
3921 foreach my $cust_pkg ($self->ncancelled_pkgs) {
3922 return 0 unless $cust_pkg->is_status_delay_cancel;
3927 =item ucfirst_cust_status
3929 =item ucfirst_status
3931 Deprecated, use the cust_status_label method instead.
3933 Returns the status with the first character capitalized.
3937 sub ucfirst_status {
3938 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3939 local($ucfirst_nowarn) = 1;
3940 shift->ucfirst_cust_status(@_);
3943 sub ucfirst_cust_status {
3944 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3946 ucfirst($self->cust_status);
3949 =item cust_status_label
3953 Returns the display label for this status.
3957 sub status_label { shift->cust_status_label(@_); }
3959 sub cust_status_label {
3961 __PACKAGE__->statuslabels->{$self->cust_status};
3966 Returns a hex triplet color string for this customer's status.
3970 sub statuscolor { shift->cust_statuscolor(@_); }
3972 sub cust_statuscolor {
3974 __PACKAGE__->statuscolors->{$self->cust_status};
3977 =item tickets [ STATUS ]
3979 Returns an array of hashes representing the customer's RT tickets.
3981 An optional status (or arrayref or hashref of statuses) may be specified.
3987 my $status = ( @_ && $_[0] ) ? shift : '';
3989 my $num = $conf->config('cust_main-max_tickets') || 10;
3992 if ( $conf->config('ticket_system') ) {
3993 unless ( $conf->config('ticket_system-custom_priority_field') ) {
3995 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4004 foreach my $priority (
4005 $conf->config('ticket_system-custom_priority_field-values'), ''
4007 last if scalar(@tickets) >= $num;
4009 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4010 $num - scalar(@tickets),
4021 # Return services representing svc_accts in customer support packages
4022 sub support_services {
4024 my %packages = map { $_ => 1 } $conf->config('support_packages');
4026 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4027 grep { $_->part_svc->svcdb eq 'svc_acct' }
4028 map { $_->cust_svc }
4029 grep { exists $packages{ $_->pkgpart } }
4030 $self->ncancelled_pkgs;
4034 # Return a list of latitude/longitude for one of the services (if any)
4035 sub service_coordinates {
4039 grep { $_->latitude && $_->longitude }
4041 map { $_->cust_svc }
4042 $self->ncancelled_pkgs;
4044 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4049 Returns a masked version of the named field
4054 my ($self,$field) = @_;
4058 'x'x(length($self->getfield($field))-4).
4059 substr($self->getfield($field), (length($self->getfield($field))-4));
4065 =head1 CLASS METHODS
4071 Class method that returns the list of possible status strings for customers
4072 (see L<the status method|/status>). For example:
4074 @statuses = FS::cust_main->statuses();
4080 keys %{ $self->statuscolors };
4083 =item cust_status_sql
4085 Returns an SQL fragment to determine the status of a cust_main record, as a
4090 sub cust_status_sql {
4092 for my $status ( FS::cust_main->statuses() ) {
4093 my $method = $status.'_sql';
4094 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4103 Returns an SQL expression identifying prospective cust_main records (customers
4104 with no packages ever ordered)
4108 use vars qw($select_count_pkgs);
4109 $select_count_pkgs =
4110 "SELECT COUNT(*) FROM cust_pkg
4111 WHERE cust_pkg.custnum = cust_main.custnum";
4113 sub select_count_pkgs_sql {
4118 " 0 = ( $select_count_pkgs ) ";
4123 Returns an SQL expression identifying ordered cust_main records (customers with
4124 no active packages, but recurring packages not yet setup or one time charges
4130 FS::cust_main->none_active_sql.
4131 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4136 Returns an SQL expression identifying active cust_main records (customers with
4137 active recurring packages).
4142 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4145 =item none_active_sql
4147 Returns an SQL expression identifying cust_main records with no active
4148 recurring packages. This includes customers of status prospect, ordered,
4149 inactive, and suspended.
4153 sub none_active_sql {
4154 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4159 Returns an SQL expression identifying inactive cust_main records (customers with
4160 no active recurring packages, but otherwise unsuspended/uncancelled).
4165 FS::cust_main->none_active_sql.
4166 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4172 Returns an SQL expression identifying suspended cust_main records.
4177 sub suspended_sql { susp_sql(@_); }
4179 FS::cust_main->none_active_sql.
4180 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4186 Returns an SQL expression identifying cancelled cust_main records.
4190 sub cancel_sql { shift->cancelled_sql(@_); }
4193 =item uncancelled_sql
4195 Returns an SQL expression identifying un-cancelled cust_main records.
4199 sub uncancelled_sql { uncancel_sql(@_); }
4200 sub uncancel_sql { "
4201 ( 0 < ( $select_count_pkgs
4202 AND ( cust_pkg.cancel IS NULL
4203 OR cust_pkg.cancel = 0
4206 OR 0 = ( $select_count_pkgs )
4212 Returns an SQL fragment to retreive the balance.
4217 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4218 WHERE cust_bill.custnum = cust_main.custnum )
4219 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4220 WHERE cust_pay.custnum = cust_main.custnum )
4221 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4222 WHERE cust_credit.custnum = cust_main.custnum )
4223 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4224 WHERE cust_refund.custnum = cust_main.custnum )
4227 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4229 Returns an SQL fragment to retreive the balance for this customer, optionally
4230 considering invoices with date earlier than START_TIME, and not
4231 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4232 total_unapplied_payments).
4234 Times are specified as SQL fragments or numeric
4235 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4236 L<Date::Parse> for conversion functions. The empty string can be passed
4237 to disable that time constraint completely.
4239 Available options are:
4243 =item unapplied_date
4245 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)
4250 set to true to remove all customer comparison clauses, for totals
4255 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4260 JOIN clause (typically used with the total option)
4264 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4265 time will be ignored. Note that START_TIME and END_TIME only limit the date
4266 range for invoices and I<unapplied> payments, credits, and refunds.
4272 sub balance_date_sql {
4273 my( $class, $start, $end, %opt ) = @_;
4275 my $cutoff = $opt{'cutoff'};
4277 my $owed = FS::cust_bill->owed_sql($cutoff);
4278 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4279 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4280 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4282 my $j = $opt{'join'} || '';
4284 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4285 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4286 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4287 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4289 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4290 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4291 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4292 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4297 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4299 Returns an SQL fragment to retreive the total unapplied payments for this
4300 customer, only considering payments with date earlier than START_TIME, and
4301 optionally not later than END_TIME.
4303 Times are specified as SQL fragments or numeric
4304 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4305 L<Date::Parse> for conversion functions. The empty string can be passed
4306 to disable that time constraint completely.
4308 Available options are:
4312 sub unapplied_payments_date_sql {
4313 my( $class, $start, $end, %opt ) = @_;
4315 my $cutoff = $opt{'cutoff'};
4317 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4319 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4320 'unapplied_date'=>1 );
4322 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4325 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4327 Helper method for balance_date_sql; name (and usage) subject to change
4328 (suggestions welcome).
4330 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4331 cust_refund, cust_credit or cust_pay).
4333 If TABLE is "cust_bill" or the unapplied_date option is true, only
4334 considers records with date earlier than START_TIME, and optionally not
4335 later than END_TIME .
4339 sub _money_table_where {
4340 my( $class, $table, $start, $end, %opt ) = @_;
4343 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4344 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4345 push @where, "$table._date <= $start" if defined($start) && length($start);
4346 push @where, "$table._date > $end" if defined($end) && length($end);
4348 push @where, @{$opt{'where'}} if $opt{'where'};
4349 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4355 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4356 use FS::cust_main::Search;
4359 FS::cust_main::Search->search(@_);
4368 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4370 Deprecated. Use event notification and message templates
4371 (L<FS::msg_template>) instead.
4373 Sends a templated email notification to the customer (see L<Text::Template>).
4375 OPTIONS is a hash and may include
4377 I<from> - the email sender (default is invoice_from)
4379 I<to> - comma-separated scalar or arrayref of recipients
4380 (default is invoicing_list)
4382 I<subject> - The subject line of the sent email notification
4383 (default is "Notice from company_name")
4385 I<extra_fields> - a hashref of name/value pairs which will be substituted
4388 The following variables are vavailable in the template.
4390 I<$first> - the customer first name
4391 I<$last> - the customer last name
4392 I<$company> - the customer company
4393 I<$payby> - a description of the method of payment for the customer
4394 # would be nice to use FS::payby::shortname
4395 I<$payinfo> - the account information used to collect for this customer
4396 I<$expdate> - the expiration of the customer payment in seconds from epoch
4401 my ($self, $template, %options) = @_;
4403 return unless $conf->exists($template);
4405 my $from = $conf->invoice_from_full($self->agentnum)
4406 if $conf->exists('invoice_from', $self->agentnum);
4407 $from = $options{from} if exists($options{from});
4409 my $to = join(',', $self->invoicing_list_emailonly);
4410 $to = $options{to} if exists($options{to});
4412 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4413 if $conf->exists('company_name', $self->agentnum);
4414 $subject = $options{subject} if exists($options{subject});
4416 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4417 SOURCE => [ map "$_\n",
4418 $conf->config($template)]
4420 or die "can't create new Text::Template object: Text::Template::ERROR";
4421 $notify_template->compile()
4422 or die "can't compile template: Text::Template::ERROR";
4424 $FS::notify_template::_template::company_name =
4425 $conf->config('company_name', $self->agentnum);
4426 $FS::notify_template::_template::company_address =
4427 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4429 my $paydate = $self->paydate || '2037-12-31';
4430 $FS::notify_template::_template::first = $self->first;
4431 $FS::notify_template::_template::last = $self->last;
4432 $FS::notify_template::_template::company = $self->company;
4433 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4434 my $payby = $self->payby;
4435 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4436 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4438 #credit cards expire at the end of the month/year of their exp date
4439 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4440 $FS::notify_template::_template::payby = 'credit card';
4441 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4442 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4444 }elsif ($payby eq 'COMP') {
4445 $FS::notify_template::_template::payby = 'complimentary account';
4447 $FS::notify_template::_template::payby = 'current method';
4449 $FS::notify_template::_template::expdate = $expire_time;
4451 for (keys %{$options{extra_fields}}){
4453 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4456 send_email(from => $from,
4458 subject => $subject,
4459 body => $notify_template->fill_in( PACKAGE =>
4460 'FS::notify_template::_template' ),
4465 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4467 Generates a templated notification to the customer (see L<Text::Template>).
4469 OPTIONS is a hash and may include
4471 I<extra_fields> - a hashref of name/value pairs which will be substituted
4472 into the template. These values may override values mentioned below
4473 and those from the customer record.
4475 The following variables are available in the template instead of or in addition
4476 to the fields of the customer record.
4478 I<$payby> - a description of the method of payment for the customer
4479 # would be nice to use FS::payby::shortname
4480 I<$payinfo> - the masked account information used to collect for this customer
4481 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4482 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4486 # a lot like cust_bill::print_latex
4487 sub generate_letter {
4488 my ($self, $template, %options) = @_;
4490 return unless $conf->exists($template);
4492 my $letter_template = new Text::Template
4494 SOURCE => [ map "$_\n", $conf->config($template)],
4495 DELIMITERS => [ '[@--', '--@]' ],
4497 or die "can't create new Text::Template object: Text::Template::ERROR";
4499 $letter_template->compile()
4500 or die "can't compile template: Text::Template::ERROR";
4502 my %letter_data = map { $_ => $self->$_ } $self->fields;
4503 $letter_data{payinfo} = $self->mask_payinfo;
4505 #my $paydate = $self->paydate || '2037-12-31';
4506 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4508 my $payby = $self->payby;
4509 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4510 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4512 #credit cards expire at the end of the month/year of their exp date
4513 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4514 $letter_data{payby} = 'credit card';
4515 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4516 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4518 }elsif ($payby eq 'COMP') {
4519 $letter_data{payby} = 'complimentary account';
4521 $letter_data{payby} = 'current method';
4523 $letter_data{expdate} = $expire_time;
4525 for (keys %{$options{extra_fields}}){
4526 $letter_data{$_} = $options{extra_fields}->{$_};
4529 unless(exists($letter_data{returnaddress})){
4530 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4531 $self->agent_template)
4533 if ( length($retadd) ) {
4534 $letter_data{returnaddress} = $retadd;
4535 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4536 $letter_data{returnaddress} =
4537 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4541 ( $conf->config('company_name', $self->agentnum),
4542 $conf->config('company_address', $self->agentnum),
4546 $letter_data{returnaddress} = '~';
4550 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4552 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4554 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4556 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4560 ) or die "can't open temp file: $!\n";
4561 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4562 or die "can't write temp file: $!\n";
4564 $letter_data{'logo_file'} = $lh->filename;
4566 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4570 ) or die "can't open temp file: $!\n";
4572 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4574 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4575 return ($1, $letter_data{'logo_file'});
4579 =item print_ps TEMPLATE
4581 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4587 my($file, $lfile) = $self->generate_letter(@_);
4588 my $ps = FS::Misc::generate_ps($file);
4589 unlink($file.'.tex');
4595 =item print TEMPLATE
4597 Prints the filled in template.
4599 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4603 sub queueable_print {
4606 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4607 or die "invalid customer number: " . $opt{custnum};
4609 my $error = $self->print( { 'template' => $opt{template} } );
4610 die $error if $error;
4614 my ($self, $template) = (shift, shift);
4616 [ $self->print_ps($template) ],
4617 'agentnum' => $self->agentnum,
4621 #these three subs should just go away once agent stuff is all config overrides
4623 sub agent_template {
4625 $self->_agent_plandata('agent_templatename');
4628 sub agent_invoice_from {
4630 $self->_agent_plandata('agent_invoice_from');
4633 sub _agent_plandata {
4634 my( $self, $option ) = @_;
4636 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4637 #agent-specific Conf
4639 use FS::part_event::Condition;
4641 my $agentnum = $self->agentnum;
4643 my $regexp = regexp_sql();
4645 my $part_event_option =
4647 'select' => 'part_event_option.*',
4648 'table' => 'part_event_option',
4650 LEFT JOIN part_event USING ( eventpart )
4651 LEFT JOIN part_event_option AS peo_agentnum
4652 ON ( part_event.eventpart = peo_agentnum.eventpart
4653 AND peo_agentnum.optionname = 'agentnum'
4654 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4656 LEFT JOIN part_event_condition
4657 ON ( part_event.eventpart = part_event_condition.eventpart
4658 AND part_event_condition.conditionname = 'cust_bill_age'
4660 LEFT JOIN part_event_condition_option
4661 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4662 AND part_event_condition_option.optionname = 'age'
4665 #'hashref' => { 'optionname' => $option },
4666 #'hashref' => { 'part_event_option.optionname' => $option },
4668 " WHERE part_event_option.optionname = ". dbh->quote($option).
4669 " AND action = 'cust_bill_send_agent' ".
4670 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4671 " AND peo_agentnum.optionname = 'agentnum' ".
4672 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4674 CASE WHEN part_event_condition_option.optionname IS NULL
4676 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4678 , part_event.weight".
4682 unless ( $part_event_option ) {
4683 return $self->agent->invoice_template || ''
4684 if $option eq 'agent_templatename';
4688 $part_event_option->optionvalue;
4692 sub process_o2m_qsearch {
4695 return qsearch($table, @_) unless $table eq 'contact';
4697 my $hashref = shift;
4698 my %hash = %$hashref;
4699 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4700 or die 'guru meditation #4343';
4702 qsearch({ 'table' => 'contact',
4703 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4704 'hashref' => \%hash,
4705 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4706 " cust_contact.custnum = $custnum "
4710 sub process_o2m_qsearchs {
4713 return qsearchs($table, @_) unless $table eq 'contact';
4715 my $hashref = shift;
4716 my %hash = %$hashref;
4717 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4718 or die 'guru meditation #2121';
4720 qsearchs({ 'table' => 'contact',
4721 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4722 'hashref' => \%hash,
4723 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4724 " cust_contact.custnum = $custnum "
4728 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4730 Subroutine (not a method), designed to be called from the queue.
4732 Takes a list of options and values.
4734 Pulls up the customer record via the custnum option and calls bill_and_collect.
4739 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4741 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4742 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4744 #without this errors don't get rolled back
4745 $args{'fatal'} = 1; # runs from job queue, will be caught
4747 $cust_main->bill_and_collect( %args );
4750 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4752 Like queued_bill, but instead of C<bill_and_collect>, just runs the
4753 C<collect> part. This is used in batch tax calculation, where invoice
4754 generation and collection events have to be completely separated.
4758 sub queued_collect {
4760 my $cust_main = FS::cust_main->by_key($args{'custnum'});
4762 $cust_main->collect(%args);
4765 sub process_bill_and_collect {
4768 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4769 or die "custnum '$param->{custnum}' not found!\n";
4770 $param->{'job'} = $job;
4771 $param->{'fatal'} = 1; # runs from job queue, will be caught
4772 $param->{'retry'} = 1;
4774 $cust_main->bill_and_collect( %$param );
4777 #starting to take quite a while for big dbs
4778 # (JRNL: journaled so it only happens once per database)
4779 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
4780 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
4781 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
4782 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
4783 # JRNL leading/trailing spaces in first, last, company
4784 # JRNL migrate to cust_payby
4785 # - otaker upgrade? journal and call it good? (double check to make sure
4786 # we're not still setting otaker here)
4788 #only going to get worse with new location stuff...
4790 sub _upgrade_data { #class method
4791 my ($class, %opts) = @_;
4794 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4797 #this seems to be the only expensive one.. why does it take so long?
4798 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
4800 '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';
4801 FS::upgrade_journal->set_done('cust_main__signupdate');
4804 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
4806 # fix yyyy-m-dd formatted paydates
4807 if ( driver_name =~ /^mysql/i ) {
4809 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4810 } else { # the SQL standard
4812 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4814 FS::upgrade_journal->set_done('cust_main__paydate');
4817 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
4819 push @statements, #fix the weird BILL with a cc# in payinfo problem
4821 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
4823 FS::upgrade_journal->set_done('cust_main__payinfo');
4828 foreach my $sql ( @statements ) {
4829 my $sth = dbh->prepare($sql) or die dbh->errstr;
4830 $sth->execute or die $sth->errstr;
4831 #warn ( (time - $t). " seconds\n" );
4835 local($ignore_expired_card) = 1;
4836 local($ignore_banned_card) = 1;
4837 local($skip_fuzzyfiles) = 1;
4838 local($import) = 1; #prevent automatic geocoding (need its own variable?)
4840 FS::cust_main::Location->_upgrade_data(%opts);
4842 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
4844 foreach my $cust_main ( qsearch({
4845 'table' => 'cust_main',
4847 'extra_sql' => 'WHERE '.
4849 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
4850 qw( first last company )
4853 my $error = $cust_main->replace;
4854 die $error if $error;
4857 FS::upgrade_journal->set_done('cust_main__trimspaces');
4861 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
4863 #we don't want to decrypt them, just stuff them as-is into cust_payby
4864 local(@encrypted_fields) = ();
4866 local($FS::cust_payby::ignore_expired_card) = 1;
4867 local($FS::cust_payby::ignore_banned_card) = 1;
4869 my @payfields = qw( payby payinfo paycvv paymask
4870 paydate paystart_month paystart_year payissue
4871 payname paystate paytype payip
4874 my $search = new FS::Cursor {
4875 'table' => 'cust_main',
4876 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
4879 while (my $cust_main = $search->fetch) {
4881 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
4883 my $cust_payby = new FS::cust_payby {
4884 'custnum' => $cust_main->custnum,
4886 map { $_ => $cust_main->$_(); } @payfields
4889 my $error = $cust_payby->insert;
4890 die $error if $error;
4894 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
4896 $cust_main->invoice_attn( $cust_main->payname )
4897 if $cust_main->payby eq 'BILL' && $cust_main->payname;
4898 $cust_main->po_number( $cust_main->payinfo )
4899 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
4901 $cust_main->setfield($_, '') foreach @payfields;
4902 my $error = $cust_main->replace;
4903 die "Error upgradging payment information for custnum ".
4904 $cust_main->custnum. ": $error"
4909 FS::upgrade_journal->set_done('cust_main__cust_payby');
4912 $class->_upgrade_otaker(%opts);
4922 The delete method should possibly take an FS::cust_main object reference
4923 instead of a scalar customer number.
4925 Bill and collect options should probably be passed as references instead of a
4928 There should probably be a configuration file with a list of allowed credit
4931 No multiple currency support (probably a larger project than just this module).
4933 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4935 Birthdates rely on negative epoch values.
4937 The payby for card/check batches is broken. With mixed batching, bad
4940 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4944 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4945 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4946 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.