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 $cust_pkg_ref = '';
3135 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3137 if ( ref( $_[0] ) ) {
3138 $amount = $_[0]->{amount};
3139 $setup_cost = $_[0]->{setup_cost};
3140 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3141 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3142 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3143 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3144 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3145 : '$'. sprintf("%.2f",$amount);
3146 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3147 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3148 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3149 $additional = $_[0]->{additional} || [];
3150 $taxproduct = $_[0]->{taxproductnum};
3151 $override = { '' => $_[0]->{tax_override} };
3152 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3153 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3154 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3155 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3161 $pkg = @_ ? shift : 'One-time charge';
3162 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3164 $taxclass = @_ ? shift : '';
3168 local $SIG{HUP} = 'IGNORE';
3169 local $SIG{INT} = 'IGNORE';
3170 local $SIG{QUIT} = 'IGNORE';
3171 local $SIG{TERM} = 'IGNORE';
3172 local $SIG{TSTP} = 'IGNORE';
3173 local $SIG{PIPE} = 'IGNORE';
3175 my $oldAutoCommit = $FS::UID::AutoCommit;
3176 local $FS::UID::AutoCommit = 0;
3179 my $part_pkg = new FS::part_pkg ( {
3181 'comment' => $comment,
3185 'classnum' => ( $classnum ? $classnum : '' ),
3186 'setuptax' => $setuptax,
3187 'taxclass' => $taxclass,
3188 'taxproductnum' => $taxproduct,
3189 'setup_cost' => $setup_cost,
3192 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3193 ( 0 .. @$additional - 1 )
3195 'additional_count' => scalar(@$additional),
3196 'setup_fee' => $amount,
3199 my $error = $part_pkg->insert( options => \%options,
3200 tax_overrides => $override,
3203 $dbh->rollback if $oldAutoCommit;
3207 my $pkgpart = $part_pkg->pkgpart;
3208 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3209 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3210 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3211 $error = $type_pkgs->insert;
3213 $dbh->rollback if $oldAutoCommit;
3218 my $cust_pkg = new FS::cust_pkg ( {
3219 'custnum' => $self->custnum,
3220 'pkgpart' => $pkgpart,
3221 'quantity' => $quantity,
3222 'start_date' => $start_date,
3223 'no_auto' => $no_auto,
3224 'locationnum'=> $locationnum,
3227 $error = $cust_pkg->insert;
3229 $dbh->rollback if $oldAutoCommit;
3231 } elsif ( $cust_pkg_ref ) {
3232 ${$cust_pkg_ref} = $cust_pkg;
3236 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3237 'pkg_list' => [ $cust_pkg ],
3240 $dbh->rollback if $oldAutoCommit;
3245 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3250 #=item charge_postal_fee
3252 #Applies a one time charge this customer. If there is an error,
3253 #returns the error, returns the cust_pkg charge object or false
3254 #if there was no charge.
3258 # This should be a customer event. For that to work requires that bill
3259 # also be a customer event.
3261 sub charge_postal_fee {
3264 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3265 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3267 my $cust_pkg = new FS::cust_pkg ( {
3268 'custnum' => $self->custnum,
3269 'pkgpart' => $pkgpart,
3273 my $error = $cust_pkg->insert;
3274 $error ? $error : $cust_pkg;
3277 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3279 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3281 Optionally, a list or hashref of additional arguments to the qsearch call can
3288 my $opt = ref($_[0]) ? shift : { @_ };
3290 #return $self->num_cust_bill unless wantarray || keys %$opt;
3292 $opt->{'table'} = 'cust_bill';
3293 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3294 $opt->{'hashref'}{'custnum'} = $self->custnum;
3295 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3297 map { $_ } #behavior of sort undefined in scalar context
3298 sort { $a->_date <=> $b->_date }
3302 =item open_cust_bill
3304 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3309 sub open_cust_bill {
3313 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3319 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3321 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3325 sub legacy_cust_bill {
3328 #return $self->num_legacy_cust_bill unless wantarray;
3330 map { $_ } #behavior of sort undefined in scalar context
3331 sort { $a->_date <=> $b->_date }
3332 qsearch({ 'table' => 'legacy_cust_bill',
3333 'hashref' => { 'custnum' => $self->custnum, },
3334 'order_by' => 'ORDER BY _date ASC',
3338 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3340 Returns all the statements (see L<FS::cust_statement>) for this customer.
3342 Optionally, a list or hashref of additional arguments to the qsearch call can
3347 =item cust_bill_void
3349 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3353 sub cust_bill_void {
3356 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3357 sort { $a->_date <=> $b->_date }
3358 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3361 sub cust_statement {
3363 my $opt = ref($_[0]) ? shift : { @_ };
3365 #return $self->num_cust_statement unless wantarray || keys %$opt;
3367 $opt->{'table'} = 'cust_statement';
3368 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3369 $opt->{'hashref'}{'custnum'} = $self->custnum;
3370 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3372 map { $_ } #behavior of sort undefined in scalar context
3373 sort { $a->_date <=> $b->_date }
3377 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3379 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3381 Optionally, a list or hashref of additional arguments to the qsearch call can
3382 be passed following the SVCDB.
3389 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3390 warn "$me svc_x requires a svcdb";
3393 my $opt = ref($_[0]) ? shift : { @_ };
3395 $opt->{'table'} = $svcdb;
3396 $opt->{'addl_from'} =
3397 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3398 ($opt->{'addl_from'} || '');
3400 my $custnum = $self->custnum;
3401 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3402 my $where = "cust_pkg.custnum = $custnum";
3404 my $extra_sql = $opt->{'extra_sql'} || '';
3405 if ( keys %{ $opt->{'hashref'} } ) {
3406 $extra_sql = " AND $where $extra_sql";
3409 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3410 $extra_sql = "WHERE $where AND $1";
3413 $extra_sql = "WHERE $where $extra_sql";
3416 $opt->{'extra_sql'} = $extra_sql;
3421 # required for use as an eventtable;
3424 $self->svc_x('svc_acct', @_);
3429 Returns all the credits (see L<FS::cust_credit>) for this customer.
3435 map { $_ } #return $self->num_cust_credit unless wantarray;
3436 sort { $a->_date <=> $b->_date }
3437 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3440 =item cust_credit_pkgnum
3442 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3443 package when using experimental package balances.
3447 sub cust_credit_pkgnum {
3448 my( $self, $pkgnum ) = @_;
3449 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3450 sort { $a->_date <=> $b->_date }
3451 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3452 'pkgnum' => $pkgnum,
3457 =item cust_credit_void
3459 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3463 sub cust_credit_void {
3466 sort { $a->_date <=> $b->_date }
3467 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3472 Returns all the payments (see L<FS::cust_pay>) for this customer.
3478 my $opt = ref($_[0]) ? shift : { @_ };
3480 return $self->num_cust_pay unless wantarray || keys %$opt;
3482 $opt->{'table'} = 'cust_pay';
3483 $opt->{'hashref'}{'custnum'} = $self->custnum;
3485 map { $_ } #behavior of sort undefined in scalar context
3486 sort { $a->_date <=> $b->_date }
3493 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3494 called automatically when the cust_pay method is used in a scalar context.
3500 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3501 my $sth = dbh->prepare($sql) or die dbh->errstr;
3502 $sth->execute($self->custnum) or die $sth->errstr;
3503 $sth->fetchrow_arrayref->[0];
3506 =item unapplied_cust_pay
3508 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3512 sub unapplied_cust_pay {
3516 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3522 =item cust_pay_pkgnum
3524 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3525 package when using experimental package balances.
3529 sub cust_pay_pkgnum {
3530 my( $self, $pkgnum ) = @_;
3531 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3532 sort { $a->_date <=> $b->_date }
3533 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3534 'pkgnum' => $pkgnum,
3541 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3547 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3548 sort { $a->_date <=> $b->_date }
3549 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3552 =item cust_pay_pending
3554 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3555 (without status "done").
3559 sub cust_pay_pending {
3561 return $self->num_cust_pay_pending unless wantarray;
3562 sort { $a->_date <=> $b->_date }
3563 qsearch( 'cust_pay_pending', {
3564 'custnum' => $self->custnum,
3565 'status' => { op=>'!=', value=>'done' },
3570 =item cust_pay_pending_attempt
3572 Returns all payment attempts / declined payments for this customer, as pending
3573 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3574 a corresponding payment (see L<FS::cust_pay>).
3578 sub cust_pay_pending_attempt {
3580 return $self->num_cust_pay_pending_attempt unless wantarray;
3581 sort { $a->_date <=> $b->_date }
3582 qsearch( 'cust_pay_pending', {
3583 'custnum' => $self->custnum,
3590 =item num_cust_pay_pending
3592 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3593 customer (without status "done"). Also called automatically when the
3594 cust_pay_pending method is used in a scalar context.
3598 sub num_cust_pay_pending {
3601 " SELECT COUNT(*) FROM cust_pay_pending ".
3602 " WHERE custnum = ? AND status != 'done' ",
3607 =item num_cust_pay_pending_attempt
3609 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3610 customer, with status "done" but without a corresp. Also called automatically when the
3611 cust_pay_pending method is used in a scalar context.
3615 sub num_cust_pay_pending_attempt {
3618 " SELECT COUNT(*) FROM cust_pay_pending ".
3619 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3626 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3632 map { $_ } #return $self->num_cust_refund unless wantarray;
3633 sort { $a->_date <=> $b->_date }
3634 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3637 =item display_custnum
3639 Returns the displayed customer number for this customer: agent_custid if
3640 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3644 sub display_custnum {
3647 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3648 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3649 if ( $special eq 'CoStAg' ) {
3650 $prefix = uc( join('',
3652 ($self->state =~ /^(..)/),
3653 $prefix || ($self->agent->agent =~ /^(..)/)
3656 elsif ( $special eq 'CoStCl' ) {
3657 $prefix = uc( join('',
3659 ($self->state =~ /^(..)/),
3660 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3663 # add any others here if needed
3666 my $length = $conf->config('cust_main-custnum-display_length');
3667 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3668 return $self->agent_custid;
3669 } elsif ( $prefix ) {
3670 $length = 8 if !defined($length);
3672 sprintf('%0'.$length.'d', $self->custnum)
3673 } elsif ( $length ) {
3674 return sprintf('%0'.$length.'d', $self->custnum);
3676 return $self->custnum;
3682 Returns a name string for this customer, either "Company (Last, First)" or
3689 my $name = $self->contact;
3690 $name = $self->company. " ($name)" if $self->company;
3694 =item service_contact
3696 Returns the L<FS::contact> object for this customer that has the 'Service'
3697 contact class, or undef if there is no such contact. Deprecated; don't use
3702 sub service_contact {
3704 if ( !exists($self->{service_contact}) ) {
3705 my $classnum = $self->scalar_sql(
3706 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3707 ) || 0; #if it's zero, qsearchs will return nothing
3708 my $cust_contact = qsearchs('cust_contact', {
3709 'classnum' => $classnum,
3710 'custnum' => $self->custnum,
3712 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3714 $self->{service_contact};
3719 Returns a name string for this (service/shipping) contact, either
3720 "Company (Last, First)" or "Last, First".
3727 my $name = $self->ship_contact;
3728 $name = $self->company. " ($name)" if $self->company;
3734 Returns a name string for this customer, either "Company" or "First Last".
3740 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3743 =item ship_name_short
3745 Returns a name string for this (service/shipping) contact, either "Company"
3750 sub ship_name_short {
3752 $self->service_contact
3753 ? $self->ship_contact_firstlast
3759 Returns this customer's full (billing) contact name only, "Last, First"
3765 $self->get('last'). ', '. $self->first;
3770 Returns this customer's full (shipping) contact name only, "Last, First"
3776 my $contact = $self->service_contact || $self;
3777 $contact->get('last') . ', ' . $contact->get('first');
3780 =item contact_firstlast
3782 Returns this customers full (billing) contact name only, "First Last".
3786 sub contact_firstlast {
3788 $self->first. ' '. $self->get('last');
3791 =item ship_contact_firstlast
3793 Returns this customer's full (shipping) contact name only, "First Last".
3797 sub ship_contact_firstlast {
3799 my $contact = $self->service_contact || $self;
3800 $contact->get('first') . ' '. $contact->get('last');
3803 #XXX this doesn't work in 3.x+
3806 #Returns this customer's full country name
3812 # code2country($self->country);
3815 sub bill_country_full {
3817 code2country($self->bill_location->country);
3820 sub ship_country_full {
3822 code2country($self->ship_location->country);
3825 =item county_state_county [ PREFIX ]
3827 Returns a string consisting of just the county, state and country.
3831 sub county_state_country {
3834 if ( @_ && $_[0] && $self->has_ship_address ) {
3835 $locationnum = $self->ship_locationnum;
3837 $locationnum = $self->bill_locationnum;
3839 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3840 $cust_location->county_state_country;
3843 =item geocode DATA_VENDOR
3845 Returns a value for the customer location as encoded by DATA_VENDOR.
3846 Currently this only makes sense for "CCH" as DATA_VENDOR.
3854 Returns a status string for this customer, currently:
3860 No packages have ever been ordered. Displayed as "No packages".
3864 Recurring packages all are new (not yet billed).
3868 One or more recurring packages is active.
3872 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3876 All non-cancelled recurring packages are suspended.
3880 All recurring packages are cancelled.
3884 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3885 cust_main-status_module configuration option.
3889 sub status { shift->cust_status(@_); }
3893 for my $status ( FS::cust_main->statuses() ) {
3894 my $method = $status.'_sql';
3895 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3896 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3897 $sth->execute( ($self->custnum) x $numnum )
3898 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3899 return $status if $sth->fetchrow_arrayref->[0];
3903 =item is_status_delay_cancel
3905 Returns true if customer status is 'suspended'
3906 and all suspended cust_pkg return true for
3907 cust_pkg->is_status_delay_cancel.
3909 This is not a real status, this only meant for hacking display
3910 values, because otherwise treating the customer as suspended is
3911 really the whole point of the delay_cancel option.
3915 sub is_status_delay_cancel {
3917 return 0 unless $self->status eq 'suspended';
3918 foreach my $cust_pkg ($self->ncancelled_pkgs) {
3919 return 0 unless $cust_pkg->is_status_delay_cancel;
3924 =item ucfirst_cust_status
3926 =item ucfirst_status
3928 Deprecated, use the cust_status_label method instead.
3930 Returns the status with the first character capitalized.
3934 sub ucfirst_status {
3935 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3936 local($ucfirst_nowarn) = 1;
3937 shift->ucfirst_cust_status(@_);
3940 sub ucfirst_cust_status {
3941 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3943 ucfirst($self->cust_status);
3946 =item cust_status_label
3950 Returns the display label for this status.
3954 sub status_label { shift->cust_status_label(@_); }
3956 sub cust_status_label {
3958 __PACKAGE__->statuslabels->{$self->cust_status};
3963 Returns a hex triplet color string for this customer's status.
3967 sub statuscolor { shift->cust_statuscolor(@_); }
3969 sub cust_statuscolor {
3971 __PACKAGE__->statuscolors->{$self->cust_status};
3974 =item tickets [ STATUS ]
3976 Returns an array of hashes representing the customer's RT tickets.
3978 An optional status (or arrayref or hashref of statuses) may be specified.
3984 my $status = ( @_ && $_[0] ) ? shift : '';
3986 my $num = $conf->config('cust_main-max_tickets') || 10;
3989 if ( $conf->config('ticket_system') ) {
3990 unless ( $conf->config('ticket_system-custom_priority_field') ) {
3992 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4001 foreach my $priority (
4002 $conf->config('ticket_system-custom_priority_field-values'), ''
4004 last if scalar(@tickets) >= $num;
4006 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4007 $num - scalar(@tickets),
4018 # Return services representing svc_accts in customer support packages
4019 sub support_services {
4021 my %packages = map { $_ => 1 } $conf->config('support_packages');
4023 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4024 grep { $_->part_svc->svcdb eq 'svc_acct' }
4025 map { $_->cust_svc }
4026 grep { exists $packages{ $_->pkgpart } }
4027 $self->ncancelled_pkgs;
4031 # Return a list of latitude/longitude for one of the services (if any)
4032 sub service_coordinates {
4036 grep { $_->latitude && $_->longitude }
4038 map { $_->cust_svc }
4039 $self->ncancelled_pkgs;
4041 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4046 Returns a masked version of the named field
4051 my ($self,$field) = @_;
4055 'x'x(length($self->getfield($field))-4).
4056 substr($self->getfield($field), (length($self->getfield($field))-4));
4062 =head1 CLASS METHODS
4068 Class method that returns the list of possible status strings for customers
4069 (see L<the status method|/status>). For example:
4071 @statuses = FS::cust_main->statuses();
4077 keys %{ $self->statuscolors };
4080 =item cust_status_sql
4082 Returns an SQL fragment to determine the status of a cust_main record, as a
4087 sub cust_status_sql {
4089 for my $status ( FS::cust_main->statuses() ) {
4090 my $method = $status.'_sql';
4091 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4100 Returns an SQL expression identifying prospective cust_main records (customers
4101 with no packages ever ordered)
4105 use vars qw($select_count_pkgs);
4106 $select_count_pkgs =
4107 "SELECT COUNT(*) FROM cust_pkg
4108 WHERE cust_pkg.custnum = cust_main.custnum";
4110 sub select_count_pkgs_sql {
4115 " 0 = ( $select_count_pkgs ) ";
4120 Returns an SQL expression identifying ordered cust_main records (customers with
4121 no active packages, but recurring packages not yet setup or one time charges
4127 FS::cust_main->none_active_sql.
4128 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4133 Returns an SQL expression identifying active cust_main records (customers with
4134 active recurring packages).
4139 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4142 =item none_active_sql
4144 Returns an SQL expression identifying cust_main records with no active
4145 recurring packages. This includes customers of status prospect, ordered,
4146 inactive, and suspended.
4150 sub none_active_sql {
4151 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4156 Returns an SQL expression identifying inactive cust_main records (customers with
4157 no active recurring packages, but otherwise unsuspended/uncancelled).
4162 FS::cust_main->none_active_sql.
4163 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4169 Returns an SQL expression identifying suspended cust_main records.
4174 sub suspended_sql { susp_sql(@_); }
4176 FS::cust_main->none_active_sql.
4177 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4183 Returns an SQL expression identifying cancelled cust_main records.
4187 sub cancel_sql { shift->cancelled_sql(@_); }
4190 =item uncancelled_sql
4192 Returns an SQL expression identifying un-cancelled cust_main records.
4196 sub uncancelled_sql { uncancel_sql(@_); }
4197 sub uncancel_sql { "
4198 ( 0 < ( $select_count_pkgs
4199 AND ( cust_pkg.cancel IS NULL
4200 OR cust_pkg.cancel = 0
4203 OR 0 = ( $select_count_pkgs )
4209 Returns an SQL fragment to retreive the balance.
4214 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4215 WHERE cust_bill.custnum = cust_main.custnum )
4216 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4217 WHERE cust_pay.custnum = cust_main.custnum )
4218 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4219 WHERE cust_credit.custnum = cust_main.custnum )
4220 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4221 WHERE cust_refund.custnum = cust_main.custnum )
4224 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4226 Returns an SQL fragment to retreive the balance for this customer, optionally
4227 considering invoices with date earlier than START_TIME, and not
4228 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4229 total_unapplied_payments).
4231 Times are specified as SQL fragments or numeric
4232 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4233 L<Date::Parse> for conversion functions. The empty string can be passed
4234 to disable that time constraint completely.
4236 Available options are:
4240 =item unapplied_date
4242 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)
4247 set to true to remove all customer comparison clauses, for totals
4252 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4257 JOIN clause (typically used with the total option)
4261 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4262 time will be ignored. Note that START_TIME and END_TIME only limit the date
4263 range for invoices and I<unapplied> payments, credits, and refunds.
4269 sub balance_date_sql {
4270 my( $class, $start, $end, %opt ) = @_;
4272 my $cutoff = $opt{'cutoff'};
4274 my $owed = FS::cust_bill->owed_sql($cutoff);
4275 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4276 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4277 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4279 my $j = $opt{'join'} || '';
4281 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4282 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4283 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4284 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4286 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4287 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4288 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4289 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4294 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4296 Returns an SQL fragment to retreive the total unapplied payments for this
4297 customer, only considering payments with date earlier than START_TIME, and
4298 optionally not later than END_TIME.
4300 Times are specified as SQL fragments or numeric
4301 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4302 L<Date::Parse> for conversion functions. The empty string can be passed
4303 to disable that time constraint completely.
4305 Available options are:
4309 sub unapplied_payments_date_sql {
4310 my( $class, $start, $end, %opt ) = @_;
4312 my $cutoff = $opt{'cutoff'};
4314 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4316 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4317 'unapplied_date'=>1 );
4319 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4322 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4324 Helper method for balance_date_sql; name (and usage) subject to change
4325 (suggestions welcome).
4327 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4328 cust_refund, cust_credit or cust_pay).
4330 If TABLE is "cust_bill" or the unapplied_date option is true, only
4331 considers records with date earlier than START_TIME, and optionally not
4332 later than END_TIME .
4336 sub _money_table_where {
4337 my( $class, $table, $start, $end, %opt ) = @_;
4340 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4341 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4342 push @where, "$table._date <= $start" if defined($start) && length($start);
4343 push @where, "$table._date > $end" if defined($end) && length($end);
4345 push @where, @{$opt{'where'}} if $opt{'where'};
4346 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4352 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4353 use FS::cust_main::Search;
4356 FS::cust_main::Search->search(@_);
4365 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4367 Deprecated. Use event notification and message templates
4368 (L<FS::msg_template>) instead.
4370 Sends a templated email notification to the customer (see L<Text::Template>).
4372 OPTIONS is a hash and may include
4374 I<from> - the email sender (default is invoice_from)
4376 I<to> - comma-separated scalar or arrayref of recipients
4377 (default is invoicing_list)
4379 I<subject> - The subject line of the sent email notification
4380 (default is "Notice from company_name")
4382 I<extra_fields> - a hashref of name/value pairs which will be substituted
4385 The following variables are vavailable in the template.
4387 I<$first> - the customer first name
4388 I<$last> - the customer last name
4389 I<$company> - the customer company
4390 I<$payby> - a description of the method of payment for the customer
4391 # would be nice to use FS::payby::shortname
4392 I<$payinfo> - the account information used to collect for this customer
4393 I<$expdate> - the expiration of the customer payment in seconds from epoch
4398 my ($self, $template, %options) = @_;
4400 return unless $conf->exists($template);
4402 my $from = $conf->invoice_from_full($self->agentnum)
4403 if $conf->exists('invoice_from', $self->agentnum);
4404 $from = $options{from} if exists($options{from});
4406 my $to = join(',', $self->invoicing_list_emailonly);
4407 $to = $options{to} if exists($options{to});
4409 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4410 if $conf->exists('company_name', $self->agentnum);
4411 $subject = $options{subject} if exists($options{subject});
4413 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4414 SOURCE => [ map "$_\n",
4415 $conf->config($template)]
4417 or die "can't create new Text::Template object: Text::Template::ERROR";
4418 $notify_template->compile()
4419 or die "can't compile template: Text::Template::ERROR";
4421 $FS::notify_template::_template::company_name =
4422 $conf->config('company_name', $self->agentnum);
4423 $FS::notify_template::_template::company_address =
4424 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4426 my $paydate = $self->paydate || '2037-12-31';
4427 $FS::notify_template::_template::first = $self->first;
4428 $FS::notify_template::_template::last = $self->last;
4429 $FS::notify_template::_template::company = $self->company;
4430 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4431 my $payby = $self->payby;
4432 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4433 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4435 #credit cards expire at the end of the month/year of their exp date
4436 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4437 $FS::notify_template::_template::payby = 'credit card';
4438 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4439 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4441 }elsif ($payby eq 'COMP') {
4442 $FS::notify_template::_template::payby = 'complimentary account';
4444 $FS::notify_template::_template::payby = 'current method';
4446 $FS::notify_template::_template::expdate = $expire_time;
4448 for (keys %{$options{extra_fields}}){
4450 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4453 send_email(from => $from,
4455 subject => $subject,
4456 body => $notify_template->fill_in( PACKAGE =>
4457 'FS::notify_template::_template' ),
4462 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4464 Generates a templated notification to the customer (see L<Text::Template>).
4466 OPTIONS is a hash and may include
4468 I<extra_fields> - a hashref of name/value pairs which will be substituted
4469 into the template. These values may override values mentioned below
4470 and those from the customer record.
4472 The following variables are available in the template instead of or in addition
4473 to the fields of the customer record.
4475 I<$payby> - a description of the method of payment for the customer
4476 # would be nice to use FS::payby::shortname
4477 I<$payinfo> - the masked account information used to collect for this customer
4478 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4479 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4483 # a lot like cust_bill::print_latex
4484 sub generate_letter {
4485 my ($self, $template, %options) = @_;
4487 return unless $conf->exists($template);
4489 my $letter_template = new Text::Template
4491 SOURCE => [ map "$_\n", $conf->config($template)],
4492 DELIMITERS => [ '[@--', '--@]' ],
4494 or die "can't create new Text::Template object: Text::Template::ERROR";
4496 $letter_template->compile()
4497 or die "can't compile template: Text::Template::ERROR";
4499 my %letter_data = map { $_ => $self->$_ } $self->fields;
4500 $letter_data{payinfo} = $self->mask_payinfo;
4502 #my $paydate = $self->paydate || '2037-12-31';
4503 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4505 my $payby = $self->payby;
4506 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4507 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4509 #credit cards expire at the end of the month/year of their exp date
4510 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4511 $letter_data{payby} = 'credit card';
4512 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4513 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4515 }elsif ($payby eq 'COMP') {
4516 $letter_data{payby} = 'complimentary account';
4518 $letter_data{payby} = 'current method';
4520 $letter_data{expdate} = $expire_time;
4522 for (keys %{$options{extra_fields}}){
4523 $letter_data{$_} = $options{extra_fields}->{$_};
4526 unless(exists($letter_data{returnaddress})){
4527 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4528 $self->agent_template)
4530 if ( length($retadd) ) {
4531 $letter_data{returnaddress} = $retadd;
4532 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4533 $letter_data{returnaddress} =
4534 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4538 ( $conf->config('company_name', $self->agentnum),
4539 $conf->config('company_address', $self->agentnum),
4543 $letter_data{returnaddress} = '~';
4547 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4549 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4551 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4553 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4557 ) or die "can't open temp file: $!\n";
4558 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4559 or die "can't write temp file: $!\n";
4561 $letter_data{'logo_file'} = $lh->filename;
4563 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4567 ) or die "can't open temp file: $!\n";
4569 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4571 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4572 return ($1, $letter_data{'logo_file'});
4576 =item print_ps TEMPLATE
4578 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4584 my($file, $lfile) = $self->generate_letter(@_);
4585 my $ps = FS::Misc::generate_ps($file);
4586 unlink($file.'.tex');
4592 =item print TEMPLATE
4594 Prints the filled in template.
4596 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4600 sub queueable_print {
4603 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4604 or die "invalid customer number: " . $opt{custnum};
4606 my $error = $self->print( { 'template' => $opt{template} } );
4607 die $error if $error;
4611 my ($self, $template) = (shift, shift);
4613 [ $self->print_ps($template) ],
4614 'agentnum' => $self->agentnum,
4618 #these three subs should just go away once agent stuff is all config overrides
4620 sub agent_template {
4622 $self->_agent_plandata('agent_templatename');
4625 sub agent_invoice_from {
4627 $self->_agent_plandata('agent_invoice_from');
4630 sub _agent_plandata {
4631 my( $self, $option ) = @_;
4633 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4634 #agent-specific Conf
4636 use FS::part_event::Condition;
4638 my $agentnum = $self->agentnum;
4640 my $regexp = regexp_sql();
4642 my $part_event_option =
4644 'select' => 'part_event_option.*',
4645 'table' => 'part_event_option',
4647 LEFT JOIN part_event USING ( eventpart )
4648 LEFT JOIN part_event_option AS peo_agentnum
4649 ON ( part_event.eventpart = peo_agentnum.eventpart
4650 AND peo_agentnum.optionname = 'agentnum'
4651 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4653 LEFT JOIN part_event_condition
4654 ON ( part_event.eventpart = part_event_condition.eventpart
4655 AND part_event_condition.conditionname = 'cust_bill_age'
4657 LEFT JOIN part_event_condition_option
4658 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4659 AND part_event_condition_option.optionname = 'age'
4662 #'hashref' => { 'optionname' => $option },
4663 #'hashref' => { 'part_event_option.optionname' => $option },
4665 " WHERE part_event_option.optionname = ". dbh->quote($option).
4666 " AND action = 'cust_bill_send_agent' ".
4667 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4668 " AND peo_agentnum.optionname = 'agentnum' ".
4669 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4671 CASE WHEN part_event_condition_option.optionname IS NULL
4673 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4675 , part_event.weight".
4679 unless ( $part_event_option ) {
4680 return $self->agent->invoice_template || ''
4681 if $option eq 'agent_templatename';
4685 $part_event_option->optionvalue;
4689 sub process_o2m_qsearch {
4692 return qsearch($table, @_) unless $table eq 'contact';
4694 my $hashref = shift;
4695 my %hash = %$hashref;
4696 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4697 or die 'guru meditation #4343';
4699 qsearch({ 'table' => 'contact',
4700 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4701 'hashref' => \%hash,
4702 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4703 " cust_contact.custnum = $custnum "
4707 sub process_o2m_qsearchs {
4710 return qsearchs($table, @_) unless $table eq 'contact';
4712 my $hashref = shift;
4713 my %hash = %$hashref;
4714 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4715 or die 'guru meditation #2121';
4717 qsearchs({ 'table' => 'contact',
4718 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4719 'hashref' => \%hash,
4720 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4721 " cust_contact.custnum = $custnum "
4725 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4727 Subroutine (not a method), designed to be called from the queue.
4729 Takes a list of options and values.
4731 Pulls up the customer record via the custnum option and calls bill_and_collect.
4736 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4738 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4739 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4741 #without this errors don't get rolled back
4742 $args{'fatal'} = 1; # runs from job queue, will be caught
4744 $cust_main->bill_and_collect( %args );
4747 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4749 Like queued_bill, but instead of C<bill_and_collect>, just runs the
4750 C<collect> part. This is used in batch tax calculation, where invoice
4751 generation and collection events have to be completely separated.
4755 sub queued_collect {
4757 my $cust_main = FS::cust_main->by_key($args{'custnum'});
4759 $cust_main->collect(%args);
4762 sub process_bill_and_collect {
4765 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4766 or die "custnum '$param->{custnum}' not found!\n";
4767 $param->{'job'} = $job;
4768 $param->{'fatal'} = 1; # runs from job queue, will be caught
4769 $param->{'retry'} = 1;
4771 $cust_main->bill_and_collect( %$param );
4774 #starting to take quite a while for big dbs
4775 # (JRNL: journaled so it only happens once per database)
4776 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
4777 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
4778 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
4779 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
4780 # JRNL leading/trailing spaces in first, last, company
4781 # JRNL migrate to cust_payby
4782 # - otaker upgrade? journal and call it good? (double check to make sure
4783 # we're not still setting otaker here)
4785 #only going to get worse with new location stuff...
4787 sub _upgrade_data { #class method
4788 my ($class, %opts) = @_;
4791 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4794 #this seems to be the only expensive one.. why does it take so long?
4795 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
4797 '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';
4798 FS::upgrade_journal->set_done('cust_main__signupdate');
4801 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
4803 # fix yyyy-m-dd formatted paydates
4804 if ( driver_name =~ /^mysql/i ) {
4806 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4807 } else { # the SQL standard
4809 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4811 FS::upgrade_journal->set_done('cust_main__paydate');
4814 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
4816 push @statements, #fix the weird BILL with a cc# in payinfo problem
4818 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
4820 FS::upgrade_journal->set_done('cust_main__payinfo');
4825 foreach my $sql ( @statements ) {
4826 my $sth = dbh->prepare($sql) or die dbh->errstr;
4827 $sth->execute or die $sth->errstr;
4828 #warn ( (time - $t). " seconds\n" );
4832 local($ignore_expired_card) = 1;
4833 local($ignore_banned_card) = 1;
4834 local($skip_fuzzyfiles) = 1;
4835 local($import) = 1; #prevent automatic geocoding (need its own variable?)
4837 FS::cust_main::Location->_upgrade_data(%opts);
4839 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
4841 foreach my $cust_main ( qsearch({
4842 'table' => 'cust_main',
4844 'extra_sql' => 'WHERE '.
4846 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
4847 qw( first last company )
4850 my $error = $cust_main->replace;
4851 die $error if $error;
4854 FS::upgrade_journal->set_done('cust_main__trimspaces');
4858 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
4860 #we don't want to decrypt them, just stuff them as-is into cust_payby
4861 local(@encrypted_fields) = ();
4863 local($FS::cust_payby::ignore_expired_card) = 1;
4864 local($FS::cust_payby::ignore_banned_card) = 1;
4866 my @payfields = qw( payby payinfo paycvv paymask
4867 paydate paystart_month paystart_year payissue
4868 payname paystate paytype payip
4871 my $search = new FS::Cursor {
4872 'table' => 'cust_main',
4873 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
4876 while (my $cust_main = $search->fetch) {
4878 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
4880 my $cust_payby = new FS::cust_payby {
4881 'custnum' => $cust_main->custnum,
4883 map { $_ => $cust_main->$_(); } @payfields
4886 my $error = $cust_payby->insert;
4887 die $error if $error;
4891 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
4893 $cust_main->invoice_attn( $cust_main->payname )
4894 if $cust_main->payby eq 'BILL' && $cust_main->payname;
4895 $cust_main->po_number( $cust_main->payinfo )
4896 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
4898 $cust_main->setfield($_, '') foreach @payfields;
4899 my $error = $cust_main->replace;
4900 die "Error upgradging payment information for custnum ".
4901 $cust_main->custnum. ": $error"
4906 FS::upgrade_journal->set_done('cust_main__cust_payby');
4909 $class->_upgrade_otaker(%opts);
4919 The delete method should possibly take an FS::cust_main object reference
4920 instead of a scalar customer number.
4922 Bill and collect options should probably be passed as references instead of a
4925 There should probably be a configuration file with a list of allowed credit
4928 No multiple currency support (probably a larger project than just this module).
4930 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4932 Birthdates rely on negative epoch values.
4934 The payby for card/check batches is broken. With mixed batching, bad
4937 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4941 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4942 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4943 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.